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 DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace, MultiWorkspaceEvent, Sidebar,
31 SidebarHandle, ToggleWorkspaceSidebar,
32};
33pub use path_list::{PathList, SerializedPathList};
34pub use toast_layer::{ToastAction, ToastLayer, ToastView};
35
36use anyhow::{Context as _, Result, anyhow};
37use client::{
38 ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
39 proto::{self, ErrorCode, PanelId, PeerId},
40};
41use collections::{HashMap, HashSet, hash_map};
42use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
43use fs::Fs;
44use futures::{
45 Future, FutureExt, StreamExt,
46 channel::{
47 mpsc::{self, UnboundedReceiver, UnboundedSender},
48 oneshot,
49 },
50 future::{Shared, try_join_all},
51};
52use gpui::{
53 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
54 CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
55 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
56 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
57 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
58 WindowOptions, actions, canvas, point, relative, size, transparent_black,
59};
60pub use history_manager::*;
61pub use item::{
62 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
63 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
64};
65use itertools::Itertools;
66use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
67pub use modal_layer::*;
68use node_runtime::NodeRuntime;
69use notifications::{
70 DetachAndPromptErr, Notifications, dismiss_app_notification,
71 simple_message_notification::MessageNotification,
72};
73pub use pane::*;
74pub use pane_group::{
75 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
76 SplitDirection,
77};
78use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
79pub use persistence::{
80 WorkspaceDb, delete_unloaded_items,
81 model::{
82 DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
83 SessionWorkspace,
84 },
85 read_serialized_multi_workspaces, resolve_worktree_workspaces,
86};
87use postage::stream::Stream;
88use project::{
89 DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
90 WorktreeSettings,
91 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
92 project_settings::ProjectSettings,
93 toolchain_store::ToolchainStoreEvent,
94 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
95};
96use remote::{
97 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
98 remote_client::ConnectionIdentifier,
99};
100use schemars::JsonSchema;
101use serde::Deserialize;
102use session::AppSession;
103use settings::{
104 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
105};
106
107use sqlez::{
108 bindable::{Bind, Column, StaticColumnCount},
109 statement::Statement,
110};
111use status_bar::StatusBar;
112pub use status_bar::StatusItemView;
113use std::{
114 any::TypeId,
115 borrow::Cow,
116 cell::RefCell,
117 cmp,
118 collections::VecDeque,
119 env,
120 hash::Hash,
121 path::{Path, PathBuf},
122 process::ExitStatus,
123 rc::Rc,
124 sync::{
125 Arc, LazyLock, Weak,
126 atomic::{AtomicBool, AtomicUsize},
127 },
128 time::Duration,
129};
130use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
131use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
132pub use toolbar::{
133 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
134};
135pub use ui;
136use ui::{Window, prelude::*};
137use util::{
138 ResultExt, TryFutureExt,
139 paths::{PathStyle, SanitizedPath},
140 rel_path::RelPath,
141 serde::default_true,
142};
143use uuid::Uuid;
144pub use workspace_settings::{
145 AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
146 WorkspaceSettings,
147};
148use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
149
150use crate::{item::ItemBufferKind, notifications::NotificationId};
151use crate::{
152 persistence::{
153 SerializedAxis,
154 model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
155 },
156 security_modal::SecurityModal,
157};
158
159pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
160
161static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
162 env::var("ZED_WINDOW_SIZE")
163 .ok()
164 .as_deref()
165 .and_then(parse_pixel_size_env_var)
166});
167
168static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
169 env::var("ZED_WINDOW_POSITION")
170 .ok()
171 .as_deref()
172 .and_then(parse_pixel_position_env_var)
173});
174
175pub trait TerminalProvider {
176 fn spawn(
177 &self,
178 task: SpawnInTerminal,
179 window: &mut Window,
180 cx: &mut App,
181 ) -> Task<Option<Result<ExitStatus>>>;
182}
183
184pub trait DebuggerProvider {
185 // `active_buffer` is used to resolve build task's name against language-specific tasks.
186 fn start_session(
187 &self,
188 definition: DebugScenario,
189 task_context: SharedTaskContext,
190 active_buffer: Option<Entity<Buffer>>,
191 worktree_id: Option<WorktreeId>,
192 window: &mut Window,
193 cx: &mut App,
194 );
195
196 fn spawn_task_or_modal(
197 &self,
198 workspace: &mut Workspace,
199 action: &Spawn,
200 window: &mut Window,
201 cx: &mut Context<Workspace>,
202 );
203
204 fn task_scheduled(&self, cx: &mut App);
205 fn debug_scenario_scheduled(&self, cx: &mut App);
206 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
207
208 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
209}
210
211/// Opens a file or directory.
212#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
213#[action(namespace = workspace)]
214pub struct Open {
215 /// When true, opens in a new window. When false, adds to the current
216 /// window as a new workspace (multi-workspace).
217 #[serde(default = "Open::default_create_new_window")]
218 pub create_new_window: bool,
219}
220
221impl Open {
222 pub const DEFAULT: Self = Self {
223 create_new_window: true,
224 };
225
226 /// Used by `#[serde(default)]` on the `create_new_window` field so that
227 /// the serde default and `Open::DEFAULT` stay in sync.
228 fn default_create_new_window() -> bool {
229 Self::DEFAULT.create_new_window
230 }
231}
232
233impl Default for Open {
234 fn default() -> Self {
235 Self::DEFAULT
236 }
237}
238
239actions!(
240 workspace,
241 [
242 /// Activates the next pane in the workspace.
243 ActivateNextPane,
244 /// Activates the previous pane in the workspace.
245 ActivatePreviousPane,
246 /// Activates the last pane in the workspace.
247 ActivateLastPane,
248 /// Switches to the next window.
249 ActivateNextWindow,
250 /// Switches to the previous window.
251 ActivatePreviousWindow,
252 /// Adds a folder to the current project.
253 AddFolderToProject,
254 /// Clears all notifications.
255 ClearAllNotifications,
256 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
257 ClearNavigationHistory,
258 /// Closes the active dock.
259 CloseActiveDock,
260 /// Closes all docks.
261 CloseAllDocks,
262 /// Toggles all docks.
263 ToggleAllDocks,
264 /// Closes the current window.
265 CloseWindow,
266 /// Closes the current project.
267 CloseProject,
268 /// Opens the feedback dialog.
269 Feedback,
270 /// Follows the next collaborator in the session.
271 FollowNextCollaborator,
272 /// Moves the focused panel to the next position.
273 MoveFocusedPanelToNextPosition,
274 /// Creates a new file.
275 NewFile,
276 /// Creates a new file in a vertical split.
277 NewFileSplitVertical,
278 /// Creates a new file in a horizontal split.
279 NewFileSplitHorizontal,
280 /// Opens a new search.
281 NewSearch,
282 /// Opens a new window.
283 NewWindow,
284 /// Opens multiple files.
285 OpenFiles,
286 /// Opens the current location in terminal.
287 OpenInTerminal,
288 /// Opens the component preview.
289 OpenComponentPreview,
290 /// Reloads the active item.
291 ReloadActiveItem,
292 /// Resets the active dock to its default size.
293 ResetActiveDockSize,
294 /// Resets all open docks to their default sizes.
295 ResetOpenDocksSize,
296 /// Reloads the application
297 Reload,
298 /// Saves the current file with a new name.
299 SaveAs,
300 /// Saves without formatting.
301 SaveWithoutFormat,
302 /// Shuts down all debug adapters.
303 ShutdownDebugAdapters,
304 /// Suppresses the current notification.
305 SuppressNotification,
306 /// Toggles the bottom dock.
307 ToggleBottomDock,
308 /// Toggles centered layout mode.
309 ToggleCenteredLayout,
310 /// Toggles edit prediction feature globally for all files.
311 ToggleEditPrediction,
312 /// Toggles the left dock.
313 ToggleLeftDock,
314 /// Toggles the right dock.
315 ToggleRightDock,
316 /// Toggles zoom on the active pane.
317 ToggleZoom,
318 /// Toggles read-only mode for the active item (if supported by that item).
319 ToggleReadOnlyFile,
320 /// Zooms in on the active pane.
321 ZoomIn,
322 /// Zooms out of the active pane.
323 ZoomOut,
324 /// If any worktrees are in restricted mode, shows a modal with possible actions.
325 /// If the modal is shown already, closes it without trusting any worktree.
326 ToggleWorktreeSecurity,
327 /// Clears all trusted worktrees, placing them in restricted mode on next open.
328 /// Requires restart to take effect on already opened projects.
329 ClearTrustedWorktrees,
330 /// Stops following a collaborator.
331 Unfollow,
332 /// Restores the banner.
333 RestoreBanner,
334 /// Toggles expansion of the selected item.
335 ToggleExpandItem,
336 ]
337);
338
339/// Activates a specific pane by its index.
340#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
341#[action(namespace = workspace)]
342pub struct ActivatePane(pub usize);
343
344/// Moves an item to a specific pane by index.
345#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
346#[action(namespace = workspace)]
347#[serde(deny_unknown_fields)]
348pub struct MoveItemToPane {
349 #[serde(default = "default_1")]
350 pub destination: usize,
351 #[serde(default = "default_true")]
352 pub focus: bool,
353 #[serde(default)]
354 pub clone: bool,
355}
356
357fn default_1() -> usize {
358 1
359}
360
361/// Moves an item to a pane in the specified direction.
362#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
363#[action(namespace = workspace)]
364#[serde(deny_unknown_fields)]
365pub struct MoveItemToPaneInDirection {
366 #[serde(default = "default_right")]
367 pub direction: SplitDirection,
368 #[serde(default = "default_true")]
369 pub focus: bool,
370 #[serde(default)]
371 pub clone: bool,
372}
373
374/// Creates a new file in a split of the desired direction.
375#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
376#[action(namespace = workspace)]
377#[serde(deny_unknown_fields)]
378pub struct NewFileSplit(pub SplitDirection);
379
380fn default_right() -> SplitDirection {
381 SplitDirection::Right
382}
383
384/// Saves all open files in the workspace.
385#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
386#[action(namespace = workspace)]
387#[serde(deny_unknown_fields)]
388pub struct SaveAll {
389 #[serde(default)]
390 pub save_intent: Option<SaveIntent>,
391}
392
393/// Saves the current file with the specified options.
394#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
395#[action(namespace = workspace)]
396#[serde(deny_unknown_fields)]
397pub struct Save {
398 #[serde(default)]
399 pub save_intent: Option<SaveIntent>,
400}
401
402/// Moves Focus to the central panes in the workspace.
403#[derive(Clone, Debug, PartialEq, Eq, Action)]
404#[action(namespace = workspace)]
405pub struct FocusCenterPane;
406
407/// Closes all items and panes in the workspace.
408#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
409#[action(namespace = workspace)]
410#[serde(deny_unknown_fields)]
411pub struct CloseAllItemsAndPanes {
412 #[serde(default)]
413 pub save_intent: Option<SaveIntent>,
414}
415
416/// Closes all inactive tabs and panes in the workspace.
417#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
418#[action(namespace = workspace)]
419#[serde(deny_unknown_fields)]
420pub struct CloseInactiveTabsAndPanes {
421 #[serde(default)]
422 pub save_intent: Option<SaveIntent>,
423}
424
425/// Closes the active item across all panes.
426#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
427#[action(namespace = workspace)]
428#[serde(deny_unknown_fields)]
429pub struct CloseItemInAllPanes {
430 #[serde(default)]
431 pub save_intent: Option<SaveIntent>,
432 #[serde(default)]
433 pub close_pinned: bool,
434}
435
436/// Sends a sequence of keystrokes to the active element.
437#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
438#[action(namespace = workspace)]
439pub struct SendKeystrokes(pub String);
440
441actions!(
442 project_symbols,
443 [
444 /// Toggles the project symbols search.
445 #[action(name = "Toggle")]
446 ToggleProjectSymbols
447 ]
448);
449
450/// Toggles the file finder interface.
451#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
452#[action(namespace = file_finder, name = "Toggle")]
453#[serde(deny_unknown_fields)]
454pub struct ToggleFileFinder {
455 #[serde(default)]
456 pub separate_history: bool,
457}
458
459/// Opens a new terminal in the center.
460#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
461#[action(namespace = workspace)]
462#[serde(deny_unknown_fields)]
463pub struct NewCenterTerminal {
464 /// If true, creates a local terminal even in remote projects.
465 #[serde(default)]
466 pub local: bool,
467}
468
469/// Opens a new terminal.
470#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
471#[action(namespace = workspace)]
472#[serde(deny_unknown_fields)]
473pub struct NewTerminal {
474 /// If true, creates a local terminal even in remote projects.
475 #[serde(default)]
476 pub local: bool,
477}
478
479/// Increases size of a currently focused dock by a given amount of pixels.
480#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
481#[action(namespace = workspace)]
482#[serde(deny_unknown_fields)]
483pub struct IncreaseActiveDockSize {
484 /// For 0px parameter, uses UI font size value.
485 #[serde(default)]
486 pub px: u32,
487}
488
489/// Decreases size of a currently focused dock by a given amount of pixels.
490#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
491#[action(namespace = workspace)]
492#[serde(deny_unknown_fields)]
493pub struct DecreaseActiveDockSize {
494 /// For 0px parameter, uses UI font size value.
495 #[serde(default)]
496 pub px: u32,
497}
498
499/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
500#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
501#[action(namespace = workspace)]
502#[serde(deny_unknown_fields)]
503pub struct IncreaseOpenDocksSize {
504 /// For 0px parameter, uses UI font size value.
505 #[serde(default)]
506 pub px: u32,
507}
508
509/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
510#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
511#[action(namespace = workspace)]
512#[serde(deny_unknown_fields)]
513pub struct DecreaseOpenDocksSize {
514 /// For 0px parameter, uses UI font size value.
515 #[serde(default)]
516 pub px: u32,
517}
518
519actions!(
520 workspace,
521 [
522 /// Activates the pane to the left.
523 ActivatePaneLeft,
524 /// Activates the pane to the right.
525 ActivatePaneRight,
526 /// Activates the pane above.
527 ActivatePaneUp,
528 /// Activates the pane below.
529 ActivatePaneDown,
530 /// Swaps the current pane with the one to the left.
531 SwapPaneLeft,
532 /// Swaps the current pane with the one to the right.
533 SwapPaneRight,
534 /// Swaps the current pane with the one above.
535 SwapPaneUp,
536 /// Swaps the current pane with the one below.
537 SwapPaneDown,
538 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
539 SwapPaneAdjacent,
540 /// Move the current pane to be at the far left.
541 MovePaneLeft,
542 /// Move the current pane to be at the far right.
543 MovePaneRight,
544 /// Move the current pane to be at the very top.
545 MovePaneUp,
546 /// Move the current pane to be at the very bottom.
547 MovePaneDown,
548 ]
549);
550
551#[derive(PartialEq, Eq, Debug)]
552pub enum CloseIntent {
553 /// Quit the program entirely.
554 Quit,
555 /// Close a window.
556 CloseWindow,
557 /// Replace the workspace in an existing window.
558 ReplaceWindow,
559}
560
561#[derive(Clone)]
562pub struct Toast {
563 id: NotificationId,
564 msg: Cow<'static, str>,
565 autohide: bool,
566 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
567}
568
569impl Toast {
570 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
571 Toast {
572 id,
573 msg: msg.into(),
574 on_click: None,
575 autohide: false,
576 }
577 }
578
579 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
580 where
581 M: Into<Cow<'static, str>>,
582 F: Fn(&mut Window, &mut App) + 'static,
583 {
584 self.on_click = Some((message.into(), Arc::new(on_click)));
585 self
586 }
587
588 pub fn autohide(mut self) -> Self {
589 self.autohide = true;
590 self
591 }
592}
593
594impl PartialEq for Toast {
595 fn eq(&self, other: &Self) -> bool {
596 self.id == other.id
597 && self.msg == other.msg
598 && self.on_click.is_some() == other.on_click.is_some()
599 }
600}
601
602/// Opens a new terminal with the specified working directory.
603#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
604#[action(namespace = workspace)]
605#[serde(deny_unknown_fields)]
606pub struct OpenTerminal {
607 pub working_directory: PathBuf,
608 /// If true, creates a local terminal even in remote projects.
609 #[serde(default)]
610 pub local: bool,
611}
612
613#[derive(
614 Clone,
615 Copy,
616 Debug,
617 Default,
618 Hash,
619 PartialEq,
620 Eq,
621 PartialOrd,
622 Ord,
623 serde::Serialize,
624 serde::Deserialize,
625)]
626pub struct WorkspaceId(i64);
627
628impl WorkspaceId {
629 pub fn from_i64(value: i64) -> Self {
630 Self(value)
631 }
632}
633
634impl StaticColumnCount for WorkspaceId {}
635impl Bind for WorkspaceId {
636 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
637 self.0.bind(statement, start_index)
638 }
639}
640impl Column for WorkspaceId {
641 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
642 i64::column(statement, start_index)
643 .map(|(i, next_index)| (Self(i), next_index))
644 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
645 }
646}
647impl From<WorkspaceId> for i64 {
648 fn from(val: WorkspaceId) -> Self {
649 val.0
650 }
651}
652
653fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
654 if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
655 workspace_window
656 .update(cx, |multi_workspace, window, cx| {
657 let workspace = multi_workspace.workspace().clone();
658 workspace.update(cx, |workspace, cx| {
659 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
660 });
661 })
662 .ok();
663 } else {
664 let task = Workspace::new_local(Vec::new(), app_state.clone(), None, None, None, true, cx);
665 cx.spawn(async move |cx| {
666 let OpenResult { window, .. } = task.await?;
667 window.update(cx, |multi_workspace, window, cx| {
668 window.activate_window();
669 let workspace = multi_workspace.workspace().clone();
670 workspace.update(cx, |workspace, cx| {
671 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
672 });
673 })?;
674 anyhow::Ok(())
675 })
676 .detach_and_log_err(cx);
677 }
678}
679
680pub fn prompt_for_open_path_and_open(
681 workspace: &mut Workspace,
682 app_state: Arc<AppState>,
683 options: PathPromptOptions,
684 create_new_window: bool,
685 window: &mut Window,
686 cx: &mut Context<Workspace>,
687) {
688 let paths = workspace.prompt_for_open_path(
689 options,
690 DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
691 window,
692 cx,
693 );
694 let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
695 cx.spawn_in(window, async move |this, cx| {
696 let Some(paths) = paths.await.log_err().flatten() else {
697 return;
698 };
699 if !create_new_window {
700 if let Some(handle) = multi_workspace_handle {
701 if let Some(task) = handle
702 .update(cx, |multi_workspace, window, cx| {
703 multi_workspace.open_project(paths, window, cx)
704 })
705 .log_err()
706 {
707 task.await.log_err();
708 }
709 return;
710 }
711 }
712 if let Some(task) = this
713 .update_in(cx, |this, window, cx| {
714 this.open_workspace_for_paths(false, paths, window, cx)
715 })
716 .log_err()
717 {
718 task.await.log_err();
719 }
720 })
721 .detach();
722}
723
724pub fn init(app_state: Arc<AppState>, cx: &mut App) {
725 component::init();
726 theme_preview::init(cx);
727 toast_layer::init(cx);
728 history_manager::init(app_state.fs.clone(), cx);
729
730 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
731 .on_action(|_: &Reload, cx| reload(cx))
732 .on_action({
733 let app_state = Arc::downgrade(&app_state);
734 move |_: &Open, cx: &mut App| {
735 if let Some(app_state) = app_state.upgrade() {
736 prompt_and_open_paths(
737 app_state,
738 PathPromptOptions {
739 files: true,
740 directories: true,
741 multiple: true,
742 prompt: None,
743 },
744 cx,
745 );
746 }
747 }
748 })
749 .on_action({
750 let app_state = Arc::downgrade(&app_state);
751 move |_: &OpenFiles, cx: &mut App| {
752 let directories = cx.can_select_mixed_files_and_dirs();
753 if let Some(app_state) = app_state.upgrade() {
754 prompt_and_open_paths(
755 app_state,
756 PathPromptOptions {
757 files: true,
758 directories,
759 multiple: true,
760 prompt: None,
761 },
762 cx,
763 );
764 }
765 }
766 });
767}
768
769type BuildProjectItemFn =
770 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
771
772type BuildProjectItemForPathFn =
773 fn(
774 &Entity<Project>,
775 &ProjectPath,
776 &mut Window,
777 &mut App,
778 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
779
780#[derive(Clone, Default)]
781struct ProjectItemRegistry {
782 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
783 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
784}
785
786impl ProjectItemRegistry {
787 fn register<T: ProjectItem>(&mut self) {
788 self.build_project_item_fns_by_type.insert(
789 TypeId::of::<T::Item>(),
790 |item, project, pane, window, cx| {
791 let item = item.downcast().unwrap();
792 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
793 as Box<dyn ItemHandle>
794 },
795 );
796 self.build_project_item_for_path_fns
797 .push(|project, project_path, window, cx| {
798 let project_path = project_path.clone();
799 let is_file = project
800 .read(cx)
801 .entry_for_path(&project_path, cx)
802 .is_some_and(|entry| entry.is_file());
803 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
804 let is_local = project.read(cx).is_local();
805 let project_item =
806 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
807 let project = project.clone();
808 Some(window.spawn(cx, async move |cx| {
809 match project_item.await.with_context(|| {
810 format!(
811 "opening project path {:?}",
812 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
813 )
814 }) {
815 Ok(project_item) => {
816 let project_item = project_item;
817 let project_entry_id: Option<ProjectEntryId> =
818 project_item.read_with(cx, project::ProjectItem::entry_id);
819 let build_workspace_item = Box::new(
820 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
821 Box::new(cx.new(|cx| {
822 T::for_project_item(
823 project,
824 Some(pane),
825 project_item,
826 window,
827 cx,
828 )
829 })) as Box<dyn ItemHandle>
830 },
831 ) as Box<_>;
832 Ok((project_entry_id, build_workspace_item))
833 }
834 Err(e) => {
835 log::warn!("Failed to open a project item: {e:#}");
836 if e.error_code() == ErrorCode::Internal {
837 if let Some(abs_path) =
838 entry_abs_path.as_deref().filter(|_| is_file)
839 {
840 if let Some(broken_project_item_view) =
841 cx.update(|window, cx| {
842 T::for_broken_project_item(
843 abs_path, is_local, &e, window, cx,
844 )
845 })?
846 {
847 let build_workspace_item = Box::new(
848 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
849 cx.new(|_| broken_project_item_view).boxed_clone()
850 },
851 )
852 as Box<_>;
853 return Ok((None, build_workspace_item));
854 }
855 }
856 }
857 Err(e)
858 }
859 }
860 }))
861 });
862 }
863
864 fn open_path(
865 &self,
866 project: &Entity<Project>,
867 path: &ProjectPath,
868 window: &mut Window,
869 cx: &mut App,
870 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
871 let Some(open_project_item) = self
872 .build_project_item_for_path_fns
873 .iter()
874 .rev()
875 .find_map(|open_project_item| open_project_item(project, path, window, cx))
876 else {
877 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
878 };
879 open_project_item
880 }
881
882 fn build_item<T: project::ProjectItem>(
883 &self,
884 item: Entity<T>,
885 project: Entity<Project>,
886 pane: Option<&Pane>,
887 window: &mut Window,
888 cx: &mut App,
889 ) -> Option<Box<dyn ItemHandle>> {
890 let build = self
891 .build_project_item_fns_by_type
892 .get(&TypeId::of::<T>())?;
893 Some(build(item.into_any(), project, pane, window, cx))
894 }
895}
896
897type WorkspaceItemBuilder =
898 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
899
900impl Global for ProjectItemRegistry {}
901
902/// Registers a [ProjectItem] for the app. When opening a file, all the registered
903/// items will get a chance to open the file, starting from the project item that
904/// was added last.
905pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
906 cx.default_global::<ProjectItemRegistry>().register::<I>();
907}
908
909#[derive(Default)]
910pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
911
912struct FollowableViewDescriptor {
913 from_state_proto: fn(
914 Entity<Workspace>,
915 ViewId,
916 &mut Option<proto::view::Variant>,
917 &mut Window,
918 &mut App,
919 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
920 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
921}
922
923impl Global for FollowableViewRegistry {}
924
925impl FollowableViewRegistry {
926 pub fn register<I: FollowableItem>(cx: &mut App) {
927 cx.default_global::<Self>().0.insert(
928 TypeId::of::<I>(),
929 FollowableViewDescriptor {
930 from_state_proto: |workspace, id, state, window, cx| {
931 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
932 cx.foreground_executor()
933 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
934 })
935 },
936 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
937 },
938 );
939 }
940
941 pub fn from_state_proto(
942 workspace: Entity<Workspace>,
943 view_id: ViewId,
944 mut state: Option<proto::view::Variant>,
945 window: &mut Window,
946 cx: &mut App,
947 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
948 cx.update_default_global(|this: &mut Self, cx| {
949 this.0.values().find_map(|descriptor| {
950 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
951 })
952 })
953 }
954
955 pub fn to_followable_view(
956 view: impl Into<AnyView>,
957 cx: &App,
958 ) -> Option<Box<dyn FollowableItemHandle>> {
959 let this = cx.try_global::<Self>()?;
960 let view = view.into();
961 let descriptor = this.0.get(&view.entity_type())?;
962 Some((descriptor.to_followable_view)(&view))
963 }
964}
965
966#[derive(Copy, Clone)]
967struct SerializableItemDescriptor {
968 deserialize: fn(
969 Entity<Project>,
970 WeakEntity<Workspace>,
971 WorkspaceId,
972 ItemId,
973 &mut Window,
974 &mut Context<Pane>,
975 ) -> Task<Result<Box<dyn ItemHandle>>>,
976 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
977 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
978}
979
980#[derive(Default)]
981struct SerializableItemRegistry {
982 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
983 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
984}
985
986impl Global for SerializableItemRegistry {}
987
988impl SerializableItemRegistry {
989 fn deserialize(
990 item_kind: &str,
991 project: Entity<Project>,
992 workspace: WeakEntity<Workspace>,
993 workspace_id: WorkspaceId,
994 item_item: ItemId,
995 window: &mut Window,
996 cx: &mut Context<Pane>,
997 ) -> Task<Result<Box<dyn ItemHandle>>> {
998 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
999 return Task::ready(Err(anyhow!(
1000 "cannot deserialize {}, descriptor not found",
1001 item_kind
1002 )));
1003 };
1004
1005 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
1006 }
1007
1008 fn cleanup(
1009 item_kind: &str,
1010 workspace_id: WorkspaceId,
1011 loaded_items: Vec<ItemId>,
1012 window: &mut Window,
1013 cx: &mut App,
1014 ) -> Task<Result<()>> {
1015 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1016 return Task::ready(Err(anyhow!(
1017 "cannot cleanup {}, descriptor not found",
1018 item_kind
1019 )));
1020 };
1021
1022 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
1023 }
1024
1025 fn view_to_serializable_item_handle(
1026 view: AnyView,
1027 cx: &App,
1028 ) -> Option<Box<dyn SerializableItemHandle>> {
1029 let this = cx.try_global::<Self>()?;
1030 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
1031 Some((descriptor.view_to_serializable_item)(view))
1032 }
1033
1034 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
1035 let this = cx.try_global::<Self>()?;
1036 this.descriptors_by_kind.get(item_kind).copied()
1037 }
1038}
1039
1040pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
1041 let serialized_item_kind = I::serialized_item_kind();
1042
1043 let registry = cx.default_global::<SerializableItemRegistry>();
1044 let descriptor = SerializableItemDescriptor {
1045 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
1046 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
1047 cx.foreground_executor()
1048 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
1049 },
1050 cleanup: |workspace_id, loaded_items, window, cx| {
1051 I::cleanup(workspace_id, loaded_items, window, cx)
1052 },
1053 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
1054 };
1055 registry
1056 .descriptors_by_kind
1057 .insert(Arc::from(serialized_item_kind), descriptor);
1058 registry
1059 .descriptors_by_type
1060 .insert(TypeId::of::<I>(), descriptor);
1061}
1062
1063pub struct AppState {
1064 pub languages: Arc<LanguageRegistry>,
1065 pub client: Arc<Client>,
1066 pub user_store: Entity<UserStore>,
1067 pub workspace_store: Entity<WorkspaceStore>,
1068 pub fs: Arc<dyn fs::Fs>,
1069 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1070 pub node_runtime: NodeRuntime,
1071 pub session: Entity<AppSession>,
1072}
1073
1074struct GlobalAppState(Weak<AppState>);
1075
1076impl Global for GlobalAppState {}
1077
1078pub struct WorkspaceStore {
1079 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1080 client: Arc<Client>,
1081 _subscriptions: Vec<client::Subscription>,
1082}
1083
1084#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1085pub enum CollaboratorId {
1086 PeerId(PeerId),
1087 Agent,
1088}
1089
1090impl From<PeerId> for CollaboratorId {
1091 fn from(peer_id: PeerId) -> Self {
1092 CollaboratorId::PeerId(peer_id)
1093 }
1094}
1095
1096impl From<&PeerId> for CollaboratorId {
1097 fn from(peer_id: &PeerId) -> Self {
1098 CollaboratorId::PeerId(*peer_id)
1099 }
1100}
1101
1102#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1103struct Follower {
1104 project_id: Option<u64>,
1105 peer_id: PeerId,
1106}
1107
1108impl AppState {
1109 #[track_caller]
1110 pub fn global(cx: &App) -> Weak<Self> {
1111 cx.global::<GlobalAppState>().0.clone()
1112 }
1113 pub fn try_global(cx: &App) -> Option<Weak<Self>> {
1114 cx.try_global::<GlobalAppState>()
1115 .map(|state| state.0.clone())
1116 }
1117 pub fn set_global(state: Weak<AppState>, cx: &mut App) {
1118 cx.set_global(GlobalAppState(state));
1119 }
1120
1121 #[cfg(any(test, feature = "test-support"))]
1122 pub fn test(cx: &mut App) -> Arc<Self> {
1123 use fs::Fs;
1124 use node_runtime::NodeRuntime;
1125 use session::Session;
1126 use settings::SettingsStore;
1127
1128 if !cx.has_global::<SettingsStore>() {
1129 let settings_store = SettingsStore::test(cx);
1130 cx.set_global(settings_store);
1131 }
1132
1133 let fs = fs::FakeFs::new(cx.background_executor().clone());
1134 <dyn Fs>::set_global(fs.clone(), cx);
1135 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1136 let clock = Arc::new(clock::FakeSystemClock::new());
1137 let http_client = http_client::FakeHttpClient::with_404_response();
1138 let client = Client::new(clock, http_client, cx);
1139 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1140 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1141 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1142
1143 theme::init(theme::LoadThemes::JustBase, cx);
1144 client::init(&client, cx);
1145
1146 Arc::new(Self {
1147 client,
1148 fs,
1149 languages,
1150 user_store,
1151 workspace_store,
1152 node_runtime: NodeRuntime::unavailable(),
1153 build_window_options: |_, _| Default::default(),
1154 session,
1155 })
1156 }
1157}
1158
1159struct DelayedDebouncedEditAction {
1160 task: Option<Task<()>>,
1161 cancel_channel: Option<oneshot::Sender<()>>,
1162}
1163
1164impl DelayedDebouncedEditAction {
1165 fn new() -> DelayedDebouncedEditAction {
1166 DelayedDebouncedEditAction {
1167 task: None,
1168 cancel_channel: None,
1169 }
1170 }
1171
1172 fn fire_new<F>(
1173 &mut self,
1174 delay: Duration,
1175 window: &mut Window,
1176 cx: &mut Context<Workspace>,
1177 func: F,
1178 ) where
1179 F: 'static
1180 + Send
1181 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1182 {
1183 if let Some(channel) = self.cancel_channel.take() {
1184 _ = channel.send(());
1185 }
1186
1187 let (sender, mut receiver) = oneshot::channel::<()>();
1188 self.cancel_channel = Some(sender);
1189
1190 let previous_task = self.task.take();
1191 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1192 let mut timer = cx.background_executor().timer(delay).fuse();
1193 if let Some(previous_task) = previous_task {
1194 previous_task.await;
1195 }
1196
1197 futures::select_biased! {
1198 _ = receiver => return,
1199 _ = timer => {}
1200 }
1201
1202 if let Some(result) = workspace
1203 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1204 .log_err()
1205 {
1206 result.await.log_err();
1207 }
1208 }));
1209 }
1210}
1211
1212pub enum Event {
1213 PaneAdded(Entity<Pane>),
1214 PaneRemoved,
1215 ItemAdded {
1216 item: Box<dyn ItemHandle>,
1217 },
1218 ActiveItemChanged,
1219 ItemRemoved {
1220 item_id: EntityId,
1221 },
1222 UserSavedItem {
1223 pane: WeakEntity<Pane>,
1224 item: Box<dyn WeakItemHandle>,
1225 save_intent: SaveIntent,
1226 },
1227 ContactRequestedJoin(u64),
1228 WorkspaceCreated(WeakEntity<Workspace>),
1229 OpenBundledFile {
1230 text: Cow<'static, str>,
1231 title: &'static str,
1232 language: &'static str,
1233 },
1234 ZoomChanged,
1235 ModalOpened,
1236 Activate,
1237 PanelAdded(AnyView),
1238}
1239
1240#[derive(Debug, Clone)]
1241pub enum OpenVisible {
1242 All,
1243 None,
1244 OnlyFiles,
1245 OnlyDirectories,
1246}
1247
1248enum WorkspaceLocation {
1249 // Valid local paths or SSH project to serialize
1250 Location(SerializedWorkspaceLocation, PathList),
1251 // No valid location found hence clear session id
1252 DetachFromSession,
1253 // No valid location found to serialize
1254 None,
1255}
1256
1257type PromptForNewPath = Box<
1258 dyn Fn(
1259 &mut Workspace,
1260 DirectoryLister,
1261 Option<String>,
1262 &mut Window,
1263 &mut Context<Workspace>,
1264 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1265>;
1266
1267type PromptForOpenPath = Box<
1268 dyn Fn(
1269 &mut Workspace,
1270 DirectoryLister,
1271 &mut Window,
1272 &mut Context<Workspace>,
1273 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1274>;
1275
1276#[derive(Default)]
1277struct DispatchingKeystrokes {
1278 dispatched: HashSet<Vec<Keystroke>>,
1279 queue: VecDeque<Keystroke>,
1280 task: Option<Shared<Task<()>>>,
1281}
1282
1283/// Collects everything project-related for a certain window opened.
1284/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1285///
1286/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1287/// The `Workspace` owns everybody's state and serves as a default, "global context",
1288/// that can be used to register a global action to be triggered from any place in the window.
1289pub struct Workspace {
1290 weak_self: WeakEntity<Self>,
1291 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1292 zoomed: Option<AnyWeakView>,
1293 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1294 zoomed_position: Option<DockPosition>,
1295 center: PaneGroup,
1296 left_dock: Entity<Dock>,
1297 bottom_dock: Entity<Dock>,
1298 right_dock: Entity<Dock>,
1299 panes: Vec<Entity<Pane>>,
1300 active_worktree_override: Option<WorktreeId>,
1301 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1302 active_pane: Entity<Pane>,
1303 last_active_center_pane: Option<WeakEntity<Pane>>,
1304 last_active_view_id: Option<proto::ViewId>,
1305 status_bar: Entity<StatusBar>,
1306 pub(crate) modal_layer: Entity<ModalLayer>,
1307 toast_layer: Entity<ToastLayer>,
1308 titlebar_item: Option<AnyView>,
1309 notifications: Notifications,
1310 suppressed_notifications: HashSet<NotificationId>,
1311 project: Entity<Project>,
1312 follower_states: HashMap<CollaboratorId, FollowerState>,
1313 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1314 window_edited: bool,
1315 last_window_title: Option<String>,
1316 dirty_items: HashMap<EntityId, Subscription>,
1317 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1318 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1319 database_id: Option<WorkspaceId>,
1320 app_state: Arc<AppState>,
1321 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1322 _subscriptions: Vec<Subscription>,
1323 _apply_leader_updates: Task<Result<()>>,
1324 _observe_current_user: Task<Result<()>>,
1325 _schedule_serialize_workspace: Option<Task<()>>,
1326 _serialize_workspace_task: Option<Task<()>>,
1327 _schedule_serialize_ssh_paths: Option<Task<()>>,
1328 pane_history_timestamp: Arc<AtomicUsize>,
1329 bounds: Bounds<Pixels>,
1330 pub centered_layout: bool,
1331 bounds_save_task_queued: Option<Task<()>>,
1332 on_prompt_for_new_path: Option<PromptForNewPath>,
1333 on_prompt_for_open_path: Option<PromptForOpenPath>,
1334 terminal_provider: Option<Box<dyn TerminalProvider>>,
1335 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1336 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1337 _items_serializer: Task<Result<()>>,
1338 session_id: Option<String>,
1339 scheduled_tasks: Vec<Task<()>>,
1340 last_open_dock_positions: Vec<DockPosition>,
1341 removing: bool,
1342 _panels_task: Option<Task<Result<()>>>,
1343 sidebar_focus_handle: Option<FocusHandle>,
1344}
1345
1346impl EventEmitter<Event> for Workspace {}
1347
1348#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1349pub struct ViewId {
1350 pub creator: CollaboratorId,
1351 pub id: u64,
1352}
1353
1354pub struct FollowerState {
1355 center_pane: Entity<Pane>,
1356 dock_pane: Option<Entity<Pane>>,
1357 active_view_id: Option<ViewId>,
1358 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1359}
1360
1361struct FollowerView {
1362 view: Box<dyn FollowableItemHandle>,
1363 location: Option<proto::PanelId>,
1364}
1365
1366impl Workspace {
1367 pub fn new(
1368 workspace_id: Option<WorkspaceId>,
1369 project: Entity<Project>,
1370 app_state: Arc<AppState>,
1371 window: &mut Window,
1372 cx: &mut Context<Self>,
1373 ) -> Self {
1374 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1375 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1376 if let TrustedWorktreesEvent::Trusted(..) = e {
1377 // Do not persist auto trusted worktrees
1378 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1379 worktrees_store.update(cx, |worktrees_store, cx| {
1380 worktrees_store.schedule_serialization(
1381 cx,
1382 |new_trusted_worktrees, cx| {
1383 let timeout =
1384 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1385 let db = WorkspaceDb::global(cx);
1386 cx.background_spawn(async move {
1387 timeout.await;
1388 db.save_trusted_worktrees(new_trusted_worktrees)
1389 .await
1390 .log_err();
1391 })
1392 },
1393 )
1394 });
1395 }
1396 }
1397 })
1398 .detach();
1399
1400 cx.observe_global::<SettingsStore>(|_, cx| {
1401 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1402 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1403 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1404 trusted_worktrees.auto_trust_all(cx);
1405 })
1406 }
1407 }
1408 })
1409 .detach();
1410 }
1411
1412 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1413 match event {
1414 project::Event::RemoteIdChanged(_) => {
1415 this.update_window_title(window, cx);
1416 }
1417
1418 project::Event::CollaboratorLeft(peer_id) => {
1419 this.collaborator_left(*peer_id, window, cx);
1420 }
1421
1422 &project::Event::WorktreeRemoved(id) | &project::Event::WorktreeAdded(id) => {
1423 this.update_window_title(window, cx);
1424 if this
1425 .project()
1426 .read(cx)
1427 .worktree_for_id(id, cx)
1428 .is_some_and(|wt| wt.read(cx).is_visible())
1429 {
1430 this.serialize_workspace(window, cx);
1431 this.update_history(cx);
1432 }
1433 }
1434 project::Event::WorktreeUpdatedEntries(..) => {
1435 this.update_window_title(window, cx);
1436 this.serialize_workspace(window, cx);
1437 }
1438
1439 project::Event::DisconnectedFromHost => {
1440 this.update_window_edited(window, cx);
1441 let leaders_to_unfollow =
1442 this.follower_states.keys().copied().collect::<Vec<_>>();
1443 for leader_id in leaders_to_unfollow {
1444 this.unfollow(leader_id, window, cx);
1445 }
1446 }
1447
1448 project::Event::DisconnectedFromRemote {
1449 server_not_running: _,
1450 } => {
1451 this.update_window_edited(window, cx);
1452 }
1453
1454 project::Event::Closed => {
1455 window.remove_window();
1456 }
1457
1458 project::Event::DeletedEntry(_, entry_id) => {
1459 for pane in this.panes.iter() {
1460 pane.update(cx, |pane, cx| {
1461 pane.handle_deleted_project_item(*entry_id, window, cx)
1462 });
1463 }
1464 }
1465
1466 project::Event::Toast {
1467 notification_id,
1468 message,
1469 link,
1470 } => this.show_notification(
1471 NotificationId::named(notification_id.clone()),
1472 cx,
1473 |cx| {
1474 let mut notification = MessageNotification::new(message.clone(), cx);
1475 if let Some(link) = link {
1476 notification = notification
1477 .more_info_message(link.label)
1478 .more_info_url(link.url);
1479 }
1480
1481 cx.new(|_| notification)
1482 },
1483 ),
1484
1485 project::Event::HideToast { notification_id } => {
1486 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1487 }
1488
1489 project::Event::LanguageServerPrompt(request) => {
1490 struct LanguageServerPrompt;
1491
1492 this.show_notification(
1493 NotificationId::composite::<LanguageServerPrompt>(request.id),
1494 cx,
1495 |cx| {
1496 cx.new(|cx| {
1497 notifications::LanguageServerPrompt::new(request.clone(), cx)
1498 })
1499 },
1500 );
1501 }
1502
1503 project::Event::AgentLocationChanged => {
1504 this.handle_agent_location_changed(window, cx)
1505 }
1506
1507 _ => {}
1508 }
1509 cx.notify()
1510 })
1511 .detach();
1512
1513 cx.subscribe_in(
1514 &project.read(cx).breakpoint_store(),
1515 window,
1516 |workspace, _, event, window, cx| match event {
1517 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1518 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1519 workspace.serialize_workspace(window, cx);
1520 }
1521 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1522 },
1523 )
1524 .detach();
1525 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1526 cx.subscribe_in(
1527 &toolchain_store,
1528 window,
1529 |workspace, _, event, window, cx| match event {
1530 ToolchainStoreEvent::CustomToolchainsModified => {
1531 workspace.serialize_workspace(window, cx);
1532 }
1533 _ => {}
1534 },
1535 )
1536 .detach();
1537 }
1538
1539 cx.on_focus_lost(window, |this, window, cx| {
1540 let focus_handle = this.focus_handle(cx);
1541 window.focus(&focus_handle, cx);
1542 })
1543 .detach();
1544
1545 let weak_handle = cx.entity().downgrade();
1546 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1547
1548 let center_pane = cx.new(|cx| {
1549 let mut center_pane = Pane::new(
1550 weak_handle.clone(),
1551 project.clone(),
1552 pane_history_timestamp.clone(),
1553 None,
1554 NewFile.boxed_clone(),
1555 true,
1556 window,
1557 cx,
1558 );
1559 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1560 center_pane.set_should_display_welcome_page(true);
1561 center_pane
1562 });
1563 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1564 .detach();
1565
1566 window.focus(¢er_pane.focus_handle(cx), cx);
1567
1568 cx.emit(Event::PaneAdded(center_pane.clone()));
1569
1570 let any_window_handle = window.window_handle();
1571 app_state.workspace_store.update(cx, |store, _| {
1572 store
1573 .workspaces
1574 .insert((any_window_handle, weak_handle.clone()));
1575 });
1576
1577 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1578 let mut connection_status = app_state.client.status();
1579 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1580 current_user.next().await;
1581 connection_status.next().await;
1582 let mut stream =
1583 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1584
1585 while stream.recv().await.is_some() {
1586 this.update(cx, |_, cx| cx.notify())?;
1587 }
1588 anyhow::Ok(())
1589 });
1590
1591 // All leader updates are enqueued and then processed in a single task, so
1592 // that each asynchronous operation can be run in order.
1593 let (leader_updates_tx, mut leader_updates_rx) =
1594 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1595 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1596 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1597 Self::process_leader_update(&this, leader_id, update, cx)
1598 .await
1599 .log_err();
1600 }
1601
1602 Ok(())
1603 });
1604
1605 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1606 let modal_layer = cx.new(|_| ModalLayer::new());
1607 let toast_layer = cx.new(|_| ToastLayer::new());
1608 cx.subscribe(
1609 &modal_layer,
1610 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1611 cx.emit(Event::ModalOpened);
1612 },
1613 )
1614 .detach();
1615
1616 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1617 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1618 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1619 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1620 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1621 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1622 let status_bar = cx.new(|cx| {
1623 let mut status_bar = StatusBar::new(¢er_pane.clone(), window, cx);
1624 status_bar.add_left_item(left_dock_buttons, window, cx);
1625 status_bar.add_right_item(right_dock_buttons, window, cx);
1626 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1627 status_bar
1628 });
1629
1630 let session_id = app_state.session.read(cx).id().to_owned();
1631
1632 let mut active_call = None;
1633 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1634 let subscriptions =
1635 vec![
1636 call.0
1637 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1638 ];
1639 active_call = Some((call, subscriptions));
1640 }
1641
1642 let (serializable_items_tx, serializable_items_rx) =
1643 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1644 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1645 Self::serialize_items(&this, serializable_items_rx, cx).await
1646 });
1647
1648 let subscriptions = vec![
1649 cx.observe_window_activation(window, Self::on_window_activation_changed),
1650 cx.observe_window_bounds(window, move |this, window, cx| {
1651 if this.bounds_save_task_queued.is_some() {
1652 return;
1653 }
1654 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1655 cx.background_executor()
1656 .timer(Duration::from_millis(100))
1657 .await;
1658 this.update_in(cx, |this, window, cx| {
1659 this.save_window_bounds(window, cx).detach();
1660 this.bounds_save_task_queued.take();
1661 })
1662 .ok();
1663 }));
1664 cx.notify();
1665 }),
1666 cx.observe_window_appearance(window, |_, window, cx| {
1667 let window_appearance = window.appearance();
1668
1669 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1670
1671 GlobalTheme::reload_theme(cx);
1672 GlobalTheme::reload_icon_theme(cx);
1673 }),
1674 cx.on_release({
1675 let weak_handle = weak_handle.clone();
1676 move |this, cx| {
1677 this.app_state.workspace_store.update(cx, move |store, _| {
1678 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1679 })
1680 }
1681 }),
1682 ];
1683
1684 cx.defer_in(window, move |this, window, cx| {
1685 this.update_window_title(window, cx);
1686 this.show_initial_notifications(cx);
1687 });
1688
1689 let mut center = PaneGroup::new(center_pane.clone());
1690 center.set_is_center(true);
1691 center.mark_positions(cx);
1692
1693 Workspace {
1694 weak_self: weak_handle.clone(),
1695 zoomed: None,
1696 zoomed_position: None,
1697 previous_dock_drag_coordinates: None,
1698 center,
1699 panes: vec![center_pane.clone()],
1700 panes_by_item: Default::default(),
1701 active_pane: center_pane.clone(),
1702 last_active_center_pane: Some(center_pane.downgrade()),
1703 last_active_view_id: None,
1704 status_bar,
1705 modal_layer,
1706 toast_layer,
1707 titlebar_item: None,
1708 active_worktree_override: None,
1709 notifications: Notifications::default(),
1710 suppressed_notifications: HashSet::default(),
1711 left_dock,
1712 bottom_dock,
1713 right_dock,
1714 _panels_task: None,
1715 project: project.clone(),
1716 follower_states: Default::default(),
1717 last_leaders_by_pane: Default::default(),
1718 dispatching_keystrokes: Default::default(),
1719 window_edited: false,
1720 last_window_title: None,
1721 dirty_items: Default::default(),
1722 active_call,
1723 database_id: workspace_id,
1724 app_state,
1725 _observe_current_user,
1726 _apply_leader_updates,
1727 _schedule_serialize_workspace: None,
1728 _serialize_workspace_task: None,
1729 _schedule_serialize_ssh_paths: None,
1730 leader_updates_tx,
1731 _subscriptions: subscriptions,
1732 pane_history_timestamp,
1733 workspace_actions: Default::default(),
1734 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1735 bounds: Default::default(),
1736 centered_layout: false,
1737 bounds_save_task_queued: None,
1738 on_prompt_for_new_path: None,
1739 on_prompt_for_open_path: None,
1740 terminal_provider: None,
1741 debugger_provider: None,
1742 serializable_items_tx,
1743 _items_serializer,
1744 session_id: Some(session_id),
1745
1746 scheduled_tasks: Vec::new(),
1747 last_open_dock_positions: Vec::new(),
1748 removing: false,
1749 sidebar_focus_handle: None,
1750 }
1751 }
1752
1753 pub fn new_local(
1754 abs_paths: Vec<PathBuf>,
1755 app_state: Arc<AppState>,
1756 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1757 env: Option<HashMap<String, String>>,
1758 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1759 activate: bool,
1760 cx: &mut App,
1761 ) -> Task<anyhow::Result<OpenResult>> {
1762 let project_handle = Project::local(
1763 app_state.client.clone(),
1764 app_state.node_runtime.clone(),
1765 app_state.user_store.clone(),
1766 app_state.languages.clone(),
1767 app_state.fs.clone(),
1768 env,
1769 Default::default(),
1770 cx,
1771 );
1772
1773 let db = WorkspaceDb::global(cx);
1774 let kvp = db::kvp::KeyValueStore::global(cx);
1775 cx.spawn(async move |cx| {
1776 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1777 for path in abs_paths.into_iter() {
1778 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1779 paths_to_open.push(canonical)
1780 } else {
1781 paths_to_open.push(path)
1782 }
1783 }
1784
1785 let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
1786
1787 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1788 paths_to_open = paths.ordered_paths().cloned().collect();
1789 if !paths.is_lexicographically_ordered() {
1790 project_handle.update(cx, |project, cx| {
1791 project.set_worktrees_reordered(true, cx);
1792 });
1793 }
1794 }
1795
1796 // Get project paths for all of the abs_paths
1797 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1798 Vec::with_capacity(paths_to_open.len());
1799
1800 for path in paths_to_open.into_iter() {
1801 if let Some((_, project_entry)) = cx
1802 .update(|cx| {
1803 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1804 })
1805 .await
1806 .log_err()
1807 {
1808 project_paths.push((path, Some(project_entry)));
1809 } else {
1810 project_paths.push((path, None));
1811 }
1812 }
1813
1814 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1815 serialized_workspace.id
1816 } else {
1817 db.next_id().await.unwrap_or_else(|_| Default::default())
1818 };
1819
1820 let toolchains = db.toolchains(workspace_id).await?;
1821
1822 for (toolchain, worktree_path, path) in toolchains {
1823 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1824 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1825 this.find_worktree(&worktree_path, cx)
1826 .and_then(|(worktree, rel_path)| {
1827 if rel_path.is_empty() {
1828 Some(worktree.read(cx).id())
1829 } else {
1830 None
1831 }
1832 })
1833 }) else {
1834 // We did not find a worktree with a given path, but that's whatever.
1835 continue;
1836 };
1837 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1838 continue;
1839 }
1840
1841 project_handle
1842 .update(cx, |this, cx| {
1843 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1844 })
1845 .await;
1846 }
1847 if let Some(workspace) = serialized_workspace.as_ref() {
1848 project_handle.update(cx, |this, cx| {
1849 for (scope, toolchains) in &workspace.user_toolchains {
1850 for toolchain in toolchains {
1851 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1852 }
1853 }
1854 });
1855 }
1856
1857 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1858 if let Some(window) = requesting_window {
1859 let centered_layout = serialized_workspace
1860 .as_ref()
1861 .map(|w| w.centered_layout)
1862 .unwrap_or(false);
1863
1864 let workspace = window.update(cx, |multi_workspace, window, cx| {
1865 let workspace = cx.new(|cx| {
1866 let mut workspace = Workspace::new(
1867 Some(workspace_id),
1868 project_handle.clone(),
1869 app_state.clone(),
1870 window,
1871 cx,
1872 );
1873
1874 workspace.centered_layout = centered_layout;
1875
1876 // Call init callback to add items before window renders
1877 if let Some(init) = init {
1878 init(&mut workspace, window, cx);
1879 }
1880
1881 workspace
1882 });
1883 if activate {
1884 multi_workspace.activate(workspace.clone(), cx);
1885 } else {
1886 multi_workspace.add_workspace(workspace.clone(), cx);
1887 }
1888 workspace
1889 })?;
1890 (window, workspace)
1891 } else {
1892 let window_bounds_override = window_bounds_env_override();
1893
1894 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1895 (Some(WindowBounds::Windowed(bounds)), None)
1896 } else if let Some(workspace) = serialized_workspace.as_ref()
1897 && let Some(display) = workspace.display
1898 && let Some(bounds) = workspace.window_bounds.as_ref()
1899 {
1900 // Reopening an existing workspace - restore its saved bounds
1901 (Some(bounds.0), Some(display))
1902 } else if let Some((display, bounds)) =
1903 persistence::read_default_window_bounds(&kvp)
1904 {
1905 // New or empty workspace - use the last known window bounds
1906 (Some(bounds), Some(display))
1907 } else {
1908 // New window - let GPUI's default_bounds() handle cascading
1909 (None, None)
1910 };
1911
1912 // Use the serialized workspace to construct the new window
1913 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1914 options.window_bounds = window_bounds;
1915 let centered_layout = serialized_workspace
1916 .as_ref()
1917 .map(|w| w.centered_layout)
1918 .unwrap_or(false);
1919 let window = cx.open_window(options, {
1920 let app_state = app_state.clone();
1921 let project_handle = project_handle.clone();
1922 move |window, cx| {
1923 let workspace = cx.new(|cx| {
1924 let mut workspace = Workspace::new(
1925 Some(workspace_id),
1926 project_handle,
1927 app_state,
1928 window,
1929 cx,
1930 );
1931 workspace.centered_layout = centered_layout;
1932
1933 // Call init callback to add items before window renders
1934 if let Some(init) = init {
1935 init(&mut workspace, window, cx);
1936 }
1937
1938 workspace
1939 });
1940 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1941 }
1942 })?;
1943 let workspace =
1944 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
1945 multi_workspace.workspace().clone()
1946 })?;
1947 (window, workspace)
1948 };
1949
1950 notify_if_database_failed(window, cx);
1951 // Check if this is an empty workspace (no paths to open)
1952 // An empty workspace is one where project_paths is empty
1953 let is_empty_workspace = project_paths.is_empty();
1954 // Check if serialized workspace has paths before it's moved
1955 let serialized_workspace_has_paths = serialized_workspace
1956 .as_ref()
1957 .map(|ws| !ws.paths.is_empty())
1958 .unwrap_or(false);
1959
1960 let opened_items = window
1961 .update(cx, |_, window, cx| {
1962 workspace.update(cx, |_workspace: &mut Workspace, cx| {
1963 open_items(serialized_workspace, project_paths, window, cx)
1964 })
1965 })?
1966 .await
1967 .unwrap_or_default();
1968
1969 // Restore default dock state for empty workspaces
1970 // Only restore if:
1971 // 1. This is an empty workspace (no paths), AND
1972 // 2. The serialized workspace either doesn't exist or has no paths
1973 if is_empty_workspace && !serialized_workspace_has_paths {
1974 if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
1975 window
1976 .update(cx, |_, window, cx| {
1977 workspace.update(cx, |workspace, cx| {
1978 for (dock, serialized_dock) in [
1979 (&workspace.right_dock, &default_docks.right),
1980 (&workspace.left_dock, &default_docks.left),
1981 (&workspace.bottom_dock, &default_docks.bottom),
1982 ] {
1983 dock.update(cx, |dock, cx| {
1984 dock.serialized_dock = Some(serialized_dock.clone());
1985 dock.restore_state(window, cx);
1986 });
1987 }
1988 cx.notify();
1989 });
1990 })
1991 .log_err();
1992 }
1993 }
1994
1995 window
1996 .update(cx, |_, _window, cx| {
1997 workspace.update(cx, |this: &mut Workspace, cx| {
1998 this.update_history(cx);
1999 });
2000 })
2001 .log_err();
2002 Ok(OpenResult {
2003 window,
2004 workspace,
2005 opened_items,
2006 })
2007 })
2008 }
2009
2010 pub fn weak_handle(&self) -> WeakEntity<Self> {
2011 self.weak_self.clone()
2012 }
2013
2014 pub fn left_dock(&self) -> &Entity<Dock> {
2015 &self.left_dock
2016 }
2017
2018 pub fn bottom_dock(&self) -> &Entity<Dock> {
2019 &self.bottom_dock
2020 }
2021
2022 pub fn set_bottom_dock_layout(
2023 &mut self,
2024 layout: BottomDockLayout,
2025 window: &mut Window,
2026 cx: &mut Context<Self>,
2027 ) {
2028 let fs = self.project().read(cx).fs();
2029 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2030 content.workspace.bottom_dock_layout = Some(layout);
2031 });
2032
2033 cx.notify();
2034 self.serialize_workspace(window, cx);
2035 }
2036
2037 pub fn right_dock(&self) -> &Entity<Dock> {
2038 &self.right_dock
2039 }
2040
2041 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2042 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2043 }
2044
2045 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2046 let left_dock = self.left_dock.read(cx);
2047 let left_visible = left_dock.is_open();
2048 let left_active_panel = left_dock
2049 .active_panel()
2050 .map(|panel| panel.persistent_name().to_string());
2051 // `zoomed_position` is kept in sync with individual panel zoom state
2052 // by the dock code in `Dock::new` and `Dock::add_panel`.
2053 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2054
2055 let right_dock = self.right_dock.read(cx);
2056 let right_visible = right_dock.is_open();
2057 let right_active_panel = right_dock
2058 .active_panel()
2059 .map(|panel| panel.persistent_name().to_string());
2060 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2061
2062 let bottom_dock = self.bottom_dock.read(cx);
2063 let bottom_visible = bottom_dock.is_open();
2064 let bottom_active_panel = bottom_dock
2065 .active_panel()
2066 .map(|panel| panel.persistent_name().to_string());
2067 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2068
2069 DockStructure {
2070 left: DockData {
2071 visible: left_visible,
2072 active_panel: left_active_panel,
2073 zoom: left_dock_zoom,
2074 },
2075 right: DockData {
2076 visible: right_visible,
2077 active_panel: right_active_panel,
2078 zoom: right_dock_zoom,
2079 },
2080 bottom: DockData {
2081 visible: bottom_visible,
2082 active_panel: bottom_active_panel,
2083 zoom: bottom_dock_zoom,
2084 },
2085 }
2086 }
2087
2088 pub fn set_dock_structure(
2089 &self,
2090 docks: DockStructure,
2091 window: &mut Window,
2092 cx: &mut Context<Self>,
2093 ) {
2094 for (dock, data) in [
2095 (&self.left_dock, docks.left),
2096 (&self.bottom_dock, docks.bottom),
2097 (&self.right_dock, docks.right),
2098 ] {
2099 dock.update(cx, |dock, cx| {
2100 dock.serialized_dock = Some(data);
2101 dock.restore_state(window, cx);
2102 });
2103 }
2104 }
2105
2106 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2107 self.items(cx)
2108 .filter_map(|item| {
2109 let project_path = item.project_path(cx)?;
2110 self.project.read(cx).absolute_path(&project_path, cx)
2111 })
2112 .collect()
2113 }
2114
2115 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2116 match position {
2117 DockPosition::Left => &self.left_dock,
2118 DockPosition::Bottom => &self.bottom_dock,
2119 DockPosition::Right => &self.right_dock,
2120 }
2121 }
2122
2123 pub fn is_edited(&self) -> bool {
2124 self.window_edited
2125 }
2126
2127 pub fn add_panel<T: Panel>(
2128 &mut self,
2129 panel: Entity<T>,
2130 window: &mut Window,
2131 cx: &mut Context<Self>,
2132 ) {
2133 let focus_handle = panel.panel_focus_handle(cx);
2134 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2135 .detach();
2136
2137 let dock_position = panel.position(window, cx);
2138 let dock = self.dock_at_position(dock_position);
2139 let any_panel = panel.to_any();
2140
2141 dock.update(cx, |dock, cx| {
2142 dock.add_panel(panel, self.weak_self.clone(), window, cx)
2143 });
2144
2145 cx.emit(Event::PanelAdded(any_panel));
2146 }
2147
2148 pub fn remove_panel<T: Panel>(
2149 &mut self,
2150 panel: &Entity<T>,
2151 window: &mut Window,
2152 cx: &mut Context<Self>,
2153 ) {
2154 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2155 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2156 }
2157 }
2158
2159 pub fn status_bar(&self) -> &Entity<StatusBar> {
2160 &self.status_bar
2161 }
2162
2163 pub fn set_workspace_sidebar_open(
2164 &self,
2165 open: bool,
2166 has_notifications: bool,
2167 show_toggle: bool,
2168 cx: &mut App,
2169 ) {
2170 self.status_bar.update(cx, |status_bar, cx| {
2171 status_bar.set_workspace_sidebar_open(open, cx);
2172 status_bar.set_sidebar_has_notifications(has_notifications, cx);
2173 status_bar.set_show_sidebar_toggle(show_toggle, cx);
2174 });
2175 }
2176
2177 pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
2178 self.sidebar_focus_handle = handle;
2179 }
2180
2181 pub fn status_bar_visible(&self, cx: &App) -> bool {
2182 StatusBarSettings::get_global(cx).show
2183 }
2184
2185 pub fn app_state(&self) -> &Arc<AppState> {
2186 &self.app_state
2187 }
2188
2189 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2190 self._panels_task = Some(task);
2191 }
2192
2193 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2194 self._panels_task.take()
2195 }
2196
2197 pub fn user_store(&self) -> &Entity<UserStore> {
2198 &self.app_state.user_store
2199 }
2200
2201 pub fn project(&self) -> &Entity<Project> {
2202 &self.project
2203 }
2204
2205 pub fn path_style(&self, cx: &App) -> PathStyle {
2206 self.project.read(cx).path_style(cx)
2207 }
2208
2209 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2210 let mut history: HashMap<EntityId, usize> = HashMap::default();
2211
2212 for pane_handle in &self.panes {
2213 let pane = pane_handle.read(cx);
2214
2215 for entry in pane.activation_history() {
2216 history.insert(
2217 entry.entity_id,
2218 history
2219 .get(&entry.entity_id)
2220 .cloned()
2221 .unwrap_or(0)
2222 .max(entry.timestamp),
2223 );
2224 }
2225 }
2226
2227 history
2228 }
2229
2230 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2231 let mut recent_item: Option<Entity<T>> = None;
2232 let mut recent_timestamp = 0;
2233 for pane_handle in &self.panes {
2234 let pane = pane_handle.read(cx);
2235 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2236 pane.items().map(|item| (item.item_id(), item)).collect();
2237 for entry in pane.activation_history() {
2238 if entry.timestamp > recent_timestamp
2239 && let Some(&item) = item_map.get(&entry.entity_id)
2240 && let Some(typed_item) = item.act_as::<T>(cx)
2241 {
2242 recent_timestamp = entry.timestamp;
2243 recent_item = Some(typed_item);
2244 }
2245 }
2246 }
2247 recent_item
2248 }
2249
2250 pub fn recent_navigation_history_iter(
2251 &self,
2252 cx: &App,
2253 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2254 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2255 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2256
2257 for pane in &self.panes {
2258 let pane = pane.read(cx);
2259
2260 pane.nav_history()
2261 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2262 if let Some(fs_path) = &fs_path {
2263 abs_paths_opened
2264 .entry(fs_path.clone())
2265 .or_default()
2266 .insert(project_path.clone());
2267 }
2268 let timestamp = entry.timestamp;
2269 match history.entry(project_path) {
2270 hash_map::Entry::Occupied(mut entry) => {
2271 let (_, old_timestamp) = entry.get();
2272 if ×tamp > old_timestamp {
2273 entry.insert((fs_path, timestamp));
2274 }
2275 }
2276 hash_map::Entry::Vacant(entry) => {
2277 entry.insert((fs_path, timestamp));
2278 }
2279 }
2280 });
2281
2282 if let Some(item) = pane.active_item()
2283 && let Some(project_path) = item.project_path(cx)
2284 {
2285 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2286
2287 if let Some(fs_path) = &fs_path {
2288 abs_paths_opened
2289 .entry(fs_path.clone())
2290 .or_default()
2291 .insert(project_path.clone());
2292 }
2293
2294 history.insert(project_path, (fs_path, std::usize::MAX));
2295 }
2296 }
2297
2298 history
2299 .into_iter()
2300 .sorted_by_key(|(_, (_, order))| *order)
2301 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2302 .rev()
2303 .filter(move |(history_path, abs_path)| {
2304 let latest_project_path_opened = abs_path
2305 .as_ref()
2306 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2307 .and_then(|project_paths| {
2308 project_paths
2309 .iter()
2310 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2311 });
2312
2313 latest_project_path_opened.is_none_or(|path| path == history_path)
2314 })
2315 }
2316
2317 pub fn recent_navigation_history(
2318 &self,
2319 limit: Option<usize>,
2320 cx: &App,
2321 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2322 self.recent_navigation_history_iter(cx)
2323 .take(limit.unwrap_or(usize::MAX))
2324 .collect()
2325 }
2326
2327 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2328 for pane in &self.panes {
2329 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2330 }
2331 }
2332
2333 fn navigate_history(
2334 &mut self,
2335 pane: WeakEntity<Pane>,
2336 mode: NavigationMode,
2337 window: &mut Window,
2338 cx: &mut Context<Workspace>,
2339 ) -> Task<Result<()>> {
2340 self.navigate_history_impl(
2341 pane,
2342 mode,
2343 window,
2344 &mut |history, cx| history.pop(mode, cx),
2345 cx,
2346 )
2347 }
2348
2349 fn navigate_tag_history(
2350 &mut self,
2351 pane: WeakEntity<Pane>,
2352 mode: TagNavigationMode,
2353 window: &mut Window,
2354 cx: &mut Context<Workspace>,
2355 ) -> Task<Result<()>> {
2356 self.navigate_history_impl(
2357 pane,
2358 NavigationMode::Normal,
2359 window,
2360 &mut |history, _cx| history.pop_tag(mode),
2361 cx,
2362 )
2363 }
2364
2365 fn navigate_history_impl(
2366 &mut self,
2367 pane: WeakEntity<Pane>,
2368 mode: NavigationMode,
2369 window: &mut Window,
2370 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2371 cx: &mut Context<Workspace>,
2372 ) -> Task<Result<()>> {
2373 let to_load = if let Some(pane) = pane.upgrade() {
2374 pane.update(cx, |pane, cx| {
2375 window.focus(&pane.focus_handle(cx), cx);
2376 loop {
2377 // Retrieve the weak item handle from the history.
2378 let entry = cb(pane.nav_history_mut(), cx)?;
2379
2380 // If the item is still present in this pane, then activate it.
2381 if let Some(index) = entry
2382 .item
2383 .upgrade()
2384 .and_then(|v| pane.index_for_item(v.as_ref()))
2385 {
2386 let prev_active_item_index = pane.active_item_index();
2387 pane.nav_history_mut().set_mode(mode);
2388 pane.activate_item(index, true, true, window, cx);
2389 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2390
2391 let mut navigated = prev_active_item_index != pane.active_item_index();
2392 if let Some(data) = entry.data {
2393 navigated |= pane.active_item()?.navigate(data, window, cx);
2394 }
2395
2396 if navigated {
2397 break None;
2398 }
2399 } else {
2400 // If the item is no longer present in this pane, then retrieve its
2401 // path info in order to reopen it.
2402 break pane
2403 .nav_history()
2404 .path_for_item(entry.item.id())
2405 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2406 }
2407 }
2408 })
2409 } else {
2410 None
2411 };
2412
2413 if let Some((project_path, abs_path, entry)) = to_load {
2414 // If the item was no longer present, then load it again from its previous path, first try the local path
2415 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2416
2417 cx.spawn_in(window, async move |workspace, cx| {
2418 let open_by_project_path = open_by_project_path.await;
2419 let mut navigated = false;
2420 match open_by_project_path
2421 .with_context(|| format!("Navigating to {project_path:?}"))
2422 {
2423 Ok((project_entry_id, build_item)) => {
2424 let prev_active_item_id = pane.update(cx, |pane, _| {
2425 pane.nav_history_mut().set_mode(mode);
2426 pane.active_item().map(|p| p.item_id())
2427 })?;
2428
2429 pane.update_in(cx, |pane, window, cx| {
2430 let item = pane.open_item(
2431 project_entry_id,
2432 project_path,
2433 true,
2434 entry.is_preview,
2435 true,
2436 None,
2437 window, cx,
2438 build_item,
2439 );
2440 navigated |= Some(item.item_id()) != prev_active_item_id;
2441 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2442 if let Some(data) = entry.data {
2443 navigated |= item.navigate(data, window, cx);
2444 }
2445 })?;
2446 }
2447 Err(open_by_project_path_e) => {
2448 // Fall back to opening by abs path, in case an external file was opened and closed,
2449 // and its worktree is now dropped
2450 if let Some(abs_path) = abs_path {
2451 let prev_active_item_id = pane.update(cx, |pane, _| {
2452 pane.nav_history_mut().set_mode(mode);
2453 pane.active_item().map(|p| p.item_id())
2454 })?;
2455 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2456 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2457 })?;
2458 match open_by_abs_path
2459 .await
2460 .with_context(|| format!("Navigating to {abs_path:?}"))
2461 {
2462 Ok(item) => {
2463 pane.update_in(cx, |pane, window, cx| {
2464 navigated |= Some(item.item_id()) != prev_active_item_id;
2465 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2466 if let Some(data) = entry.data {
2467 navigated |= item.navigate(data, window, cx);
2468 }
2469 })?;
2470 }
2471 Err(open_by_abs_path_e) => {
2472 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2473 }
2474 }
2475 }
2476 }
2477 }
2478
2479 if !navigated {
2480 workspace
2481 .update_in(cx, |workspace, window, cx| {
2482 Self::navigate_history(workspace, pane, mode, window, cx)
2483 })?
2484 .await?;
2485 }
2486
2487 Ok(())
2488 })
2489 } else {
2490 Task::ready(Ok(()))
2491 }
2492 }
2493
2494 pub fn go_back(
2495 &mut self,
2496 pane: WeakEntity<Pane>,
2497 window: &mut Window,
2498 cx: &mut Context<Workspace>,
2499 ) -> Task<Result<()>> {
2500 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2501 }
2502
2503 pub fn go_forward(
2504 &mut self,
2505 pane: WeakEntity<Pane>,
2506 window: &mut Window,
2507 cx: &mut Context<Workspace>,
2508 ) -> Task<Result<()>> {
2509 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2510 }
2511
2512 pub fn reopen_closed_item(
2513 &mut self,
2514 window: &mut Window,
2515 cx: &mut Context<Workspace>,
2516 ) -> Task<Result<()>> {
2517 self.navigate_history(
2518 self.active_pane().downgrade(),
2519 NavigationMode::ReopeningClosedItem,
2520 window,
2521 cx,
2522 )
2523 }
2524
2525 pub fn client(&self) -> &Arc<Client> {
2526 &self.app_state.client
2527 }
2528
2529 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2530 self.titlebar_item = Some(item);
2531 cx.notify();
2532 }
2533
2534 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2535 self.on_prompt_for_new_path = Some(prompt)
2536 }
2537
2538 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2539 self.on_prompt_for_open_path = Some(prompt)
2540 }
2541
2542 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2543 self.terminal_provider = Some(Box::new(provider));
2544 }
2545
2546 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2547 self.debugger_provider = Some(Arc::new(provider));
2548 }
2549
2550 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2551 self.debugger_provider.clone()
2552 }
2553
2554 pub fn prompt_for_open_path(
2555 &mut self,
2556 path_prompt_options: PathPromptOptions,
2557 lister: DirectoryLister,
2558 window: &mut Window,
2559 cx: &mut Context<Self>,
2560 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2561 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2562 let prompt = self.on_prompt_for_open_path.take().unwrap();
2563 let rx = prompt(self, lister, window, cx);
2564 self.on_prompt_for_open_path = Some(prompt);
2565 rx
2566 } else {
2567 let (tx, rx) = oneshot::channel();
2568 let abs_path = cx.prompt_for_paths(path_prompt_options);
2569
2570 cx.spawn_in(window, async move |workspace, cx| {
2571 let Ok(result) = abs_path.await else {
2572 return Ok(());
2573 };
2574
2575 match result {
2576 Ok(result) => {
2577 tx.send(result).ok();
2578 }
2579 Err(err) => {
2580 let rx = workspace.update_in(cx, |workspace, window, cx| {
2581 workspace.show_portal_error(err.to_string(), cx);
2582 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2583 let rx = prompt(workspace, lister, window, cx);
2584 workspace.on_prompt_for_open_path = Some(prompt);
2585 rx
2586 })?;
2587 if let Ok(path) = rx.await {
2588 tx.send(path).ok();
2589 }
2590 }
2591 };
2592 anyhow::Ok(())
2593 })
2594 .detach();
2595
2596 rx
2597 }
2598 }
2599
2600 pub fn prompt_for_new_path(
2601 &mut self,
2602 lister: DirectoryLister,
2603 suggested_name: Option<String>,
2604 window: &mut Window,
2605 cx: &mut Context<Self>,
2606 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2607 if self.project.read(cx).is_via_collab()
2608 || self.project.read(cx).is_via_remote_server()
2609 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2610 {
2611 let prompt = self.on_prompt_for_new_path.take().unwrap();
2612 let rx = prompt(self, lister, suggested_name, window, cx);
2613 self.on_prompt_for_new_path = Some(prompt);
2614 return rx;
2615 }
2616
2617 let (tx, rx) = oneshot::channel();
2618 cx.spawn_in(window, async move |workspace, cx| {
2619 let abs_path = workspace.update(cx, |workspace, cx| {
2620 let relative_to = workspace
2621 .most_recent_active_path(cx)
2622 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2623 .or_else(|| {
2624 let project = workspace.project.read(cx);
2625 project.visible_worktrees(cx).find_map(|worktree| {
2626 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2627 })
2628 })
2629 .or_else(std::env::home_dir)
2630 .unwrap_or_else(|| PathBuf::from(""));
2631 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2632 })?;
2633 let abs_path = match abs_path.await? {
2634 Ok(path) => path,
2635 Err(err) => {
2636 let rx = workspace.update_in(cx, |workspace, window, cx| {
2637 workspace.show_portal_error(err.to_string(), cx);
2638
2639 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2640 let rx = prompt(workspace, lister, suggested_name, window, cx);
2641 workspace.on_prompt_for_new_path = Some(prompt);
2642 rx
2643 })?;
2644 if let Ok(path) = rx.await {
2645 tx.send(path).ok();
2646 }
2647 return anyhow::Ok(());
2648 }
2649 };
2650
2651 tx.send(abs_path.map(|path| vec![path])).ok();
2652 anyhow::Ok(())
2653 })
2654 .detach();
2655
2656 rx
2657 }
2658
2659 pub fn titlebar_item(&self) -> Option<AnyView> {
2660 self.titlebar_item.clone()
2661 }
2662
2663 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2664 /// When set, git-related operations should use this worktree instead of deriving
2665 /// the active worktree from the focused file.
2666 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2667 self.active_worktree_override
2668 }
2669
2670 pub fn set_active_worktree_override(
2671 &mut self,
2672 worktree_id: Option<WorktreeId>,
2673 cx: &mut Context<Self>,
2674 ) {
2675 self.active_worktree_override = worktree_id;
2676 cx.notify();
2677 }
2678
2679 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2680 self.active_worktree_override = None;
2681 cx.notify();
2682 }
2683
2684 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2685 ///
2686 /// If the given workspace has a local project, then it will be passed
2687 /// to the callback. Otherwise, a new empty window will be created.
2688 pub fn with_local_workspace<T, F>(
2689 &mut self,
2690 window: &mut Window,
2691 cx: &mut Context<Self>,
2692 callback: F,
2693 ) -> Task<Result<T>>
2694 where
2695 T: 'static,
2696 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2697 {
2698 if self.project.read(cx).is_local() {
2699 Task::ready(Ok(callback(self, window, cx)))
2700 } else {
2701 let env = self.project.read(cx).cli_environment(cx);
2702 let task = Self::new_local(
2703 Vec::new(),
2704 self.app_state.clone(),
2705 None,
2706 env,
2707 None,
2708 true,
2709 cx,
2710 );
2711 cx.spawn_in(window, async move |_vh, cx| {
2712 let OpenResult {
2713 window: multi_workspace_window,
2714 ..
2715 } = task.await?;
2716 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2717 let workspace = multi_workspace.workspace().clone();
2718 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2719 })
2720 })
2721 }
2722 }
2723
2724 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2725 ///
2726 /// If the given workspace has a local project, then it will be passed
2727 /// to the callback. Otherwise, a new empty window will be created.
2728 pub fn with_local_or_wsl_workspace<T, F>(
2729 &mut self,
2730 window: &mut Window,
2731 cx: &mut Context<Self>,
2732 callback: F,
2733 ) -> Task<Result<T>>
2734 where
2735 T: 'static,
2736 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2737 {
2738 let project = self.project.read(cx);
2739 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
2740 Task::ready(Ok(callback(self, window, cx)))
2741 } else {
2742 let env = self.project.read(cx).cli_environment(cx);
2743 let task = Self::new_local(
2744 Vec::new(),
2745 self.app_state.clone(),
2746 None,
2747 env,
2748 None,
2749 true,
2750 cx,
2751 );
2752 cx.spawn_in(window, async move |_vh, cx| {
2753 let OpenResult {
2754 window: multi_workspace_window,
2755 ..
2756 } = task.await?;
2757 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2758 let workspace = multi_workspace.workspace().clone();
2759 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2760 })
2761 })
2762 }
2763 }
2764
2765 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2766 self.project.read(cx).worktrees(cx)
2767 }
2768
2769 pub fn visible_worktrees<'a>(
2770 &self,
2771 cx: &'a App,
2772 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2773 self.project.read(cx).visible_worktrees(cx)
2774 }
2775
2776 #[cfg(any(test, feature = "test-support"))]
2777 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
2778 let futures = self
2779 .worktrees(cx)
2780 .filter_map(|worktree| worktree.read(cx).as_local())
2781 .map(|worktree| worktree.scan_complete())
2782 .collect::<Vec<_>>();
2783 async move {
2784 for future in futures {
2785 future.await;
2786 }
2787 }
2788 }
2789
2790 pub fn close_global(cx: &mut App) {
2791 cx.defer(|cx| {
2792 cx.windows().iter().find(|window| {
2793 window
2794 .update(cx, |_, window, _| {
2795 if window.is_window_active() {
2796 //This can only get called when the window's project connection has been lost
2797 //so we don't need to prompt the user for anything and instead just close the window
2798 window.remove_window();
2799 true
2800 } else {
2801 false
2802 }
2803 })
2804 .unwrap_or(false)
2805 });
2806 });
2807 }
2808
2809 pub fn move_focused_panel_to_next_position(
2810 &mut self,
2811 _: &MoveFocusedPanelToNextPosition,
2812 window: &mut Window,
2813 cx: &mut Context<Self>,
2814 ) {
2815 let docks = self.all_docks();
2816 let active_dock = docks
2817 .into_iter()
2818 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
2819
2820 if let Some(dock) = active_dock {
2821 dock.update(cx, |dock, cx| {
2822 let active_panel = dock
2823 .active_panel()
2824 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
2825
2826 if let Some(panel) = active_panel {
2827 panel.move_to_next_position(window, cx);
2828 }
2829 })
2830 }
2831 }
2832
2833 pub fn prepare_to_close(
2834 &mut self,
2835 close_intent: CloseIntent,
2836 window: &mut Window,
2837 cx: &mut Context<Self>,
2838 ) -> Task<Result<bool>> {
2839 let active_call = self.active_global_call();
2840
2841 cx.spawn_in(window, async move |this, cx| {
2842 this.update(cx, |this, _| {
2843 if close_intent == CloseIntent::CloseWindow {
2844 this.removing = true;
2845 }
2846 })?;
2847
2848 let workspace_count = cx.update(|_window, cx| {
2849 cx.windows()
2850 .iter()
2851 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
2852 .count()
2853 })?;
2854
2855 #[cfg(target_os = "macos")]
2856 let save_last_workspace = false;
2857
2858 // On Linux and Windows, closing the last window should restore the last workspace.
2859 #[cfg(not(target_os = "macos"))]
2860 let save_last_workspace = {
2861 let remaining_workspaces = cx.update(|_window, cx| {
2862 cx.windows()
2863 .iter()
2864 .filter_map(|window| window.downcast::<MultiWorkspace>())
2865 .filter_map(|multi_workspace| {
2866 multi_workspace
2867 .update(cx, |multi_workspace, _, cx| {
2868 multi_workspace.workspace().read(cx).removing
2869 })
2870 .ok()
2871 })
2872 .filter(|removing| !removing)
2873 .count()
2874 })?;
2875
2876 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
2877 };
2878
2879 if let Some(active_call) = active_call
2880 && workspace_count == 1
2881 && cx
2882 .update(|_window, cx| active_call.0.is_in_room(cx))
2883 .unwrap_or(false)
2884 {
2885 if close_intent == CloseIntent::CloseWindow {
2886 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
2887 let answer = cx.update(|window, cx| {
2888 window.prompt(
2889 PromptLevel::Warning,
2890 "Do you want to leave the current call?",
2891 None,
2892 &["Close window and hang up", "Cancel"],
2893 cx,
2894 )
2895 })?;
2896
2897 if answer.await.log_err() == Some(1) {
2898 return anyhow::Ok(false);
2899 } else {
2900 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
2901 task.await.log_err();
2902 }
2903 }
2904 }
2905 if close_intent == CloseIntent::ReplaceWindow {
2906 _ = cx.update(|_window, cx| {
2907 let multi_workspace = cx
2908 .windows()
2909 .iter()
2910 .filter_map(|window| window.downcast::<MultiWorkspace>())
2911 .next()
2912 .unwrap();
2913 let project = multi_workspace
2914 .read(cx)?
2915 .workspace()
2916 .read(cx)
2917 .project
2918 .clone();
2919 if project.read(cx).is_shared() {
2920 active_call.0.unshare_project(project, cx)?;
2921 }
2922 Ok::<_, anyhow::Error>(())
2923 });
2924 }
2925 }
2926
2927 let save_result = this
2928 .update_in(cx, |this, window, cx| {
2929 this.save_all_internal(SaveIntent::Close, window, cx)
2930 })?
2931 .await;
2932
2933 // If we're not quitting, but closing, we remove the workspace from
2934 // the current session.
2935 if close_intent != CloseIntent::Quit
2936 && !save_last_workspace
2937 && save_result.as_ref().is_ok_and(|&res| res)
2938 {
2939 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
2940 .await;
2941 }
2942
2943 save_result
2944 })
2945 }
2946
2947 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
2948 self.save_all_internal(
2949 action.save_intent.unwrap_or(SaveIntent::SaveAll),
2950 window,
2951 cx,
2952 )
2953 .detach_and_log_err(cx);
2954 }
2955
2956 fn send_keystrokes(
2957 &mut self,
2958 action: &SendKeystrokes,
2959 window: &mut Window,
2960 cx: &mut Context<Self>,
2961 ) {
2962 let keystrokes: Vec<Keystroke> = action
2963 .0
2964 .split(' ')
2965 .flat_map(|k| Keystroke::parse(k).log_err())
2966 .map(|k| {
2967 cx.keyboard_mapper()
2968 .map_key_equivalent(k, false)
2969 .inner()
2970 .clone()
2971 })
2972 .collect();
2973 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
2974 }
2975
2976 pub fn send_keystrokes_impl(
2977 &mut self,
2978 keystrokes: Vec<Keystroke>,
2979 window: &mut Window,
2980 cx: &mut Context<Self>,
2981 ) -> Shared<Task<()>> {
2982 let mut state = self.dispatching_keystrokes.borrow_mut();
2983 if !state.dispatched.insert(keystrokes.clone()) {
2984 cx.propagate();
2985 return state.task.clone().unwrap();
2986 }
2987
2988 state.queue.extend(keystrokes);
2989
2990 let keystrokes = self.dispatching_keystrokes.clone();
2991 if state.task.is_none() {
2992 state.task = Some(
2993 window
2994 .spawn(cx, async move |cx| {
2995 // limit to 100 keystrokes to avoid infinite recursion.
2996 for _ in 0..100 {
2997 let keystroke = {
2998 let mut state = keystrokes.borrow_mut();
2999 let Some(keystroke) = state.queue.pop_front() else {
3000 state.dispatched.clear();
3001 state.task.take();
3002 return;
3003 };
3004 keystroke
3005 };
3006 cx.update(|window, cx| {
3007 let focused = window.focused(cx);
3008 window.dispatch_keystroke(keystroke.clone(), cx);
3009 if window.focused(cx) != focused {
3010 // dispatch_keystroke may cause the focus to change.
3011 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
3012 // And we need that to happen before the next keystroke to keep vim mode happy...
3013 // (Note that the tests always do this implicitly, so you must manually test with something like:
3014 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
3015 // )
3016 window.draw(cx).clear();
3017 }
3018 })
3019 .ok();
3020
3021 // Yield between synthetic keystrokes so deferred focus and
3022 // other effects can settle before dispatching the next key.
3023 yield_now().await;
3024 }
3025
3026 *keystrokes.borrow_mut() = Default::default();
3027 log::error!("over 100 keystrokes passed to send_keystrokes");
3028 })
3029 .shared(),
3030 );
3031 }
3032 state.task.clone().unwrap()
3033 }
3034
3035 fn save_all_internal(
3036 &mut self,
3037 mut save_intent: SaveIntent,
3038 window: &mut Window,
3039 cx: &mut Context<Self>,
3040 ) -> Task<Result<bool>> {
3041 if self.project.read(cx).is_disconnected(cx) {
3042 return Task::ready(Ok(true));
3043 }
3044 let dirty_items = self
3045 .panes
3046 .iter()
3047 .flat_map(|pane| {
3048 pane.read(cx).items().filter_map(|item| {
3049 if item.is_dirty(cx) {
3050 item.tab_content_text(0, cx);
3051 Some((pane.downgrade(), item.boxed_clone()))
3052 } else {
3053 None
3054 }
3055 })
3056 })
3057 .collect::<Vec<_>>();
3058
3059 let project = self.project.clone();
3060 cx.spawn_in(window, async move |workspace, cx| {
3061 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3062 let (serialize_tasks, remaining_dirty_items) =
3063 workspace.update_in(cx, |workspace, window, cx| {
3064 let mut remaining_dirty_items = Vec::new();
3065 let mut serialize_tasks = Vec::new();
3066 for (pane, item) in dirty_items {
3067 if let Some(task) = item
3068 .to_serializable_item_handle(cx)
3069 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3070 {
3071 serialize_tasks.push(task);
3072 } else {
3073 remaining_dirty_items.push((pane, item));
3074 }
3075 }
3076 (serialize_tasks, remaining_dirty_items)
3077 })?;
3078
3079 futures::future::try_join_all(serialize_tasks).await?;
3080
3081 if !remaining_dirty_items.is_empty() {
3082 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3083 }
3084
3085 if remaining_dirty_items.len() > 1 {
3086 let answer = workspace.update_in(cx, |_, window, cx| {
3087 let detail = Pane::file_names_for_prompt(
3088 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3089 cx,
3090 );
3091 window.prompt(
3092 PromptLevel::Warning,
3093 "Do you want to save all changes in the following files?",
3094 Some(&detail),
3095 &["Save all", "Discard all", "Cancel"],
3096 cx,
3097 )
3098 })?;
3099 match answer.await.log_err() {
3100 Some(0) => save_intent = SaveIntent::SaveAll,
3101 Some(1) => save_intent = SaveIntent::Skip,
3102 Some(2) => return Ok(false),
3103 _ => {}
3104 }
3105 }
3106
3107 remaining_dirty_items
3108 } else {
3109 dirty_items
3110 };
3111
3112 for (pane, item) in dirty_items {
3113 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3114 (
3115 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3116 item.project_entry_ids(cx),
3117 )
3118 })?;
3119 if (singleton || !project_entry_ids.is_empty())
3120 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3121 {
3122 return Ok(false);
3123 }
3124 }
3125 Ok(true)
3126 })
3127 }
3128
3129 pub fn open_workspace_for_paths(
3130 &mut self,
3131 replace_current_window: bool,
3132 paths: Vec<PathBuf>,
3133 window: &mut Window,
3134 cx: &mut Context<Self>,
3135 ) -> Task<Result<Entity<Workspace>>> {
3136 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
3137 let is_remote = self.project.read(cx).is_via_collab();
3138 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3139 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3140
3141 let window_to_replace = if replace_current_window {
3142 window_handle
3143 } else if is_remote || has_worktree || has_dirty_items {
3144 None
3145 } else {
3146 window_handle
3147 };
3148 let app_state = self.app_state.clone();
3149
3150 cx.spawn(async move |_, cx| {
3151 let OpenResult { workspace, .. } = cx
3152 .update(|cx| {
3153 open_paths(
3154 &paths,
3155 app_state,
3156 OpenOptions {
3157 replace_window: window_to_replace,
3158 ..Default::default()
3159 },
3160 cx,
3161 )
3162 })
3163 .await?;
3164 Ok(workspace)
3165 })
3166 }
3167
3168 #[allow(clippy::type_complexity)]
3169 pub fn open_paths(
3170 &mut self,
3171 mut abs_paths: Vec<PathBuf>,
3172 options: OpenOptions,
3173 pane: Option<WeakEntity<Pane>>,
3174 window: &mut Window,
3175 cx: &mut Context<Self>,
3176 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3177 let fs = self.app_state.fs.clone();
3178
3179 let caller_ordered_abs_paths = abs_paths.clone();
3180
3181 // Sort the paths to ensure we add worktrees for parents before their children.
3182 abs_paths.sort_unstable();
3183 cx.spawn_in(window, async move |this, cx| {
3184 let mut tasks = Vec::with_capacity(abs_paths.len());
3185
3186 for abs_path in &abs_paths {
3187 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3188 OpenVisible::All => Some(true),
3189 OpenVisible::None => Some(false),
3190 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3191 Some(Some(metadata)) => Some(!metadata.is_dir),
3192 Some(None) => Some(true),
3193 None => None,
3194 },
3195 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3196 Some(Some(metadata)) => Some(metadata.is_dir),
3197 Some(None) => Some(false),
3198 None => None,
3199 },
3200 };
3201 let project_path = match visible {
3202 Some(visible) => match this
3203 .update(cx, |this, cx| {
3204 Workspace::project_path_for_path(
3205 this.project.clone(),
3206 abs_path,
3207 visible,
3208 cx,
3209 )
3210 })
3211 .log_err()
3212 {
3213 Some(project_path) => project_path.await.log_err(),
3214 None => None,
3215 },
3216 None => None,
3217 };
3218
3219 let this = this.clone();
3220 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3221 let fs = fs.clone();
3222 let pane = pane.clone();
3223 let task = cx.spawn(async move |cx| {
3224 let (_worktree, project_path) = project_path?;
3225 if fs.is_dir(&abs_path).await {
3226 // Opening a directory should not race to update the active entry.
3227 // We'll select/reveal a deterministic final entry after all paths finish opening.
3228 None
3229 } else {
3230 Some(
3231 this.update_in(cx, |this, window, cx| {
3232 this.open_path(
3233 project_path,
3234 pane,
3235 options.focus.unwrap_or(true),
3236 window,
3237 cx,
3238 )
3239 })
3240 .ok()?
3241 .await,
3242 )
3243 }
3244 });
3245 tasks.push(task);
3246 }
3247
3248 let results = futures::future::join_all(tasks).await;
3249
3250 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3251 let mut winner: Option<(PathBuf, bool)> = None;
3252 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3253 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3254 if !metadata.is_dir {
3255 winner = Some((abs_path, false));
3256 break;
3257 }
3258 if winner.is_none() {
3259 winner = Some((abs_path, true));
3260 }
3261 } else if winner.is_none() {
3262 winner = Some((abs_path, false));
3263 }
3264 }
3265
3266 // Compute the winner entry id on the foreground thread and emit once, after all
3267 // paths finish opening. This avoids races between concurrently-opening paths
3268 // (directories in particular) and makes the resulting project panel selection
3269 // deterministic.
3270 if let Some((winner_abs_path, winner_is_dir)) = winner {
3271 'emit_winner: {
3272 let winner_abs_path: Arc<Path> =
3273 SanitizedPath::new(&winner_abs_path).as_path().into();
3274
3275 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3276 OpenVisible::All => true,
3277 OpenVisible::None => false,
3278 OpenVisible::OnlyFiles => !winner_is_dir,
3279 OpenVisible::OnlyDirectories => winner_is_dir,
3280 };
3281
3282 let Some(worktree_task) = this
3283 .update(cx, |workspace, cx| {
3284 workspace.project.update(cx, |project, cx| {
3285 project.find_or_create_worktree(
3286 winner_abs_path.as_ref(),
3287 visible,
3288 cx,
3289 )
3290 })
3291 })
3292 .ok()
3293 else {
3294 break 'emit_winner;
3295 };
3296
3297 let Ok((worktree, _)) = worktree_task.await else {
3298 break 'emit_winner;
3299 };
3300
3301 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3302 let worktree = worktree.read(cx);
3303 let worktree_abs_path = worktree.abs_path();
3304 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3305 worktree.root_entry()
3306 } else {
3307 winner_abs_path
3308 .strip_prefix(worktree_abs_path.as_ref())
3309 .ok()
3310 .and_then(|relative_path| {
3311 let relative_path =
3312 RelPath::new(relative_path, PathStyle::local())
3313 .log_err()?;
3314 worktree.entry_for_path(&relative_path)
3315 })
3316 }?;
3317 Some(entry.id)
3318 }) else {
3319 break 'emit_winner;
3320 };
3321
3322 this.update(cx, |workspace, cx| {
3323 workspace.project.update(cx, |_, cx| {
3324 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3325 });
3326 })
3327 .ok();
3328 }
3329 }
3330
3331 results
3332 })
3333 }
3334
3335 pub fn open_resolved_path(
3336 &mut self,
3337 path: ResolvedPath,
3338 window: &mut Window,
3339 cx: &mut Context<Self>,
3340 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3341 match path {
3342 ResolvedPath::ProjectPath { project_path, .. } => {
3343 self.open_path(project_path, None, true, window, cx)
3344 }
3345 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3346 PathBuf::from(path),
3347 OpenOptions {
3348 visible: Some(OpenVisible::None),
3349 ..Default::default()
3350 },
3351 window,
3352 cx,
3353 ),
3354 }
3355 }
3356
3357 pub fn absolute_path_of_worktree(
3358 &self,
3359 worktree_id: WorktreeId,
3360 cx: &mut Context<Self>,
3361 ) -> Option<PathBuf> {
3362 self.project
3363 .read(cx)
3364 .worktree_for_id(worktree_id, cx)
3365 // TODO: use `abs_path` or `root_dir`
3366 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3367 }
3368
3369 fn add_folder_to_project(
3370 &mut self,
3371 _: &AddFolderToProject,
3372 window: &mut Window,
3373 cx: &mut Context<Self>,
3374 ) {
3375 let project = self.project.read(cx);
3376 if project.is_via_collab() {
3377 self.show_error(
3378 &anyhow!("You cannot add folders to someone else's project"),
3379 cx,
3380 );
3381 return;
3382 }
3383 let paths = self.prompt_for_open_path(
3384 PathPromptOptions {
3385 files: false,
3386 directories: true,
3387 multiple: true,
3388 prompt: None,
3389 },
3390 DirectoryLister::Project(self.project.clone()),
3391 window,
3392 cx,
3393 );
3394 cx.spawn_in(window, async move |this, cx| {
3395 if let Some(paths) = paths.await.log_err().flatten() {
3396 let results = this
3397 .update_in(cx, |this, window, cx| {
3398 this.open_paths(
3399 paths,
3400 OpenOptions {
3401 visible: Some(OpenVisible::All),
3402 ..Default::default()
3403 },
3404 None,
3405 window,
3406 cx,
3407 )
3408 })?
3409 .await;
3410 for result in results.into_iter().flatten() {
3411 result.log_err();
3412 }
3413 }
3414 anyhow::Ok(())
3415 })
3416 .detach_and_log_err(cx);
3417 }
3418
3419 pub fn project_path_for_path(
3420 project: Entity<Project>,
3421 abs_path: &Path,
3422 visible: bool,
3423 cx: &mut App,
3424 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3425 let entry = project.update(cx, |project, cx| {
3426 project.find_or_create_worktree(abs_path, visible, cx)
3427 });
3428 cx.spawn(async move |cx| {
3429 let (worktree, path) = entry.await?;
3430 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3431 Ok((worktree, ProjectPath { worktree_id, path }))
3432 })
3433 }
3434
3435 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3436 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3437 }
3438
3439 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3440 self.items_of_type(cx).max_by_key(|item| item.item_id())
3441 }
3442
3443 pub fn items_of_type<'a, T: Item>(
3444 &'a self,
3445 cx: &'a App,
3446 ) -> impl 'a + Iterator<Item = Entity<T>> {
3447 self.panes
3448 .iter()
3449 .flat_map(|pane| pane.read(cx).items_of_type())
3450 }
3451
3452 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3453 self.active_pane().read(cx).active_item()
3454 }
3455
3456 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3457 let item = self.active_item(cx)?;
3458 item.to_any_view().downcast::<I>().ok()
3459 }
3460
3461 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3462 self.active_item(cx).and_then(|item| item.project_path(cx))
3463 }
3464
3465 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3466 self.recent_navigation_history_iter(cx)
3467 .filter_map(|(path, abs_path)| {
3468 let worktree = self
3469 .project
3470 .read(cx)
3471 .worktree_for_id(path.worktree_id, cx)?;
3472 if worktree.read(cx).is_visible() {
3473 abs_path
3474 } else {
3475 None
3476 }
3477 })
3478 .next()
3479 }
3480
3481 pub fn save_active_item(
3482 &mut self,
3483 save_intent: SaveIntent,
3484 window: &mut Window,
3485 cx: &mut App,
3486 ) -> Task<Result<()>> {
3487 let project = self.project.clone();
3488 let pane = self.active_pane();
3489 let item = pane.read(cx).active_item();
3490 let pane = pane.downgrade();
3491
3492 window.spawn(cx, async move |cx| {
3493 if let Some(item) = item {
3494 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3495 .await
3496 .map(|_| ())
3497 } else {
3498 Ok(())
3499 }
3500 })
3501 }
3502
3503 pub fn close_inactive_items_and_panes(
3504 &mut self,
3505 action: &CloseInactiveTabsAndPanes,
3506 window: &mut Window,
3507 cx: &mut Context<Self>,
3508 ) {
3509 if let Some(task) = self.close_all_internal(
3510 true,
3511 action.save_intent.unwrap_or(SaveIntent::Close),
3512 window,
3513 cx,
3514 ) {
3515 task.detach_and_log_err(cx)
3516 }
3517 }
3518
3519 pub fn close_all_items_and_panes(
3520 &mut self,
3521 action: &CloseAllItemsAndPanes,
3522 window: &mut Window,
3523 cx: &mut Context<Self>,
3524 ) {
3525 if let Some(task) = self.close_all_internal(
3526 false,
3527 action.save_intent.unwrap_or(SaveIntent::Close),
3528 window,
3529 cx,
3530 ) {
3531 task.detach_and_log_err(cx)
3532 }
3533 }
3534
3535 /// Closes the active item across all panes.
3536 pub fn close_item_in_all_panes(
3537 &mut self,
3538 action: &CloseItemInAllPanes,
3539 window: &mut Window,
3540 cx: &mut Context<Self>,
3541 ) {
3542 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3543 return;
3544 };
3545
3546 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3547 let close_pinned = action.close_pinned;
3548
3549 if let Some(project_path) = active_item.project_path(cx) {
3550 self.close_items_with_project_path(
3551 &project_path,
3552 save_intent,
3553 close_pinned,
3554 window,
3555 cx,
3556 );
3557 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3558 let item_id = active_item.item_id();
3559 self.active_pane().update(cx, |pane, cx| {
3560 pane.close_item_by_id(item_id, save_intent, window, cx)
3561 .detach_and_log_err(cx);
3562 });
3563 }
3564 }
3565
3566 /// Closes all items with the given project path across all panes.
3567 pub fn close_items_with_project_path(
3568 &mut self,
3569 project_path: &ProjectPath,
3570 save_intent: SaveIntent,
3571 close_pinned: bool,
3572 window: &mut Window,
3573 cx: &mut Context<Self>,
3574 ) {
3575 let panes = self.panes().to_vec();
3576 for pane in panes {
3577 pane.update(cx, |pane, cx| {
3578 pane.close_items_for_project_path(
3579 project_path,
3580 save_intent,
3581 close_pinned,
3582 window,
3583 cx,
3584 )
3585 .detach_and_log_err(cx);
3586 });
3587 }
3588 }
3589
3590 fn close_all_internal(
3591 &mut self,
3592 retain_active_pane: bool,
3593 save_intent: SaveIntent,
3594 window: &mut Window,
3595 cx: &mut Context<Self>,
3596 ) -> Option<Task<Result<()>>> {
3597 let current_pane = self.active_pane();
3598
3599 let mut tasks = Vec::new();
3600
3601 if retain_active_pane {
3602 let current_pane_close = current_pane.update(cx, |pane, cx| {
3603 pane.close_other_items(
3604 &CloseOtherItems {
3605 save_intent: None,
3606 close_pinned: false,
3607 },
3608 None,
3609 window,
3610 cx,
3611 )
3612 });
3613
3614 tasks.push(current_pane_close);
3615 }
3616
3617 for pane in self.panes() {
3618 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3619 continue;
3620 }
3621
3622 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3623 pane.close_all_items(
3624 &CloseAllItems {
3625 save_intent: Some(save_intent),
3626 close_pinned: false,
3627 },
3628 window,
3629 cx,
3630 )
3631 });
3632
3633 tasks.push(close_pane_items)
3634 }
3635
3636 if tasks.is_empty() {
3637 None
3638 } else {
3639 Some(cx.spawn_in(window, async move |_, _| {
3640 for task in tasks {
3641 task.await?
3642 }
3643 Ok(())
3644 }))
3645 }
3646 }
3647
3648 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3649 self.dock_at_position(position).read(cx).is_open()
3650 }
3651
3652 pub fn toggle_dock(
3653 &mut self,
3654 dock_side: DockPosition,
3655 window: &mut Window,
3656 cx: &mut Context<Self>,
3657 ) {
3658 let mut focus_center = false;
3659 let mut reveal_dock = false;
3660
3661 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3662 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3663
3664 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3665 telemetry::event!(
3666 "Panel Button Clicked",
3667 name = panel.persistent_name(),
3668 toggle_state = !was_visible
3669 );
3670 }
3671 if was_visible {
3672 self.save_open_dock_positions(cx);
3673 }
3674
3675 let dock = self.dock_at_position(dock_side);
3676 dock.update(cx, |dock, cx| {
3677 dock.set_open(!was_visible, window, cx);
3678
3679 if dock.active_panel().is_none() {
3680 let Some(panel_ix) = dock
3681 .first_enabled_panel_idx(cx)
3682 .log_with_level(log::Level::Info)
3683 else {
3684 return;
3685 };
3686 dock.activate_panel(panel_ix, window, cx);
3687 }
3688
3689 if let Some(active_panel) = dock.active_panel() {
3690 if was_visible {
3691 if active_panel
3692 .panel_focus_handle(cx)
3693 .contains_focused(window, cx)
3694 {
3695 focus_center = true;
3696 }
3697 } else {
3698 let focus_handle = &active_panel.panel_focus_handle(cx);
3699 window.focus(focus_handle, cx);
3700 reveal_dock = true;
3701 }
3702 }
3703 });
3704
3705 if reveal_dock {
3706 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3707 }
3708
3709 if focus_center {
3710 self.active_pane
3711 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3712 }
3713
3714 cx.notify();
3715 self.serialize_workspace(window, cx);
3716 }
3717
3718 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3719 self.all_docks().into_iter().find(|&dock| {
3720 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3721 })
3722 }
3723
3724 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3725 if let Some(dock) = self.active_dock(window, cx).cloned() {
3726 self.save_open_dock_positions(cx);
3727 dock.update(cx, |dock, cx| {
3728 dock.set_open(false, window, cx);
3729 });
3730 return true;
3731 }
3732 false
3733 }
3734
3735 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3736 self.save_open_dock_positions(cx);
3737 for dock in self.all_docks() {
3738 dock.update(cx, |dock, cx| {
3739 dock.set_open(false, window, cx);
3740 });
3741 }
3742
3743 cx.focus_self(window);
3744 cx.notify();
3745 self.serialize_workspace(window, cx);
3746 }
3747
3748 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
3749 self.all_docks()
3750 .into_iter()
3751 .filter_map(|dock| {
3752 let dock_ref = dock.read(cx);
3753 if dock_ref.is_open() {
3754 Some(dock_ref.position())
3755 } else {
3756 None
3757 }
3758 })
3759 .collect()
3760 }
3761
3762 /// Saves the positions of currently open docks.
3763 ///
3764 /// Updates `last_open_dock_positions` with positions of all currently open
3765 /// docks, to later be restored by the 'Toggle All Docks' action.
3766 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
3767 let open_dock_positions = self.get_open_dock_positions(cx);
3768 if !open_dock_positions.is_empty() {
3769 self.last_open_dock_positions = open_dock_positions;
3770 }
3771 }
3772
3773 /// Toggles all docks between open and closed states.
3774 ///
3775 /// If any docks are open, closes all and remembers their positions. If all
3776 /// docks are closed, restores the last remembered dock configuration.
3777 fn toggle_all_docks(
3778 &mut self,
3779 _: &ToggleAllDocks,
3780 window: &mut Window,
3781 cx: &mut Context<Self>,
3782 ) {
3783 let open_dock_positions = self.get_open_dock_positions(cx);
3784
3785 if !open_dock_positions.is_empty() {
3786 self.close_all_docks(window, cx);
3787 } else if !self.last_open_dock_positions.is_empty() {
3788 self.restore_last_open_docks(window, cx);
3789 }
3790 }
3791
3792 /// Reopens docks from the most recently remembered configuration.
3793 ///
3794 /// Opens all docks whose positions are stored in `last_open_dock_positions`
3795 /// and clears the stored positions.
3796 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3797 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
3798
3799 for position in positions_to_open {
3800 let dock = self.dock_at_position(position);
3801 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
3802 }
3803
3804 cx.focus_self(window);
3805 cx.notify();
3806 self.serialize_workspace(window, cx);
3807 }
3808
3809 /// Transfer focus to the panel of the given type.
3810 pub fn focus_panel<T: Panel>(
3811 &mut self,
3812 window: &mut Window,
3813 cx: &mut Context<Self>,
3814 ) -> Option<Entity<T>> {
3815 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
3816 panel.to_any().downcast().ok()
3817 }
3818
3819 /// Focus the panel of the given type if it isn't already focused. If it is
3820 /// already focused, then transfer focus back to the workspace center.
3821 /// When the `close_panel_on_toggle` setting is enabled, also closes the
3822 /// panel when transferring focus back to the center.
3823 pub fn toggle_panel_focus<T: Panel>(
3824 &mut self,
3825 window: &mut Window,
3826 cx: &mut Context<Self>,
3827 ) -> bool {
3828 let mut did_focus_panel = false;
3829 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
3830 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
3831 did_focus_panel
3832 });
3833
3834 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
3835 self.close_panel::<T>(window, cx);
3836 }
3837
3838 telemetry::event!(
3839 "Panel Button Clicked",
3840 name = T::persistent_name(),
3841 toggle_state = did_focus_panel
3842 );
3843
3844 did_focus_panel
3845 }
3846
3847 pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3848 if let Some(item) = self.active_item(cx) {
3849 item.item_focus_handle(cx).focus(window, cx);
3850 } else {
3851 log::error!("Could not find a focus target when switching focus to the center panes",);
3852 }
3853 }
3854
3855 pub fn activate_panel_for_proto_id(
3856 &mut self,
3857 panel_id: PanelId,
3858 window: &mut Window,
3859 cx: &mut Context<Self>,
3860 ) -> Option<Arc<dyn PanelHandle>> {
3861 let mut panel = None;
3862 for dock in self.all_docks() {
3863 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
3864 panel = dock.update(cx, |dock, cx| {
3865 dock.activate_panel(panel_index, window, cx);
3866 dock.set_open(true, window, cx);
3867 dock.active_panel().cloned()
3868 });
3869 break;
3870 }
3871 }
3872
3873 if panel.is_some() {
3874 cx.notify();
3875 self.serialize_workspace(window, cx);
3876 }
3877
3878 panel
3879 }
3880
3881 /// Focus or unfocus the given panel type, depending on the given callback.
3882 fn focus_or_unfocus_panel<T: Panel>(
3883 &mut self,
3884 window: &mut Window,
3885 cx: &mut Context<Self>,
3886 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
3887 ) -> Option<Arc<dyn PanelHandle>> {
3888 let mut result_panel = None;
3889 let mut serialize = false;
3890 for dock in self.all_docks() {
3891 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3892 let mut focus_center = false;
3893 let panel = dock.update(cx, |dock, cx| {
3894 dock.activate_panel(panel_index, window, cx);
3895
3896 let panel = dock.active_panel().cloned();
3897 if let Some(panel) = panel.as_ref() {
3898 if should_focus(&**panel, window, cx) {
3899 dock.set_open(true, window, cx);
3900 panel.panel_focus_handle(cx).focus(window, cx);
3901 } else {
3902 focus_center = true;
3903 }
3904 }
3905 panel
3906 });
3907
3908 if focus_center {
3909 self.active_pane
3910 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3911 }
3912
3913 result_panel = panel;
3914 serialize = true;
3915 break;
3916 }
3917 }
3918
3919 if serialize {
3920 self.serialize_workspace(window, cx);
3921 }
3922
3923 cx.notify();
3924 result_panel
3925 }
3926
3927 /// Open the panel of the given type
3928 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3929 for dock in self.all_docks() {
3930 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3931 dock.update(cx, |dock, cx| {
3932 dock.activate_panel(panel_index, window, cx);
3933 dock.set_open(true, window, cx);
3934 });
3935 }
3936 }
3937 }
3938
3939 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
3940 for dock in self.all_docks().iter() {
3941 dock.update(cx, |dock, cx| {
3942 if dock.panel::<T>().is_some() {
3943 dock.set_open(false, window, cx)
3944 }
3945 })
3946 }
3947 }
3948
3949 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
3950 self.all_docks()
3951 .iter()
3952 .find_map(|dock| dock.read(cx).panel::<T>())
3953 }
3954
3955 fn dismiss_zoomed_items_to_reveal(
3956 &mut self,
3957 dock_to_reveal: Option<DockPosition>,
3958 window: &mut Window,
3959 cx: &mut Context<Self>,
3960 ) {
3961 // If a center pane is zoomed, unzoom it.
3962 for pane in &self.panes {
3963 if pane != &self.active_pane || dock_to_reveal.is_some() {
3964 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
3965 }
3966 }
3967
3968 // If another dock is zoomed, hide it.
3969 let mut focus_center = false;
3970 for dock in self.all_docks() {
3971 dock.update(cx, |dock, cx| {
3972 if Some(dock.position()) != dock_to_reveal
3973 && let Some(panel) = dock.active_panel()
3974 && panel.is_zoomed(window, cx)
3975 {
3976 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
3977 dock.set_open(false, window, cx);
3978 }
3979 });
3980 }
3981
3982 if focus_center {
3983 self.active_pane
3984 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3985 }
3986
3987 if self.zoomed_position != dock_to_reveal {
3988 self.zoomed = None;
3989 self.zoomed_position = None;
3990 cx.emit(Event::ZoomChanged);
3991 }
3992
3993 cx.notify();
3994 }
3995
3996 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
3997 let pane = cx.new(|cx| {
3998 let mut pane = Pane::new(
3999 self.weak_handle(),
4000 self.project.clone(),
4001 self.pane_history_timestamp.clone(),
4002 None,
4003 NewFile.boxed_clone(),
4004 true,
4005 window,
4006 cx,
4007 );
4008 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
4009 pane
4010 });
4011 cx.subscribe_in(&pane, window, Self::handle_pane_event)
4012 .detach();
4013 self.panes.push(pane.clone());
4014
4015 window.focus(&pane.focus_handle(cx), cx);
4016
4017 cx.emit(Event::PaneAdded(pane.clone()));
4018 pane
4019 }
4020
4021 pub fn add_item_to_center(
4022 &mut self,
4023 item: Box<dyn ItemHandle>,
4024 window: &mut Window,
4025 cx: &mut Context<Self>,
4026 ) -> bool {
4027 if let Some(center_pane) = self.last_active_center_pane.clone() {
4028 if let Some(center_pane) = center_pane.upgrade() {
4029 center_pane.update(cx, |pane, cx| {
4030 pane.add_item(item, true, true, None, window, cx)
4031 });
4032 true
4033 } else {
4034 false
4035 }
4036 } else {
4037 false
4038 }
4039 }
4040
4041 pub fn add_item_to_active_pane(
4042 &mut self,
4043 item: Box<dyn ItemHandle>,
4044 destination_index: Option<usize>,
4045 focus_item: bool,
4046 window: &mut Window,
4047 cx: &mut App,
4048 ) {
4049 self.add_item(
4050 self.active_pane.clone(),
4051 item,
4052 destination_index,
4053 false,
4054 focus_item,
4055 window,
4056 cx,
4057 )
4058 }
4059
4060 pub fn add_item(
4061 &mut self,
4062 pane: Entity<Pane>,
4063 item: Box<dyn ItemHandle>,
4064 destination_index: Option<usize>,
4065 activate_pane: bool,
4066 focus_item: bool,
4067 window: &mut Window,
4068 cx: &mut App,
4069 ) {
4070 pane.update(cx, |pane, cx| {
4071 pane.add_item(
4072 item,
4073 activate_pane,
4074 focus_item,
4075 destination_index,
4076 window,
4077 cx,
4078 )
4079 });
4080 }
4081
4082 pub fn split_item(
4083 &mut self,
4084 split_direction: SplitDirection,
4085 item: Box<dyn ItemHandle>,
4086 window: &mut Window,
4087 cx: &mut Context<Self>,
4088 ) {
4089 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4090 self.add_item(new_pane, item, None, true, true, window, cx);
4091 }
4092
4093 pub fn open_abs_path(
4094 &mut self,
4095 abs_path: PathBuf,
4096 options: OpenOptions,
4097 window: &mut Window,
4098 cx: &mut Context<Self>,
4099 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4100 cx.spawn_in(window, async move |workspace, cx| {
4101 let open_paths_task_result = workspace
4102 .update_in(cx, |workspace, window, cx| {
4103 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4104 })
4105 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4106 .await;
4107 anyhow::ensure!(
4108 open_paths_task_result.len() == 1,
4109 "open abs path {abs_path:?} task returned incorrect number of results"
4110 );
4111 match open_paths_task_result
4112 .into_iter()
4113 .next()
4114 .expect("ensured single task result")
4115 {
4116 Some(open_result) => {
4117 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4118 }
4119 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4120 }
4121 })
4122 }
4123
4124 pub fn split_abs_path(
4125 &mut self,
4126 abs_path: PathBuf,
4127 visible: bool,
4128 window: &mut Window,
4129 cx: &mut Context<Self>,
4130 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4131 let project_path_task =
4132 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4133 cx.spawn_in(window, async move |this, cx| {
4134 let (_, path) = project_path_task.await?;
4135 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4136 .await
4137 })
4138 }
4139
4140 pub fn open_path(
4141 &mut self,
4142 path: impl Into<ProjectPath>,
4143 pane: Option<WeakEntity<Pane>>,
4144 focus_item: bool,
4145 window: &mut Window,
4146 cx: &mut App,
4147 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4148 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4149 }
4150
4151 pub fn open_path_preview(
4152 &mut self,
4153 path: impl Into<ProjectPath>,
4154 pane: Option<WeakEntity<Pane>>,
4155 focus_item: bool,
4156 allow_preview: bool,
4157 activate: bool,
4158 window: &mut Window,
4159 cx: &mut App,
4160 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4161 let pane = pane.unwrap_or_else(|| {
4162 self.last_active_center_pane.clone().unwrap_or_else(|| {
4163 self.panes
4164 .first()
4165 .expect("There must be an active pane")
4166 .downgrade()
4167 })
4168 });
4169
4170 let project_path = path.into();
4171 let task = self.load_path(project_path.clone(), window, cx);
4172 window.spawn(cx, async move |cx| {
4173 let (project_entry_id, build_item) = task.await?;
4174
4175 pane.update_in(cx, |pane, window, cx| {
4176 pane.open_item(
4177 project_entry_id,
4178 project_path,
4179 focus_item,
4180 allow_preview,
4181 activate,
4182 None,
4183 window,
4184 cx,
4185 build_item,
4186 )
4187 })
4188 })
4189 }
4190
4191 pub fn split_path(
4192 &mut self,
4193 path: impl Into<ProjectPath>,
4194 window: &mut Window,
4195 cx: &mut Context<Self>,
4196 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4197 self.split_path_preview(path, false, None, window, cx)
4198 }
4199
4200 pub fn split_path_preview(
4201 &mut self,
4202 path: impl Into<ProjectPath>,
4203 allow_preview: bool,
4204 split_direction: Option<SplitDirection>,
4205 window: &mut Window,
4206 cx: &mut Context<Self>,
4207 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4208 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4209 self.panes
4210 .first()
4211 .expect("There must be an active pane")
4212 .downgrade()
4213 });
4214
4215 if let Member::Pane(center_pane) = &self.center.root
4216 && center_pane.read(cx).items_len() == 0
4217 {
4218 return self.open_path(path, Some(pane), true, window, cx);
4219 }
4220
4221 let project_path = path.into();
4222 let task = self.load_path(project_path.clone(), window, cx);
4223 cx.spawn_in(window, async move |this, cx| {
4224 let (project_entry_id, build_item) = task.await?;
4225 this.update_in(cx, move |this, window, cx| -> Option<_> {
4226 let pane = pane.upgrade()?;
4227 let new_pane = this.split_pane(
4228 pane,
4229 split_direction.unwrap_or(SplitDirection::Right),
4230 window,
4231 cx,
4232 );
4233 new_pane.update(cx, |new_pane, cx| {
4234 Some(new_pane.open_item(
4235 project_entry_id,
4236 project_path,
4237 true,
4238 allow_preview,
4239 true,
4240 None,
4241 window,
4242 cx,
4243 build_item,
4244 ))
4245 })
4246 })
4247 .map(|option| option.context("pane was dropped"))?
4248 })
4249 }
4250
4251 fn load_path(
4252 &mut self,
4253 path: ProjectPath,
4254 window: &mut Window,
4255 cx: &mut App,
4256 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4257 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4258 registry.open_path(self.project(), &path, window, cx)
4259 }
4260
4261 pub fn find_project_item<T>(
4262 &self,
4263 pane: &Entity<Pane>,
4264 project_item: &Entity<T::Item>,
4265 cx: &App,
4266 ) -> Option<Entity<T>>
4267 where
4268 T: ProjectItem,
4269 {
4270 use project::ProjectItem as _;
4271 let project_item = project_item.read(cx);
4272 let entry_id = project_item.entry_id(cx);
4273 let project_path = project_item.project_path(cx);
4274
4275 let mut item = None;
4276 if let Some(entry_id) = entry_id {
4277 item = pane.read(cx).item_for_entry(entry_id, cx);
4278 }
4279 if item.is_none()
4280 && let Some(project_path) = project_path
4281 {
4282 item = pane.read(cx).item_for_path(project_path, cx);
4283 }
4284
4285 item.and_then(|item| item.downcast::<T>())
4286 }
4287
4288 pub fn is_project_item_open<T>(
4289 &self,
4290 pane: &Entity<Pane>,
4291 project_item: &Entity<T::Item>,
4292 cx: &App,
4293 ) -> bool
4294 where
4295 T: ProjectItem,
4296 {
4297 self.find_project_item::<T>(pane, project_item, cx)
4298 .is_some()
4299 }
4300
4301 pub fn open_project_item<T>(
4302 &mut self,
4303 pane: Entity<Pane>,
4304 project_item: Entity<T::Item>,
4305 activate_pane: bool,
4306 focus_item: bool,
4307 keep_old_preview: bool,
4308 allow_new_preview: bool,
4309 window: &mut Window,
4310 cx: &mut Context<Self>,
4311 ) -> Entity<T>
4312 where
4313 T: ProjectItem,
4314 {
4315 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4316
4317 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4318 if !keep_old_preview
4319 && let Some(old_id) = old_item_id
4320 && old_id != item.item_id()
4321 {
4322 // switching to a different item, so unpreview old active item
4323 pane.update(cx, |pane, _| {
4324 pane.unpreview_item_if_preview(old_id);
4325 });
4326 }
4327
4328 self.activate_item(&item, activate_pane, focus_item, window, cx);
4329 if !allow_new_preview {
4330 pane.update(cx, |pane, _| {
4331 pane.unpreview_item_if_preview(item.item_id());
4332 });
4333 }
4334 return item;
4335 }
4336
4337 let item = pane.update(cx, |pane, cx| {
4338 cx.new(|cx| {
4339 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4340 })
4341 });
4342 let mut destination_index = None;
4343 pane.update(cx, |pane, cx| {
4344 if !keep_old_preview && let Some(old_id) = old_item_id {
4345 pane.unpreview_item_if_preview(old_id);
4346 }
4347 if allow_new_preview {
4348 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4349 }
4350 });
4351
4352 self.add_item(
4353 pane,
4354 Box::new(item.clone()),
4355 destination_index,
4356 activate_pane,
4357 focus_item,
4358 window,
4359 cx,
4360 );
4361 item
4362 }
4363
4364 pub fn open_shared_screen(
4365 &mut self,
4366 peer_id: PeerId,
4367 window: &mut Window,
4368 cx: &mut Context<Self>,
4369 ) {
4370 if let Some(shared_screen) =
4371 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4372 {
4373 self.active_pane.update(cx, |pane, cx| {
4374 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4375 });
4376 }
4377 }
4378
4379 pub fn activate_item(
4380 &mut self,
4381 item: &dyn ItemHandle,
4382 activate_pane: bool,
4383 focus_item: bool,
4384 window: &mut Window,
4385 cx: &mut App,
4386 ) -> bool {
4387 let result = self.panes.iter().find_map(|pane| {
4388 pane.read(cx)
4389 .index_for_item(item)
4390 .map(|ix| (pane.clone(), ix))
4391 });
4392 if let Some((pane, ix)) = result {
4393 pane.update(cx, |pane, cx| {
4394 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4395 });
4396 true
4397 } else {
4398 false
4399 }
4400 }
4401
4402 fn activate_pane_at_index(
4403 &mut self,
4404 action: &ActivatePane,
4405 window: &mut Window,
4406 cx: &mut Context<Self>,
4407 ) {
4408 let panes = self.center.panes();
4409 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4410 window.focus(&pane.focus_handle(cx), cx);
4411 } else {
4412 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4413 .detach();
4414 }
4415 }
4416
4417 fn move_item_to_pane_at_index(
4418 &mut self,
4419 action: &MoveItemToPane,
4420 window: &mut Window,
4421 cx: &mut Context<Self>,
4422 ) {
4423 let panes = self.center.panes();
4424 let destination = match panes.get(action.destination) {
4425 Some(&destination) => destination.clone(),
4426 None => {
4427 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4428 return;
4429 }
4430 let direction = SplitDirection::Right;
4431 let split_off_pane = self
4432 .find_pane_in_direction(direction, cx)
4433 .unwrap_or_else(|| self.active_pane.clone());
4434 let new_pane = self.add_pane(window, cx);
4435 self.center.split(&split_off_pane, &new_pane, direction, cx);
4436 new_pane
4437 }
4438 };
4439
4440 if action.clone {
4441 if self
4442 .active_pane
4443 .read(cx)
4444 .active_item()
4445 .is_some_and(|item| item.can_split(cx))
4446 {
4447 clone_active_item(
4448 self.database_id(),
4449 &self.active_pane,
4450 &destination,
4451 action.focus,
4452 window,
4453 cx,
4454 );
4455 return;
4456 }
4457 }
4458 move_active_item(
4459 &self.active_pane,
4460 &destination,
4461 action.focus,
4462 true,
4463 window,
4464 cx,
4465 )
4466 }
4467
4468 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4469 let panes = self.center.panes();
4470 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4471 let next_ix = (ix + 1) % panes.len();
4472 let next_pane = panes[next_ix].clone();
4473 window.focus(&next_pane.focus_handle(cx), cx);
4474 }
4475 }
4476
4477 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4478 let panes = self.center.panes();
4479 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4480 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4481 let prev_pane = panes[prev_ix].clone();
4482 window.focus(&prev_pane.focus_handle(cx), cx);
4483 }
4484 }
4485
4486 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4487 let last_pane = self.center.last_pane();
4488 window.focus(&last_pane.focus_handle(cx), cx);
4489 }
4490
4491 pub fn activate_pane_in_direction(
4492 &mut self,
4493 direction: SplitDirection,
4494 window: &mut Window,
4495 cx: &mut App,
4496 ) {
4497 use ActivateInDirectionTarget as Target;
4498 enum Origin {
4499 Sidebar,
4500 LeftDock,
4501 RightDock,
4502 BottomDock,
4503 Center,
4504 }
4505
4506 let origin: Origin = if self
4507 .sidebar_focus_handle
4508 .as_ref()
4509 .is_some_and(|h| h.contains_focused(window, cx))
4510 {
4511 Origin::Sidebar
4512 } else {
4513 [
4514 (&self.left_dock, Origin::LeftDock),
4515 (&self.right_dock, Origin::RightDock),
4516 (&self.bottom_dock, Origin::BottomDock),
4517 ]
4518 .into_iter()
4519 .find_map(|(dock, origin)| {
4520 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4521 Some(origin)
4522 } else {
4523 None
4524 }
4525 })
4526 .unwrap_or(Origin::Center)
4527 };
4528
4529 let get_last_active_pane = || {
4530 let pane = self
4531 .last_active_center_pane
4532 .clone()
4533 .unwrap_or_else(|| {
4534 self.panes
4535 .first()
4536 .expect("There must be an active pane")
4537 .downgrade()
4538 })
4539 .upgrade()?;
4540 (pane.read(cx).items_len() != 0).then_some(pane)
4541 };
4542
4543 let try_dock =
4544 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4545
4546 let sidebar_target = self
4547 .sidebar_focus_handle
4548 .as_ref()
4549 .map(|h| Target::Sidebar(h.clone()));
4550
4551 let target = match (origin, direction) {
4552 // From the sidebar, only Right navigates into the workspace.
4553 (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
4554 .or_else(|| get_last_active_pane().map(Target::Pane))
4555 .or_else(|| try_dock(&self.bottom_dock))
4556 .or_else(|| try_dock(&self.right_dock)),
4557
4558 (Origin::Sidebar, _) => None,
4559
4560 // We're in the center, so we first try to go to a different pane,
4561 // otherwise try to go to a dock.
4562 (Origin::Center, direction) => {
4563 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4564 Some(Target::Pane(pane))
4565 } else {
4566 match direction {
4567 SplitDirection::Up => None,
4568 SplitDirection::Down => try_dock(&self.bottom_dock),
4569 SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
4570 SplitDirection::Right => try_dock(&self.right_dock),
4571 }
4572 }
4573 }
4574
4575 (Origin::LeftDock, SplitDirection::Right) => {
4576 if let Some(last_active_pane) = get_last_active_pane() {
4577 Some(Target::Pane(last_active_pane))
4578 } else {
4579 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4580 }
4581 }
4582
4583 (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
4584
4585 (Origin::LeftDock, SplitDirection::Down)
4586 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4587
4588 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4589 (Origin::BottomDock, SplitDirection::Left) => {
4590 try_dock(&self.left_dock).or(sidebar_target)
4591 }
4592 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4593
4594 (Origin::RightDock, SplitDirection::Left) => {
4595 if let Some(last_active_pane) = get_last_active_pane() {
4596 Some(Target::Pane(last_active_pane))
4597 } else {
4598 try_dock(&self.bottom_dock)
4599 .or_else(|| try_dock(&self.left_dock))
4600 .or(sidebar_target)
4601 }
4602 }
4603
4604 _ => None,
4605 };
4606
4607 match target {
4608 Some(ActivateInDirectionTarget::Pane(pane)) => {
4609 let pane = pane.read(cx);
4610 if let Some(item) = pane.active_item() {
4611 item.item_focus_handle(cx).focus(window, cx);
4612 } else {
4613 log::error!(
4614 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4615 );
4616 }
4617 }
4618 Some(ActivateInDirectionTarget::Dock(dock)) => {
4619 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4620 window.defer(cx, move |window, cx| {
4621 let dock = dock.read(cx);
4622 if let Some(panel) = dock.active_panel() {
4623 panel.panel_focus_handle(cx).focus(window, cx);
4624 } else {
4625 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4626 }
4627 })
4628 }
4629 Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
4630 focus_handle.focus(window, cx);
4631 }
4632 None => {}
4633 }
4634 }
4635
4636 pub fn move_item_to_pane_in_direction(
4637 &mut self,
4638 action: &MoveItemToPaneInDirection,
4639 window: &mut Window,
4640 cx: &mut Context<Self>,
4641 ) {
4642 let destination = match self.find_pane_in_direction(action.direction, cx) {
4643 Some(destination) => destination,
4644 None => {
4645 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4646 return;
4647 }
4648 let new_pane = self.add_pane(window, cx);
4649 self.center
4650 .split(&self.active_pane, &new_pane, action.direction, cx);
4651 new_pane
4652 }
4653 };
4654
4655 if action.clone {
4656 if self
4657 .active_pane
4658 .read(cx)
4659 .active_item()
4660 .is_some_and(|item| item.can_split(cx))
4661 {
4662 clone_active_item(
4663 self.database_id(),
4664 &self.active_pane,
4665 &destination,
4666 action.focus,
4667 window,
4668 cx,
4669 );
4670 return;
4671 }
4672 }
4673 move_active_item(
4674 &self.active_pane,
4675 &destination,
4676 action.focus,
4677 true,
4678 window,
4679 cx,
4680 );
4681 }
4682
4683 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4684 self.center.bounding_box_for_pane(pane)
4685 }
4686
4687 pub fn find_pane_in_direction(
4688 &mut self,
4689 direction: SplitDirection,
4690 cx: &App,
4691 ) -> Option<Entity<Pane>> {
4692 self.center
4693 .find_pane_in_direction(&self.active_pane, direction, cx)
4694 .cloned()
4695 }
4696
4697 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4698 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4699 self.center.swap(&self.active_pane, &to, cx);
4700 cx.notify();
4701 }
4702 }
4703
4704 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4705 if self
4706 .center
4707 .move_to_border(&self.active_pane, direction, cx)
4708 .unwrap()
4709 {
4710 cx.notify();
4711 }
4712 }
4713
4714 pub fn resize_pane(
4715 &mut self,
4716 axis: gpui::Axis,
4717 amount: Pixels,
4718 window: &mut Window,
4719 cx: &mut Context<Self>,
4720 ) {
4721 let docks = self.all_docks();
4722 let active_dock = docks
4723 .into_iter()
4724 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4725
4726 if let Some(dock) = active_dock {
4727 let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
4728 return;
4729 };
4730 match dock.read(cx).position() {
4731 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4732 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4733 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4734 }
4735 } else {
4736 self.center
4737 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
4738 }
4739 cx.notify();
4740 }
4741
4742 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
4743 self.center.reset_pane_sizes(cx);
4744 cx.notify();
4745 }
4746
4747 fn handle_pane_focused(
4748 &mut self,
4749 pane: Entity<Pane>,
4750 window: &mut Window,
4751 cx: &mut Context<Self>,
4752 ) {
4753 // This is explicitly hoisted out of the following check for pane identity as
4754 // terminal panel panes are not registered as a center panes.
4755 self.status_bar.update(cx, |status_bar, cx| {
4756 status_bar.set_active_pane(&pane, window, cx);
4757 });
4758 if self.active_pane != pane {
4759 self.set_active_pane(&pane, window, cx);
4760 }
4761
4762 if self.last_active_center_pane.is_none() {
4763 self.last_active_center_pane = Some(pane.downgrade());
4764 }
4765
4766 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
4767 // This prevents the dock from closing when focus events fire during window activation.
4768 // We also preserve any dock whose active panel itself has focus — this covers
4769 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
4770 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
4771 let dock_read = dock.read(cx);
4772 if let Some(panel) = dock_read.active_panel() {
4773 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
4774 || panel.panel_focus_handle(cx).contains_focused(window, cx)
4775 {
4776 return Some(dock_read.position());
4777 }
4778 }
4779 None
4780 });
4781
4782 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
4783 if pane.read(cx).is_zoomed() {
4784 self.zoomed = Some(pane.downgrade().into());
4785 } else {
4786 self.zoomed = None;
4787 }
4788 self.zoomed_position = None;
4789 cx.emit(Event::ZoomChanged);
4790 self.update_active_view_for_followers(window, cx);
4791 pane.update(cx, |pane, _| {
4792 pane.track_alternate_file_items();
4793 });
4794
4795 cx.notify();
4796 }
4797
4798 fn set_active_pane(
4799 &mut self,
4800 pane: &Entity<Pane>,
4801 window: &mut Window,
4802 cx: &mut Context<Self>,
4803 ) {
4804 self.active_pane = pane.clone();
4805 self.active_item_path_changed(true, window, cx);
4806 self.last_active_center_pane = Some(pane.downgrade());
4807 }
4808
4809 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4810 self.update_active_view_for_followers(window, cx);
4811 }
4812
4813 fn handle_pane_event(
4814 &mut self,
4815 pane: &Entity<Pane>,
4816 event: &pane::Event,
4817 window: &mut Window,
4818 cx: &mut Context<Self>,
4819 ) {
4820 let mut serialize_workspace = true;
4821 match event {
4822 pane::Event::AddItem { item } => {
4823 item.added_to_pane(self, pane.clone(), window, cx);
4824 cx.emit(Event::ItemAdded {
4825 item: item.boxed_clone(),
4826 });
4827 }
4828 pane::Event::Split { direction, mode } => {
4829 match mode {
4830 SplitMode::ClonePane => {
4831 self.split_and_clone(pane.clone(), *direction, window, cx)
4832 .detach();
4833 }
4834 SplitMode::EmptyPane => {
4835 self.split_pane(pane.clone(), *direction, window, cx);
4836 }
4837 SplitMode::MovePane => {
4838 self.split_and_move(pane.clone(), *direction, window, cx);
4839 }
4840 };
4841 }
4842 pane::Event::JoinIntoNext => {
4843 self.join_pane_into_next(pane.clone(), window, cx);
4844 }
4845 pane::Event::JoinAll => {
4846 self.join_all_panes(window, cx);
4847 }
4848 pane::Event::Remove { focus_on_pane } => {
4849 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
4850 }
4851 pane::Event::ActivateItem {
4852 local,
4853 focus_changed,
4854 } => {
4855 window.invalidate_character_coordinates();
4856
4857 pane.update(cx, |pane, _| {
4858 pane.track_alternate_file_items();
4859 });
4860 if *local {
4861 self.unfollow_in_pane(pane, window, cx);
4862 }
4863 serialize_workspace = *focus_changed || pane != self.active_pane();
4864 if pane == self.active_pane() {
4865 self.active_item_path_changed(*focus_changed, window, cx);
4866 self.update_active_view_for_followers(window, cx);
4867 } else if *local {
4868 self.set_active_pane(pane, window, cx);
4869 }
4870 }
4871 pane::Event::UserSavedItem { item, save_intent } => {
4872 cx.emit(Event::UserSavedItem {
4873 pane: pane.downgrade(),
4874 item: item.boxed_clone(),
4875 save_intent: *save_intent,
4876 });
4877 serialize_workspace = false;
4878 }
4879 pane::Event::ChangeItemTitle => {
4880 if *pane == self.active_pane {
4881 self.active_item_path_changed(false, window, cx);
4882 }
4883 serialize_workspace = false;
4884 }
4885 pane::Event::RemovedItem { item } => {
4886 cx.emit(Event::ActiveItemChanged);
4887 self.update_window_edited(window, cx);
4888 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
4889 && entry.get().entity_id() == pane.entity_id()
4890 {
4891 entry.remove();
4892 }
4893 cx.emit(Event::ItemRemoved {
4894 item_id: item.item_id(),
4895 });
4896 }
4897 pane::Event::Focus => {
4898 window.invalidate_character_coordinates();
4899 self.handle_pane_focused(pane.clone(), window, cx);
4900 }
4901 pane::Event::ZoomIn => {
4902 if *pane == self.active_pane {
4903 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
4904 if pane.read(cx).has_focus(window, cx) {
4905 self.zoomed = Some(pane.downgrade().into());
4906 self.zoomed_position = None;
4907 cx.emit(Event::ZoomChanged);
4908 }
4909 cx.notify();
4910 }
4911 }
4912 pane::Event::ZoomOut => {
4913 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4914 if self.zoomed_position.is_none() {
4915 self.zoomed = None;
4916 cx.emit(Event::ZoomChanged);
4917 }
4918 cx.notify();
4919 }
4920 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
4921 }
4922
4923 if serialize_workspace {
4924 self.serialize_workspace(window, cx);
4925 }
4926 }
4927
4928 pub fn unfollow_in_pane(
4929 &mut self,
4930 pane: &Entity<Pane>,
4931 window: &mut Window,
4932 cx: &mut Context<Workspace>,
4933 ) -> Option<CollaboratorId> {
4934 let leader_id = self.leader_for_pane(pane)?;
4935 self.unfollow(leader_id, window, cx);
4936 Some(leader_id)
4937 }
4938
4939 pub fn split_pane(
4940 &mut self,
4941 pane_to_split: Entity<Pane>,
4942 split_direction: SplitDirection,
4943 window: &mut Window,
4944 cx: &mut Context<Self>,
4945 ) -> Entity<Pane> {
4946 let new_pane = self.add_pane(window, cx);
4947 self.center
4948 .split(&pane_to_split, &new_pane, split_direction, cx);
4949 cx.notify();
4950 new_pane
4951 }
4952
4953 pub fn split_and_move(
4954 &mut self,
4955 pane: Entity<Pane>,
4956 direction: SplitDirection,
4957 window: &mut Window,
4958 cx: &mut Context<Self>,
4959 ) {
4960 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
4961 return;
4962 };
4963 let new_pane = self.add_pane(window, cx);
4964 new_pane.update(cx, |pane, cx| {
4965 pane.add_item(item, true, true, None, window, cx)
4966 });
4967 self.center.split(&pane, &new_pane, direction, cx);
4968 cx.notify();
4969 }
4970
4971 pub fn split_and_clone(
4972 &mut self,
4973 pane: Entity<Pane>,
4974 direction: SplitDirection,
4975 window: &mut Window,
4976 cx: &mut Context<Self>,
4977 ) -> Task<Option<Entity<Pane>>> {
4978 let Some(item) = pane.read(cx).active_item() else {
4979 return Task::ready(None);
4980 };
4981 if !item.can_split(cx) {
4982 return Task::ready(None);
4983 }
4984 let task = item.clone_on_split(self.database_id(), window, cx);
4985 cx.spawn_in(window, async move |this, cx| {
4986 if let Some(clone) = task.await {
4987 this.update_in(cx, |this, window, cx| {
4988 let new_pane = this.add_pane(window, cx);
4989 let nav_history = pane.read(cx).fork_nav_history();
4990 new_pane.update(cx, |pane, cx| {
4991 pane.set_nav_history(nav_history, cx);
4992 pane.add_item(clone, true, true, None, window, cx)
4993 });
4994 this.center.split(&pane, &new_pane, direction, cx);
4995 cx.notify();
4996 new_pane
4997 })
4998 .ok()
4999 } else {
5000 None
5001 }
5002 })
5003 }
5004
5005 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5006 let active_item = self.active_pane.read(cx).active_item();
5007 for pane in &self.panes {
5008 join_pane_into_active(&self.active_pane, pane, window, cx);
5009 }
5010 if let Some(active_item) = active_item {
5011 self.activate_item(active_item.as_ref(), true, true, window, cx);
5012 }
5013 cx.notify();
5014 }
5015
5016 pub fn join_pane_into_next(
5017 &mut self,
5018 pane: Entity<Pane>,
5019 window: &mut Window,
5020 cx: &mut Context<Self>,
5021 ) {
5022 let next_pane = self
5023 .find_pane_in_direction(SplitDirection::Right, cx)
5024 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
5025 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
5026 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
5027 let Some(next_pane) = next_pane else {
5028 return;
5029 };
5030 move_all_items(&pane, &next_pane, window, cx);
5031 cx.notify();
5032 }
5033
5034 fn remove_pane(
5035 &mut self,
5036 pane: Entity<Pane>,
5037 focus_on: Option<Entity<Pane>>,
5038 window: &mut Window,
5039 cx: &mut Context<Self>,
5040 ) {
5041 if self.center.remove(&pane, cx).unwrap() {
5042 self.force_remove_pane(&pane, &focus_on, window, cx);
5043 self.unfollow_in_pane(&pane, window, cx);
5044 self.last_leaders_by_pane.remove(&pane.downgrade());
5045 for removed_item in pane.read(cx).items() {
5046 self.panes_by_item.remove(&removed_item.item_id());
5047 }
5048
5049 cx.notify();
5050 } else {
5051 self.active_item_path_changed(true, window, cx);
5052 }
5053 cx.emit(Event::PaneRemoved);
5054 }
5055
5056 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5057 &mut self.panes
5058 }
5059
5060 pub fn panes(&self) -> &[Entity<Pane>] {
5061 &self.panes
5062 }
5063
5064 pub fn active_pane(&self) -> &Entity<Pane> {
5065 &self.active_pane
5066 }
5067
5068 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5069 for dock in self.all_docks() {
5070 if dock.focus_handle(cx).contains_focused(window, cx)
5071 && let Some(pane) = dock
5072 .read(cx)
5073 .active_panel()
5074 .and_then(|panel| panel.pane(cx))
5075 {
5076 return pane;
5077 }
5078 }
5079 self.active_pane().clone()
5080 }
5081
5082 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5083 self.find_pane_in_direction(SplitDirection::Right, cx)
5084 .unwrap_or_else(|| {
5085 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5086 })
5087 }
5088
5089 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5090 self.pane_for_item_id(handle.item_id())
5091 }
5092
5093 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5094 let weak_pane = self.panes_by_item.get(&item_id)?;
5095 weak_pane.upgrade()
5096 }
5097
5098 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5099 self.panes
5100 .iter()
5101 .find(|pane| pane.entity_id() == entity_id)
5102 .cloned()
5103 }
5104
5105 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5106 self.follower_states.retain(|leader_id, state| {
5107 if *leader_id == CollaboratorId::PeerId(peer_id) {
5108 for item in state.items_by_leader_view_id.values() {
5109 item.view.set_leader_id(None, window, cx);
5110 }
5111 false
5112 } else {
5113 true
5114 }
5115 });
5116 cx.notify();
5117 }
5118
5119 pub fn start_following(
5120 &mut self,
5121 leader_id: impl Into<CollaboratorId>,
5122 window: &mut Window,
5123 cx: &mut Context<Self>,
5124 ) -> Option<Task<Result<()>>> {
5125 let leader_id = leader_id.into();
5126 let pane = self.active_pane().clone();
5127
5128 self.last_leaders_by_pane
5129 .insert(pane.downgrade(), leader_id);
5130 self.unfollow(leader_id, window, cx);
5131 self.unfollow_in_pane(&pane, window, cx);
5132 self.follower_states.insert(
5133 leader_id,
5134 FollowerState {
5135 center_pane: pane.clone(),
5136 dock_pane: None,
5137 active_view_id: None,
5138 items_by_leader_view_id: Default::default(),
5139 },
5140 );
5141 cx.notify();
5142
5143 match leader_id {
5144 CollaboratorId::PeerId(leader_peer_id) => {
5145 let room_id = self.active_call()?.room_id(cx)?;
5146 let project_id = self.project.read(cx).remote_id();
5147 let request = self.app_state.client.request(proto::Follow {
5148 room_id,
5149 project_id,
5150 leader_id: Some(leader_peer_id),
5151 });
5152
5153 Some(cx.spawn_in(window, async move |this, cx| {
5154 let response = request.await?;
5155 this.update(cx, |this, _| {
5156 let state = this
5157 .follower_states
5158 .get_mut(&leader_id)
5159 .context("following interrupted")?;
5160 state.active_view_id = response
5161 .active_view
5162 .as_ref()
5163 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5164 anyhow::Ok(())
5165 })??;
5166 if let Some(view) = response.active_view {
5167 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5168 }
5169 this.update_in(cx, |this, window, cx| {
5170 this.leader_updated(leader_id, window, cx)
5171 })?;
5172 Ok(())
5173 }))
5174 }
5175 CollaboratorId::Agent => {
5176 self.leader_updated(leader_id, window, cx)?;
5177 Some(Task::ready(Ok(())))
5178 }
5179 }
5180 }
5181
5182 pub fn follow_next_collaborator(
5183 &mut self,
5184 _: &FollowNextCollaborator,
5185 window: &mut Window,
5186 cx: &mut Context<Self>,
5187 ) {
5188 let collaborators = self.project.read(cx).collaborators();
5189 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5190 let mut collaborators = collaborators.keys().copied();
5191 for peer_id in collaborators.by_ref() {
5192 if CollaboratorId::PeerId(peer_id) == leader_id {
5193 break;
5194 }
5195 }
5196 collaborators.next().map(CollaboratorId::PeerId)
5197 } else if let Some(last_leader_id) =
5198 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5199 {
5200 match last_leader_id {
5201 CollaboratorId::PeerId(peer_id) => {
5202 if collaborators.contains_key(peer_id) {
5203 Some(*last_leader_id)
5204 } else {
5205 None
5206 }
5207 }
5208 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5209 }
5210 } else {
5211 None
5212 };
5213
5214 let pane = self.active_pane.clone();
5215 let Some(leader_id) = next_leader_id.or_else(|| {
5216 Some(CollaboratorId::PeerId(
5217 collaborators.keys().copied().next()?,
5218 ))
5219 }) else {
5220 return;
5221 };
5222 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5223 return;
5224 }
5225 if let Some(task) = self.start_following(leader_id, window, cx) {
5226 task.detach_and_log_err(cx)
5227 }
5228 }
5229
5230 pub fn follow(
5231 &mut self,
5232 leader_id: impl Into<CollaboratorId>,
5233 window: &mut Window,
5234 cx: &mut Context<Self>,
5235 ) {
5236 let leader_id = leader_id.into();
5237
5238 if let CollaboratorId::PeerId(peer_id) = leader_id {
5239 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5240 return;
5241 };
5242 let Some(remote_participant) =
5243 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5244 else {
5245 return;
5246 };
5247
5248 let project = self.project.read(cx);
5249
5250 let other_project_id = match remote_participant.location {
5251 ParticipantLocation::External => None,
5252 ParticipantLocation::UnsharedProject => None,
5253 ParticipantLocation::SharedProject { project_id } => {
5254 if Some(project_id) == project.remote_id() {
5255 None
5256 } else {
5257 Some(project_id)
5258 }
5259 }
5260 };
5261
5262 // if they are active in another project, follow there.
5263 if let Some(project_id) = other_project_id {
5264 let app_state = self.app_state.clone();
5265 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5266 .detach_and_log_err(cx);
5267 }
5268 }
5269
5270 // if you're already following, find the right pane and focus it.
5271 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5272 window.focus(&follower_state.pane().focus_handle(cx), cx);
5273
5274 return;
5275 }
5276
5277 // Otherwise, follow.
5278 if let Some(task) = self.start_following(leader_id, window, cx) {
5279 task.detach_and_log_err(cx)
5280 }
5281 }
5282
5283 pub fn unfollow(
5284 &mut self,
5285 leader_id: impl Into<CollaboratorId>,
5286 window: &mut Window,
5287 cx: &mut Context<Self>,
5288 ) -> Option<()> {
5289 cx.notify();
5290
5291 let leader_id = leader_id.into();
5292 let state = self.follower_states.remove(&leader_id)?;
5293 for (_, item) in state.items_by_leader_view_id {
5294 item.view.set_leader_id(None, window, cx);
5295 }
5296
5297 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5298 let project_id = self.project.read(cx).remote_id();
5299 let room_id = self.active_call()?.room_id(cx)?;
5300 self.app_state
5301 .client
5302 .send(proto::Unfollow {
5303 room_id,
5304 project_id,
5305 leader_id: Some(leader_peer_id),
5306 })
5307 .log_err();
5308 }
5309
5310 Some(())
5311 }
5312
5313 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5314 self.follower_states.contains_key(&id.into())
5315 }
5316
5317 fn active_item_path_changed(
5318 &mut self,
5319 focus_changed: bool,
5320 window: &mut Window,
5321 cx: &mut Context<Self>,
5322 ) {
5323 cx.emit(Event::ActiveItemChanged);
5324 let active_entry = self.active_project_path(cx);
5325 self.project.update(cx, |project, cx| {
5326 project.set_active_path(active_entry.clone(), cx)
5327 });
5328
5329 if focus_changed && let Some(project_path) = &active_entry {
5330 let git_store_entity = self.project.read(cx).git_store().clone();
5331 git_store_entity.update(cx, |git_store, cx| {
5332 git_store.set_active_repo_for_path(project_path, cx);
5333 });
5334 }
5335
5336 self.update_window_title(window, cx);
5337 }
5338
5339 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5340 let project = self.project().read(cx);
5341 let mut title = String::new();
5342
5343 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5344 let name = {
5345 let settings_location = SettingsLocation {
5346 worktree_id: worktree.read(cx).id(),
5347 path: RelPath::empty(),
5348 };
5349
5350 let settings = WorktreeSettings::get(Some(settings_location), cx);
5351 match &settings.project_name {
5352 Some(name) => name.as_str(),
5353 None => worktree.read(cx).root_name_str(),
5354 }
5355 };
5356 if i > 0 {
5357 title.push_str(", ");
5358 }
5359 title.push_str(name);
5360 }
5361
5362 if title.is_empty() {
5363 title = "empty project".to_string();
5364 }
5365
5366 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5367 let filename = path.path.file_name().or_else(|| {
5368 Some(
5369 project
5370 .worktree_for_id(path.worktree_id, cx)?
5371 .read(cx)
5372 .root_name_str(),
5373 )
5374 });
5375
5376 if let Some(filename) = filename {
5377 title.push_str(" — ");
5378 title.push_str(filename.as_ref());
5379 }
5380 }
5381
5382 if project.is_via_collab() {
5383 title.push_str(" ↙");
5384 } else if project.is_shared() {
5385 title.push_str(" ↗");
5386 }
5387
5388 if let Some(last_title) = self.last_window_title.as_ref()
5389 && &title == last_title
5390 {
5391 return;
5392 }
5393 window.set_window_title(&title);
5394 SystemWindowTabController::update_tab_title(
5395 cx,
5396 window.window_handle().window_id(),
5397 SharedString::from(&title),
5398 );
5399 self.last_window_title = Some(title);
5400 }
5401
5402 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5403 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5404 if is_edited != self.window_edited {
5405 self.window_edited = is_edited;
5406 window.set_window_edited(self.window_edited)
5407 }
5408 }
5409
5410 fn update_item_dirty_state(
5411 &mut self,
5412 item: &dyn ItemHandle,
5413 window: &mut Window,
5414 cx: &mut App,
5415 ) {
5416 let is_dirty = item.is_dirty(cx);
5417 let item_id = item.item_id();
5418 let was_dirty = self.dirty_items.contains_key(&item_id);
5419 if is_dirty == was_dirty {
5420 return;
5421 }
5422 if was_dirty {
5423 self.dirty_items.remove(&item_id);
5424 self.update_window_edited(window, cx);
5425 return;
5426 }
5427
5428 let workspace = self.weak_handle();
5429 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5430 return;
5431 };
5432 let on_release_callback = Box::new(move |cx: &mut App| {
5433 window_handle
5434 .update(cx, |_, window, cx| {
5435 workspace
5436 .update(cx, |workspace, cx| {
5437 workspace.dirty_items.remove(&item_id);
5438 workspace.update_window_edited(window, cx)
5439 })
5440 .ok();
5441 })
5442 .ok();
5443 });
5444
5445 let s = item.on_release(cx, on_release_callback);
5446 self.dirty_items.insert(item_id, s);
5447 self.update_window_edited(window, cx);
5448 }
5449
5450 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5451 if self.notifications.is_empty() {
5452 None
5453 } else {
5454 Some(
5455 div()
5456 .absolute()
5457 .right_3()
5458 .bottom_3()
5459 .w_112()
5460 .h_full()
5461 .flex()
5462 .flex_col()
5463 .justify_end()
5464 .gap_2()
5465 .children(
5466 self.notifications
5467 .iter()
5468 .map(|(_, notification)| notification.clone().into_any()),
5469 ),
5470 )
5471 }
5472 }
5473
5474 // RPC handlers
5475
5476 fn active_view_for_follower(
5477 &self,
5478 follower_project_id: Option<u64>,
5479 window: &mut Window,
5480 cx: &mut Context<Self>,
5481 ) -> Option<proto::View> {
5482 let (item, panel_id) = self.active_item_for_followers(window, cx);
5483 let item = item?;
5484 let leader_id = self
5485 .pane_for(&*item)
5486 .and_then(|pane| self.leader_for_pane(&pane));
5487 let leader_peer_id = match leader_id {
5488 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5489 Some(CollaboratorId::Agent) | None => None,
5490 };
5491
5492 let item_handle = item.to_followable_item_handle(cx)?;
5493 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5494 let variant = item_handle.to_state_proto(window, cx)?;
5495
5496 if item_handle.is_project_item(window, cx)
5497 && (follower_project_id.is_none()
5498 || follower_project_id != self.project.read(cx).remote_id())
5499 {
5500 return None;
5501 }
5502
5503 Some(proto::View {
5504 id: id.to_proto(),
5505 leader_id: leader_peer_id,
5506 variant: Some(variant),
5507 panel_id: panel_id.map(|id| id as i32),
5508 })
5509 }
5510
5511 fn handle_follow(
5512 &mut self,
5513 follower_project_id: Option<u64>,
5514 window: &mut Window,
5515 cx: &mut Context<Self>,
5516 ) -> proto::FollowResponse {
5517 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5518
5519 cx.notify();
5520 proto::FollowResponse {
5521 views: active_view.iter().cloned().collect(),
5522 active_view,
5523 }
5524 }
5525
5526 fn handle_update_followers(
5527 &mut self,
5528 leader_id: PeerId,
5529 message: proto::UpdateFollowers,
5530 _window: &mut Window,
5531 _cx: &mut Context<Self>,
5532 ) {
5533 self.leader_updates_tx
5534 .unbounded_send((leader_id, message))
5535 .ok();
5536 }
5537
5538 async fn process_leader_update(
5539 this: &WeakEntity<Self>,
5540 leader_id: PeerId,
5541 update: proto::UpdateFollowers,
5542 cx: &mut AsyncWindowContext,
5543 ) -> Result<()> {
5544 match update.variant.context("invalid update")? {
5545 proto::update_followers::Variant::CreateView(view) => {
5546 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5547 let should_add_view = this.update(cx, |this, _| {
5548 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5549 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5550 } else {
5551 anyhow::Ok(false)
5552 }
5553 })??;
5554
5555 if should_add_view {
5556 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5557 }
5558 }
5559 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5560 let should_add_view = this.update(cx, |this, _| {
5561 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5562 state.active_view_id = update_active_view
5563 .view
5564 .as_ref()
5565 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5566
5567 if state.active_view_id.is_some_and(|view_id| {
5568 !state.items_by_leader_view_id.contains_key(&view_id)
5569 }) {
5570 anyhow::Ok(true)
5571 } else {
5572 anyhow::Ok(false)
5573 }
5574 } else {
5575 anyhow::Ok(false)
5576 }
5577 })??;
5578
5579 if should_add_view && let Some(view) = update_active_view.view {
5580 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5581 }
5582 }
5583 proto::update_followers::Variant::UpdateView(update_view) => {
5584 let variant = update_view.variant.context("missing update view variant")?;
5585 let id = update_view.id.context("missing update view id")?;
5586 let mut tasks = Vec::new();
5587 this.update_in(cx, |this, window, cx| {
5588 let project = this.project.clone();
5589 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5590 let view_id = ViewId::from_proto(id.clone())?;
5591 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5592 tasks.push(item.view.apply_update_proto(
5593 &project,
5594 variant.clone(),
5595 window,
5596 cx,
5597 ));
5598 }
5599 }
5600 anyhow::Ok(())
5601 })??;
5602 try_join_all(tasks).await.log_err();
5603 }
5604 }
5605 this.update_in(cx, |this, window, cx| {
5606 this.leader_updated(leader_id, window, cx)
5607 })?;
5608 Ok(())
5609 }
5610
5611 async fn add_view_from_leader(
5612 this: WeakEntity<Self>,
5613 leader_id: PeerId,
5614 view: &proto::View,
5615 cx: &mut AsyncWindowContext,
5616 ) -> Result<()> {
5617 let this = this.upgrade().context("workspace dropped")?;
5618
5619 let Some(id) = view.id.clone() else {
5620 anyhow::bail!("no id for view");
5621 };
5622 let id = ViewId::from_proto(id)?;
5623 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5624
5625 let pane = this.update(cx, |this, _cx| {
5626 let state = this
5627 .follower_states
5628 .get(&leader_id.into())
5629 .context("stopped following")?;
5630 anyhow::Ok(state.pane().clone())
5631 })?;
5632 let existing_item = pane.update_in(cx, |pane, window, cx| {
5633 let client = this.read(cx).client().clone();
5634 pane.items().find_map(|item| {
5635 let item = item.to_followable_item_handle(cx)?;
5636 if item.remote_id(&client, window, cx) == Some(id) {
5637 Some(item)
5638 } else {
5639 None
5640 }
5641 })
5642 })?;
5643 let item = if let Some(existing_item) = existing_item {
5644 existing_item
5645 } else {
5646 let variant = view.variant.clone();
5647 anyhow::ensure!(variant.is_some(), "missing view variant");
5648
5649 let task = cx.update(|window, cx| {
5650 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5651 })?;
5652
5653 let Some(task) = task else {
5654 anyhow::bail!(
5655 "failed to construct view from leader (maybe from a different version of zed?)"
5656 );
5657 };
5658
5659 let mut new_item = task.await?;
5660 pane.update_in(cx, |pane, window, cx| {
5661 let mut item_to_remove = None;
5662 for (ix, item) in pane.items().enumerate() {
5663 if let Some(item) = item.to_followable_item_handle(cx) {
5664 match new_item.dedup(item.as_ref(), window, cx) {
5665 Some(item::Dedup::KeepExisting) => {
5666 new_item =
5667 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5668 break;
5669 }
5670 Some(item::Dedup::ReplaceExisting) => {
5671 item_to_remove = Some((ix, item.item_id()));
5672 break;
5673 }
5674 None => {}
5675 }
5676 }
5677 }
5678
5679 if let Some((ix, id)) = item_to_remove {
5680 pane.remove_item(id, false, false, window, cx);
5681 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5682 }
5683 })?;
5684
5685 new_item
5686 };
5687
5688 this.update_in(cx, |this, window, cx| {
5689 let state = this.follower_states.get_mut(&leader_id.into())?;
5690 item.set_leader_id(Some(leader_id.into()), window, cx);
5691 state.items_by_leader_view_id.insert(
5692 id,
5693 FollowerView {
5694 view: item,
5695 location: panel_id,
5696 },
5697 );
5698
5699 Some(())
5700 })
5701 .context("no follower state")?;
5702
5703 Ok(())
5704 }
5705
5706 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5707 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5708 return;
5709 };
5710
5711 if let Some(agent_location) = self.project.read(cx).agent_location() {
5712 let buffer_entity_id = agent_location.buffer.entity_id();
5713 let view_id = ViewId {
5714 creator: CollaboratorId::Agent,
5715 id: buffer_entity_id.as_u64(),
5716 };
5717 follower_state.active_view_id = Some(view_id);
5718
5719 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5720 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5721 hash_map::Entry::Vacant(entry) => {
5722 let existing_view =
5723 follower_state
5724 .center_pane
5725 .read(cx)
5726 .items()
5727 .find_map(|item| {
5728 let item = item.to_followable_item_handle(cx)?;
5729 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5730 && item.project_item_model_ids(cx).as_slice()
5731 == [buffer_entity_id]
5732 {
5733 Some(item)
5734 } else {
5735 None
5736 }
5737 });
5738 let view = existing_view.or_else(|| {
5739 agent_location.buffer.upgrade().and_then(|buffer| {
5740 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
5741 registry.build_item(buffer, self.project.clone(), None, window, cx)
5742 })?
5743 .to_followable_item_handle(cx)
5744 })
5745 });
5746
5747 view.map(|view| {
5748 entry.insert(FollowerView {
5749 view,
5750 location: None,
5751 })
5752 })
5753 }
5754 };
5755
5756 if let Some(item) = item {
5757 item.view
5758 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
5759 item.view
5760 .update_agent_location(agent_location.position, window, cx);
5761 }
5762 } else {
5763 follower_state.active_view_id = None;
5764 }
5765
5766 self.leader_updated(CollaboratorId::Agent, window, cx);
5767 }
5768
5769 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
5770 let mut is_project_item = true;
5771 let mut update = proto::UpdateActiveView::default();
5772 if window.is_window_active() {
5773 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
5774
5775 if let Some(item) = active_item
5776 && item.item_focus_handle(cx).contains_focused(window, cx)
5777 {
5778 let leader_id = self
5779 .pane_for(&*item)
5780 .and_then(|pane| self.leader_for_pane(&pane));
5781 let leader_peer_id = match leader_id {
5782 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5783 Some(CollaboratorId::Agent) | None => None,
5784 };
5785
5786 if let Some(item) = item.to_followable_item_handle(cx) {
5787 let id = item
5788 .remote_id(&self.app_state.client, window, cx)
5789 .map(|id| id.to_proto());
5790
5791 if let Some(id) = id
5792 && let Some(variant) = item.to_state_proto(window, cx)
5793 {
5794 let view = Some(proto::View {
5795 id,
5796 leader_id: leader_peer_id,
5797 variant: Some(variant),
5798 panel_id: panel_id.map(|id| id as i32),
5799 });
5800
5801 is_project_item = item.is_project_item(window, cx);
5802 update = proto::UpdateActiveView { view };
5803 };
5804 }
5805 }
5806 }
5807
5808 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
5809 if active_view_id != self.last_active_view_id.as_ref() {
5810 self.last_active_view_id = active_view_id.cloned();
5811 self.update_followers(
5812 is_project_item,
5813 proto::update_followers::Variant::UpdateActiveView(update),
5814 window,
5815 cx,
5816 );
5817 }
5818 }
5819
5820 fn active_item_for_followers(
5821 &self,
5822 window: &mut Window,
5823 cx: &mut App,
5824 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
5825 let mut active_item = None;
5826 let mut panel_id = None;
5827 for dock in self.all_docks() {
5828 if dock.focus_handle(cx).contains_focused(window, cx)
5829 && let Some(panel) = dock.read(cx).active_panel()
5830 && let Some(pane) = panel.pane(cx)
5831 && let Some(item) = pane.read(cx).active_item()
5832 {
5833 active_item = Some(item);
5834 panel_id = panel.remote_id();
5835 break;
5836 }
5837 }
5838
5839 if active_item.is_none() {
5840 active_item = self.active_pane().read(cx).active_item();
5841 }
5842 (active_item, panel_id)
5843 }
5844
5845 fn update_followers(
5846 &self,
5847 project_only: bool,
5848 update: proto::update_followers::Variant,
5849 _: &mut Window,
5850 cx: &mut App,
5851 ) -> Option<()> {
5852 // If this update only applies to for followers in the current project,
5853 // then skip it unless this project is shared. If it applies to all
5854 // followers, regardless of project, then set `project_id` to none,
5855 // indicating that it goes to all followers.
5856 let project_id = if project_only {
5857 Some(self.project.read(cx).remote_id()?)
5858 } else {
5859 None
5860 };
5861 self.app_state().workspace_store.update(cx, |store, cx| {
5862 store.update_followers(project_id, update, cx)
5863 })
5864 }
5865
5866 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
5867 self.follower_states.iter().find_map(|(leader_id, state)| {
5868 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
5869 Some(*leader_id)
5870 } else {
5871 None
5872 }
5873 })
5874 }
5875
5876 fn leader_updated(
5877 &mut self,
5878 leader_id: impl Into<CollaboratorId>,
5879 window: &mut Window,
5880 cx: &mut Context<Self>,
5881 ) -> Option<Box<dyn ItemHandle>> {
5882 cx.notify();
5883
5884 let leader_id = leader_id.into();
5885 let (panel_id, item) = match leader_id {
5886 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
5887 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
5888 };
5889
5890 let state = self.follower_states.get(&leader_id)?;
5891 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
5892 let pane;
5893 if let Some(panel_id) = panel_id {
5894 pane = self
5895 .activate_panel_for_proto_id(panel_id, window, cx)?
5896 .pane(cx)?;
5897 let state = self.follower_states.get_mut(&leader_id)?;
5898 state.dock_pane = Some(pane.clone());
5899 } else {
5900 pane = state.center_pane.clone();
5901 let state = self.follower_states.get_mut(&leader_id)?;
5902 if let Some(dock_pane) = state.dock_pane.take() {
5903 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
5904 }
5905 }
5906
5907 pane.update(cx, |pane, cx| {
5908 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
5909 if let Some(index) = pane.index_for_item(item.as_ref()) {
5910 pane.activate_item(index, false, false, window, cx);
5911 } else {
5912 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
5913 }
5914
5915 if focus_active_item {
5916 pane.focus_active_item(window, cx)
5917 }
5918 });
5919
5920 Some(item)
5921 }
5922
5923 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
5924 let state = self.follower_states.get(&CollaboratorId::Agent)?;
5925 let active_view_id = state.active_view_id?;
5926 Some(
5927 state
5928 .items_by_leader_view_id
5929 .get(&active_view_id)?
5930 .view
5931 .boxed_clone(),
5932 )
5933 }
5934
5935 fn active_item_for_peer(
5936 &self,
5937 peer_id: PeerId,
5938 window: &mut Window,
5939 cx: &mut Context<Self>,
5940 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
5941 let call = self.active_call()?;
5942 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
5943 let leader_in_this_app;
5944 let leader_in_this_project;
5945 match participant.location {
5946 ParticipantLocation::SharedProject { project_id } => {
5947 leader_in_this_app = true;
5948 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
5949 }
5950 ParticipantLocation::UnsharedProject => {
5951 leader_in_this_app = true;
5952 leader_in_this_project = false;
5953 }
5954 ParticipantLocation::External => {
5955 leader_in_this_app = false;
5956 leader_in_this_project = false;
5957 }
5958 };
5959 let state = self.follower_states.get(&peer_id.into())?;
5960 let mut item_to_activate = None;
5961 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
5962 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
5963 && (leader_in_this_project || !item.view.is_project_item(window, cx))
5964 {
5965 item_to_activate = Some((item.location, item.view.boxed_clone()));
5966 }
5967 } else if let Some(shared_screen) =
5968 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
5969 {
5970 item_to_activate = Some((None, Box::new(shared_screen)));
5971 }
5972 item_to_activate
5973 }
5974
5975 fn shared_screen_for_peer(
5976 &self,
5977 peer_id: PeerId,
5978 pane: &Entity<Pane>,
5979 window: &mut Window,
5980 cx: &mut App,
5981 ) -> Option<Entity<SharedScreen>> {
5982 self.active_call()?
5983 .create_shared_screen(peer_id, pane, window, cx)
5984 }
5985
5986 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5987 if window.is_window_active() {
5988 self.update_active_view_for_followers(window, cx);
5989
5990 if let Some(database_id) = self.database_id {
5991 let db = WorkspaceDb::global(cx);
5992 cx.background_spawn(async move { db.update_timestamp(database_id).await })
5993 .detach();
5994 }
5995 } else {
5996 for pane in &self.panes {
5997 pane.update(cx, |pane, cx| {
5998 if let Some(item) = pane.active_item() {
5999 item.workspace_deactivated(window, cx);
6000 }
6001 for item in pane.items() {
6002 if matches!(
6003 item.workspace_settings(cx).autosave,
6004 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
6005 ) {
6006 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
6007 .detach_and_log_err(cx);
6008 }
6009 }
6010 });
6011 }
6012 }
6013 }
6014
6015 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
6016 self.active_call.as_ref().map(|(call, _)| &*call.0)
6017 }
6018
6019 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
6020 self.active_call.as_ref().map(|(call, _)| call.clone())
6021 }
6022
6023 fn on_active_call_event(
6024 &mut self,
6025 event: &ActiveCallEvent,
6026 window: &mut Window,
6027 cx: &mut Context<Self>,
6028 ) {
6029 match event {
6030 ActiveCallEvent::ParticipantLocationChanged { participant_id }
6031 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
6032 self.leader_updated(participant_id, window, cx);
6033 }
6034 }
6035 }
6036
6037 pub fn database_id(&self) -> Option<WorkspaceId> {
6038 self.database_id
6039 }
6040
6041 #[cfg(any(test, feature = "test-support"))]
6042 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
6043 self.database_id = Some(id);
6044 }
6045
6046 pub fn session_id(&self) -> Option<String> {
6047 self.session_id.clone()
6048 }
6049
6050 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6051 let Some(display) = window.display(cx) else {
6052 return Task::ready(());
6053 };
6054 let Ok(display_uuid) = display.uuid() else {
6055 return Task::ready(());
6056 };
6057
6058 let window_bounds = window.inner_window_bounds();
6059 let database_id = self.database_id;
6060 let has_paths = !self.root_paths(cx).is_empty();
6061 let db = WorkspaceDb::global(cx);
6062 let kvp = db::kvp::KeyValueStore::global(cx);
6063
6064 cx.background_executor().spawn(async move {
6065 if !has_paths {
6066 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6067 .await
6068 .log_err();
6069 }
6070 if let Some(database_id) = database_id {
6071 db.set_window_open_status(
6072 database_id,
6073 SerializedWindowBounds(window_bounds),
6074 display_uuid,
6075 )
6076 .await
6077 .log_err();
6078 } else {
6079 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6080 .await
6081 .log_err();
6082 }
6083 })
6084 }
6085
6086 /// Bypass the 200ms serialization throttle and write workspace state to
6087 /// the DB immediately. Returns a task the caller can await to ensure the
6088 /// write completes. Used by the quit handler so the most recent state
6089 /// isn't lost to a pending throttle timer when the process exits.
6090 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6091 self._schedule_serialize_workspace.take();
6092 self._serialize_workspace_task.take();
6093 self.bounds_save_task_queued.take();
6094
6095 let bounds_task = self.save_window_bounds(window, cx);
6096 let serialize_task = self.serialize_workspace_internal(window, cx);
6097 cx.spawn(async move |_| {
6098 bounds_task.await;
6099 serialize_task.await;
6100 })
6101 }
6102
6103 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6104 let project = self.project().read(cx);
6105 project
6106 .visible_worktrees(cx)
6107 .map(|worktree| worktree.read(cx).abs_path())
6108 .collect::<Vec<_>>()
6109 }
6110
6111 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6112 match member {
6113 Member::Axis(PaneAxis { members, .. }) => {
6114 for child in members.iter() {
6115 self.remove_panes(child.clone(), window, cx)
6116 }
6117 }
6118 Member::Pane(pane) => {
6119 self.force_remove_pane(&pane, &None, window, cx);
6120 }
6121 }
6122 }
6123
6124 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6125 self.session_id.take();
6126 self.serialize_workspace_internal(window, cx)
6127 }
6128
6129 fn force_remove_pane(
6130 &mut self,
6131 pane: &Entity<Pane>,
6132 focus_on: &Option<Entity<Pane>>,
6133 window: &mut Window,
6134 cx: &mut Context<Workspace>,
6135 ) {
6136 self.panes.retain(|p| p != pane);
6137 if let Some(focus_on) = focus_on {
6138 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6139 } else if self.active_pane() == pane {
6140 self.panes
6141 .last()
6142 .unwrap()
6143 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6144 }
6145 if self.last_active_center_pane == Some(pane.downgrade()) {
6146 self.last_active_center_pane = None;
6147 }
6148 cx.notify();
6149 }
6150
6151 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6152 if self._schedule_serialize_workspace.is_none() {
6153 self._schedule_serialize_workspace =
6154 Some(cx.spawn_in(window, async move |this, cx| {
6155 cx.background_executor()
6156 .timer(SERIALIZATION_THROTTLE_TIME)
6157 .await;
6158 this.update_in(cx, |this, window, cx| {
6159 this._serialize_workspace_task =
6160 Some(this.serialize_workspace_internal(window, cx));
6161 this._schedule_serialize_workspace.take();
6162 })
6163 .log_err();
6164 }));
6165 }
6166 }
6167
6168 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6169 let Some(database_id) = self.database_id() else {
6170 return Task::ready(());
6171 };
6172
6173 fn serialize_pane_handle(
6174 pane_handle: &Entity<Pane>,
6175 window: &mut Window,
6176 cx: &mut App,
6177 ) -> SerializedPane {
6178 let (items, active, pinned_count) = {
6179 let pane = pane_handle.read(cx);
6180 let active_item_id = pane.active_item().map(|item| item.item_id());
6181 (
6182 pane.items()
6183 .filter_map(|handle| {
6184 let handle = handle.to_serializable_item_handle(cx)?;
6185
6186 Some(SerializedItem {
6187 kind: Arc::from(handle.serialized_item_kind()),
6188 item_id: handle.item_id().as_u64(),
6189 active: Some(handle.item_id()) == active_item_id,
6190 preview: pane.is_active_preview_item(handle.item_id()),
6191 })
6192 })
6193 .collect::<Vec<_>>(),
6194 pane.has_focus(window, cx),
6195 pane.pinned_count(),
6196 )
6197 };
6198
6199 SerializedPane::new(items, active, pinned_count)
6200 }
6201
6202 fn build_serialized_pane_group(
6203 pane_group: &Member,
6204 window: &mut Window,
6205 cx: &mut App,
6206 ) -> SerializedPaneGroup {
6207 match pane_group {
6208 Member::Axis(PaneAxis {
6209 axis,
6210 members,
6211 flexes,
6212 bounding_boxes: _,
6213 }) => SerializedPaneGroup::Group {
6214 axis: SerializedAxis(*axis),
6215 children: members
6216 .iter()
6217 .map(|member| build_serialized_pane_group(member, window, cx))
6218 .collect::<Vec<_>>(),
6219 flexes: Some(flexes.lock().clone()),
6220 },
6221 Member::Pane(pane_handle) => {
6222 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6223 }
6224 }
6225 }
6226
6227 fn build_serialized_docks(
6228 this: &Workspace,
6229 window: &mut Window,
6230 cx: &mut App,
6231 ) -> DockStructure {
6232 this.capture_dock_state(window, cx)
6233 }
6234
6235 match self.workspace_location(cx) {
6236 WorkspaceLocation::Location(location, paths) => {
6237 let breakpoints = self.project.update(cx, |project, cx| {
6238 project
6239 .breakpoint_store()
6240 .read(cx)
6241 .all_source_breakpoints(cx)
6242 });
6243 let user_toolchains = self
6244 .project
6245 .read(cx)
6246 .user_toolchains(cx)
6247 .unwrap_or_default();
6248
6249 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6250 let docks = build_serialized_docks(self, window, cx);
6251 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6252
6253 let serialized_workspace = SerializedWorkspace {
6254 id: database_id,
6255 location,
6256 paths,
6257 center_group,
6258 window_bounds,
6259 display: Default::default(),
6260 docks,
6261 centered_layout: self.centered_layout,
6262 session_id: self.session_id.clone(),
6263 breakpoints,
6264 window_id: Some(window.window_handle().window_id().as_u64()),
6265 user_toolchains,
6266 };
6267
6268 let db = WorkspaceDb::global(cx);
6269 window.spawn(cx, async move |_| {
6270 db.save_workspace(serialized_workspace).await;
6271 })
6272 }
6273 WorkspaceLocation::DetachFromSession => {
6274 let window_bounds = SerializedWindowBounds(window.window_bounds());
6275 let display = window.display(cx).and_then(|d| d.uuid().ok());
6276 // Save dock state for empty local workspaces
6277 let docks = build_serialized_docks(self, window, cx);
6278 let db = WorkspaceDb::global(cx);
6279 let kvp = db::kvp::KeyValueStore::global(cx);
6280 window.spawn(cx, async move |_| {
6281 db.set_window_open_status(
6282 database_id,
6283 window_bounds,
6284 display.unwrap_or_default(),
6285 )
6286 .await
6287 .log_err();
6288 db.set_session_id(database_id, None).await.log_err();
6289 persistence::write_default_dock_state(&kvp, docks)
6290 .await
6291 .log_err();
6292 })
6293 }
6294 WorkspaceLocation::None => {
6295 // Save dock state for empty non-local workspaces
6296 let docks = build_serialized_docks(self, window, cx);
6297 let kvp = db::kvp::KeyValueStore::global(cx);
6298 window.spawn(cx, async move |_| {
6299 persistence::write_default_dock_state(&kvp, docks)
6300 .await
6301 .log_err();
6302 })
6303 }
6304 }
6305 }
6306
6307 fn has_any_items_open(&self, cx: &App) -> bool {
6308 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6309 }
6310
6311 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6312 let paths = PathList::new(&self.root_paths(cx));
6313 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6314 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6315 } else if self.project.read(cx).is_local() {
6316 if !paths.is_empty() || self.has_any_items_open(cx) {
6317 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6318 } else {
6319 WorkspaceLocation::DetachFromSession
6320 }
6321 } else {
6322 WorkspaceLocation::None
6323 }
6324 }
6325
6326 fn update_history(&self, cx: &mut App) {
6327 let Some(id) = self.database_id() else {
6328 return;
6329 };
6330 if !self.project.read(cx).is_local() {
6331 return;
6332 }
6333 if let Some(manager) = HistoryManager::global(cx) {
6334 let paths = PathList::new(&self.root_paths(cx));
6335 manager.update(cx, |this, cx| {
6336 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6337 });
6338 }
6339 }
6340
6341 async fn serialize_items(
6342 this: &WeakEntity<Self>,
6343 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6344 cx: &mut AsyncWindowContext,
6345 ) -> Result<()> {
6346 const CHUNK_SIZE: usize = 200;
6347
6348 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6349
6350 while let Some(items_received) = serializable_items.next().await {
6351 let unique_items =
6352 items_received
6353 .into_iter()
6354 .fold(HashMap::default(), |mut acc, item| {
6355 acc.entry(item.item_id()).or_insert(item);
6356 acc
6357 });
6358
6359 // We use into_iter() here so that the references to the items are moved into
6360 // the tasks and not kept alive while we're sleeping.
6361 for (_, item) in unique_items.into_iter() {
6362 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6363 item.serialize(workspace, false, window, cx)
6364 }) {
6365 cx.background_spawn(async move { task.await.log_err() })
6366 .detach();
6367 }
6368 }
6369
6370 cx.background_executor()
6371 .timer(SERIALIZATION_THROTTLE_TIME)
6372 .await;
6373 }
6374
6375 Ok(())
6376 }
6377
6378 pub(crate) fn enqueue_item_serialization(
6379 &mut self,
6380 item: Box<dyn SerializableItemHandle>,
6381 ) -> Result<()> {
6382 self.serializable_items_tx
6383 .unbounded_send(item)
6384 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6385 }
6386
6387 pub(crate) fn load_workspace(
6388 serialized_workspace: SerializedWorkspace,
6389 paths_to_open: Vec<Option<ProjectPath>>,
6390 window: &mut Window,
6391 cx: &mut Context<Workspace>,
6392 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6393 cx.spawn_in(window, async move |workspace, cx| {
6394 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6395
6396 let mut center_group = None;
6397 let mut center_items = None;
6398
6399 // Traverse the splits tree and add to things
6400 if let Some((group, active_pane, items)) = serialized_workspace
6401 .center_group
6402 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6403 .await
6404 {
6405 center_items = Some(items);
6406 center_group = Some((group, active_pane))
6407 }
6408
6409 let mut items_by_project_path = HashMap::default();
6410 let mut item_ids_by_kind = HashMap::default();
6411 let mut all_deserialized_items = Vec::default();
6412 cx.update(|_, cx| {
6413 for item in center_items.unwrap_or_default().into_iter().flatten() {
6414 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6415 item_ids_by_kind
6416 .entry(serializable_item_handle.serialized_item_kind())
6417 .or_insert(Vec::new())
6418 .push(item.item_id().as_u64() as ItemId);
6419 }
6420
6421 if let Some(project_path) = item.project_path(cx) {
6422 items_by_project_path.insert(project_path, item.clone());
6423 }
6424 all_deserialized_items.push(item);
6425 }
6426 })?;
6427
6428 let opened_items = paths_to_open
6429 .into_iter()
6430 .map(|path_to_open| {
6431 path_to_open
6432 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6433 })
6434 .collect::<Vec<_>>();
6435
6436 // Remove old panes from workspace panes list
6437 workspace.update_in(cx, |workspace, window, cx| {
6438 if let Some((center_group, active_pane)) = center_group {
6439 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6440
6441 // Swap workspace center group
6442 workspace.center = PaneGroup::with_root(center_group);
6443 workspace.center.set_is_center(true);
6444 workspace.center.mark_positions(cx);
6445
6446 if let Some(active_pane) = active_pane {
6447 workspace.set_active_pane(&active_pane, window, cx);
6448 cx.focus_self(window);
6449 } else {
6450 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6451 }
6452 }
6453
6454 let docks = serialized_workspace.docks;
6455
6456 for (dock, serialized_dock) in [
6457 (&mut workspace.right_dock, docks.right),
6458 (&mut workspace.left_dock, docks.left),
6459 (&mut workspace.bottom_dock, docks.bottom),
6460 ]
6461 .iter_mut()
6462 {
6463 dock.update(cx, |dock, cx| {
6464 dock.serialized_dock = Some(serialized_dock.clone());
6465 dock.restore_state(window, cx);
6466 });
6467 }
6468
6469 cx.notify();
6470 })?;
6471
6472 let _ = project
6473 .update(cx, |project, cx| {
6474 project
6475 .breakpoint_store()
6476 .update(cx, |breakpoint_store, cx| {
6477 breakpoint_store
6478 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6479 })
6480 })
6481 .await;
6482
6483 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6484 // after loading the items, we might have different items and in order to avoid
6485 // the database filling up, we delete items that haven't been loaded now.
6486 //
6487 // The items that have been loaded, have been saved after they've been added to the workspace.
6488 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6489 item_ids_by_kind
6490 .into_iter()
6491 .map(|(item_kind, loaded_items)| {
6492 SerializableItemRegistry::cleanup(
6493 item_kind,
6494 serialized_workspace.id,
6495 loaded_items,
6496 window,
6497 cx,
6498 )
6499 .log_err()
6500 })
6501 .collect::<Vec<_>>()
6502 })?;
6503
6504 futures::future::join_all(clean_up_tasks).await;
6505
6506 workspace
6507 .update_in(cx, |workspace, window, cx| {
6508 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6509 workspace.serialize_workspace_internal(window, cx).detach();
6510
6511 // Ensure that we mark the window as edited if we did load dirty items
6512 workspace.update_window_edited(window, cx);
6513 })
6514 .ok();
6515
6516 Ok(opened_items)
6517 })
6518 }
6519
6520 pub fn key_context(&self, cx: &App) -> KeyContext {
6521 let mut context = KeyContext::new_with_defaults();
6522 context.add("Workspace");
6523 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6524 if let Some(status) = self
6525 .debugger_provider
6526 .as_ref()
6527 .and_then(|provider| provider.active_thread_state(cx))
6528 {
6529 match status {
6530 ThreadStatus::Running | ThreadStatus::Stepping => {
6531 context.add("debugger_running");
6532 }
6533 ThreadStatus::Stopped => context.add("debugger_stopped"),
6534 ThreadStatus::Exited | ThreadStatus::Ended => {}
6535 }
6536 }
6537
6538 if self.left_dock.read(cx).is_open() {
6539 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6540 context.set("left_dock", active_panel.panel_key());
6541 }
6542 }
6543
6544 if self.right_dock.read(cx).is_open() {
6545 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6546 context.set("right_dock", active_panel.panel_key());
6547 }
6548 }
6549
6550 if self.bottom_dock.read(cx).is_open() {
6551 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6552 context.set("bottom_dock", active_panel.panel_key());
6553 }
6554 }
6555
6556 context
6557 }
6558
6559 /// Multiworkspace uses this to add workspace action handling to itself
6560 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6561 self.add_workspace_actions_listeners(div, window, cx)
6562 .on_action(cx.listener(
6563 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6564 for action in &action_sequence.0 {
6565 window.dispatch_action(action.boxed_clone(), cx);
6566 }
6567 },
6568 ))
6569 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6570 .on_action(cx.listener(Self::close_all_items_and_panes))
6571 .on_action(cx.listener(Self::close_item_in_all_panes))
6572 .on_action(cx.listener(Self::save_all))
6573 .on_action(cx.listener(Self::send_keystrokes))
6574 .on_action(cx.listener(Self::add_folder_to_project))
6575 .on_action(cx.listener(Self::follow_next_collaborator))
6576 .on_action(cx.listener(Self::activate_pane_at_index))
6577 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6578 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6579 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6580 .on_action(cx.listener(Self::toggle_theme_mode))
6581 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6582 let pane = workspace.active_pane().clone();
6583 workspace.unfollow_in_pane(&pane, window, cx);
6584 }))
6585 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6586 workspace
6587 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6588 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6589 }))
6590 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6591 workspace
6592 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6593 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6594 }))
6595 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6596 workspace
6597 .save_active_item(SaveIntent::SaveAs, window, cx)
6598 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6599 }))
6600 .on_action(
6601 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6602 workspace.activate_previous_pane(window, cx)
6603 }),
6604 )
6605 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6606 workspace.activate_next_pane(window, cx)
6607 }))
6608 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6609 workspace.activate_last_pane(window, cx)
6610 }))
6611 .on_action(
6612 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6613 workspace.activate_next_window(cx)
6614 }),
6615 )
6616 .on_action(
6617 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6618 workspace.activate_previous_window(cx)
6619 }),
6620 )
6621 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6622 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6623 }))
6624 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6625 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6626 }))
6627 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6628 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6629 }))
6630 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6631 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6632 }))
6633 .on_action(cx.listener(
6634 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6635 workspace.move_item_to_pane_in_direction(action, window, cx)
6636 },
6637 ))
6638 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6639 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6640 }))
6641 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6642 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6643 }))
6644 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6645 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6646 }))
6647 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6648 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6649 }))
6650 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6651 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6652 SplitDirection::Down,
6653 SplitDirection::Up,
6654 SplitDirection::Right,
6655 SplitDirection::Left,
6656 ];
6657 for dir in DIRECTION_PRIORITY {
6658 if workspace.find_pane_in_direction(dir, cx).is_some() {
6659 workspace.swap_pane_in_direction(dir, cx);
6660 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6661 break;
6662 }
6663 }
6664 }))
6665 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6666 workspace.move_pane_to_border(SplitDirection::Left, cx)
6667 }))
6668 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6669 workspace.move_pane_to_border(SplitDirection::Right, cx)
6670 }))
6671 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6672 workspace.move_pane_to_border(SplitDirection::Up, cx)
6673 }))
6674 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6675 workspace.move_pane_to_border(SplitDirection::Down, cx)
6676 }))
6677 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6678 this.toggle_dock(DockPosition::Left, window, cx);
6679 }))
6680 .on_action(cx.listener(
6681 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6682 workspace.toggle_dock(DockPosition::Right, window, cx);
6683 },
6684 ))
6685 .on_action(cx.listener(
6686 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6687 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6688 },
6689 ))
6690 .on_action(cx.listener(
6691 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6692 if !workspace.close_active_dock(window, cx) {
6693 cx.propagate();
6694 }
6695 },
6696 ))
6697 .on_action(
6698 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6699 workspace.close_all_docks(window, cx);
6700 }),
6701 )
6702 .on_action(cx.listener(Self::toggle_all_docks))
6703 .on_action(cx.listener(
6704 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6705 workspace.clear_all_notifications(cx);
6706 },
6707 ))
6708 .on_action(cx.listener(
6709 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6710 workspace.clear_navigation_history(window, cx);
6711 },
6712 ))
6713 .on_action(cx.listener(
6714 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6715 if let Some((notification_id, _)) = workspace.notifications.pop() {
6716 workspace.suppress_notification(¬ification_id, cx);
6717 }
6718 },
6719 ))
6720 .on_action(cx.listener(
6721 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6722 workspace.show_worktree_trust_security_modal(true, window, cx);
6723 },
6724 ))
6725 .on_action(
6726 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6727 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6728 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6729 trusted_worktrees.clear_trusted_paths()
6730 });
6731 let db = WorkspaceDb::global(cx);
6732 cx.spawn(async move |_, cx| {
6733 if db.clear_trusted_worktrees().await.log_err().is_some() {
6734 cx.update(|cx| reload(cx));
6735 }
6736 })
6737 .detach();
6738 }
6739 }),
6740 )
6741 .on_action(cx.listener(
6742 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
6743 workspace.reopen_closed_item(window, cx).detach();
6744 },
6745 ))
6746 .on_action(cx.listener(
6747 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
6748 for dock in workspace.all_docks() {
6749 if dock.focus_handle(cx).contains_focused(window, cx) {
6750 let Some(panel) = dock.read(cx).active_panel() else {
6751 return;
6752 };
6753
6754 // Set to `None`, then the size will fall back to the default.
6755 panel.clone().set_size(None, window, cx);
6756
6757 return;
6758 }
6759 }
6760 },
6761 ))
6762 .on_action(cx.listener(
6763 |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
6764 for dock in workspace.all_docks() {
6765 if let Some(panel) = dock.read(cx).visible_panel() {
6766 // Set to `None`, then the size will fall back to the default.
6767 panel.clone().set_size(None, window, cx);
6768 }
6769 }
6770 },
6771 ))
6772 .on_action(cx.listener(
6773 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
6774 adjust_active_dock_size_by_px(
6775 px_with_ui_font_fallback(act.px, cx),
6776 workspace,
6777 window,
6778 cx,
6779 );
6780 },
6781 ))
6782 .on_action(cx.listener(
6783 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
6784 adjust_active_dock_size_by_px(
6785 px_with_ui_font_fallback(act.px, cx) * -1.,
6786 workspace,
6787 window,
6788 cx,
6789 );
6790 },
6791 ))
6792 .on_action(cx.listener(
6793 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
6794 adjust_open_docks_size_by_px(
6795 px_with_ui_font_fallback(act.px, cx),
6796 workspace,
6797 window,
6798 cx,
6799 );
6800 },
6801 ))
6802 .on_action(cx.listener(
6803 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
6804 adjust_open_docks_size_by_px(
6805 px_with_ui_font_fallback(act.px, cx) * -1.,
6806 workspace,
6807 window,
6808 cx,
6809 );
6810 },
6811 ))
6812 .on_action(cx.listener(Workspace::toggle_centered_layout))
6813 .on_action(cx.listener(
6814 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
6815 if let Some(active_dock) = workspace.active_dock(window, cx) {
6816 let dock = active_dock.read(cx);
6817 if let Some(active_panel) = dock.active_panel() {
6818 if active_panel.pane(cx).is_none() {
6819 let mut recent_pane: Option<Entity<Pane>> = None;
6820 let mut recent_timestamp = 0;
6821 for pane_handle in workspace.panes() {
6822 let pane = pane_handle.read(cx);
6823 for entry in pane.activation_history() {
6824 if entry.timestamp > recent_timestamp {
6825 recent_timestamp = entry.timestamp;
6826 recent_pane = Some(pane_handle.clone());
6827 }
6828 }
6829 }
6830
6831 if let Some(pane) = recent_pane {
6832 pane.update(cx, |pane, cx| {
6833 let current_index = pane.active_item_index();
6834 let items_len = pane.items_len();
6835 if items_len > 0 {
6836 let next_index = if current_index + 1 < items_len {
6837 current_index + 1
6838 } else {
6839 0
6840 };
6841 pane.activate_item(
6842 next_index, false, false, window, cx,
6843 );
6844 }
6845 });
6846 return;
6847 }
6848 }
6849 }
6850 }
6851 cx.propagate();
6852 },
6853 ))
6854 .on_action(cx.listener(
6855 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
6856 if let Some(active_dock) = workspace.active_dock(window, cx) {
6857 let dock = active_dock.read(cx);
6858 if let Some(active_panel) = dock.active_panel() {
6859 if active_panel.pane(cx).is_none() {
6860 let mut recent_pane: Option<Entity<Pane>> = None;
6861 let mut recent_timestamp = 0;
6862 for pane_handle in workspace.panes() {
6863 let pane = pane_handle.read(cx);
6864 for entry in pane.activation_history() {
6865 if entry.timestamp > recent_timestamp {
6866 recent_timestamp = entry.timestamp;
6867 recent_pane = Some(pane_handle.clone());
6868 }
6869 }
6870 }
6871
6872 if let Some(pane) = recent_pane {
6873 pane.update(cx, |pane, cx| {
6874 let current_index = pane.active_item_index();
6875 let items_len = pane.items_len();
6876 if items_len > 0 {
6877 let prev_index = if current_index > 0 {
6878 current_index - 1
6879 } else {
6880 items_len.saturating_sub(1)
6881 };
6882 pane.activate_item(
6883 prev_index, false, false, window, cx,
6884 );
6885 }
6886 });
6887 return;
6888 }
6889 }
6890 }
6891 }
6892 cx.propagate();
6893 },
6894 ))
6895 .on_action(cx.listener(
6896 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
6897 if let Some(active_dock) = workspace.active_dock(window, cx) {
6898 let dock = active_dock.read(cx);
6899 if let Some(active_panel) = dock.active_panel() {
6900 if active_panel.pane(cx).is_none() {
6901 let active_pane = workspace.active_pane().clone();
6902 active_pane.update(cx, |pane, cx| {
6903 pane.close_active_item(action, window, cx)
6904 .detach_and_log_err(cx);
6905 });
6906 return;
6907 }
6908 }
6909 }
6910 cx.propagate();
6911 },
6912 ))
6913 .on_action(
6914 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
6915 let pane = workspace.active_pane().clone();
6916 if let Some(item) = pane.read(cx).active_item() {
6917 item.toggle_read_only(window, cx);
6918 }
6919 }),
6920 )
6921 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
6922 workspace.focus_center_pane(window, cx);
6923 }))
6924 .on_action(cx.listener(Workspace::cancel))
6925 }
6926
6927 #[cfg(any(test, feature = "test-support"))]
6928 pub fn set_random_database_id(&mut self) {
6929 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
6930 }
6931
6932 #[cfg(any(test, feature = "test-support"))]
6933 pub(crate) fn test_new(
6934 project: Entity<Project>,
6935 window: &mut Window,
6936 cx: &mut Context<Self>,
6937 ) -> Self {
6938 use node_runtime::NodeRuntime;
6939 use session::Session;
6940
6941 let client = project.read(cx).client();
6942 let user_store = project.read(cx).user_store();
6943 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
6944 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
6945 window.activate_window();
6946 let app_state = Arc::new(AppState {
6947 languages: project.read(cx).languages().clone(),
6948 workspace_store,
6949 client,
6950 user_store,
6951 fs: project.read(cx).fs().clone(),
6952 build_window_options: |_, _| Default::default(),
6953 node_runtime: NodeRuntime::unavailable(),
6954 session,
6955 });
6956 let workspace = Self::new(Default::default(), project, app_state, window, cx);
6957 workspace
6958 .active_pane
6959 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6960 workspace
6961 }
6962
6963 pub fn register_action<A: Action>(
6964 &mut self,
6965 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
6966 ) -> &mut Self {
6967 let callback = Arc::new(callback);
6968
6969 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
6970 let callback = callback.clone();
6971 div.on_action(cx.listener(move |workspace, event, window, cx| {
6972 (callback)(workspace, event, window, cx)
6973 }))
6974 }));
6975 self
6976 }
6977 pub fn register_action_renderer(
6978 &mut self,
6979 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
6980 ) -> &mut Self {
6981 self.workspace_actions.push(Box::new(callback));
6982 self
6983 }
6984
6985 fn add_workspace_actions_listeners(
6986 &self,
6987 mut div: Div,
6988 window: &mut Window,
6989 cx: &mut Context<Self>,
6990 ) -> Div {
6991 for action in self.workspace_actions.iter() {
6992 div = (action)(div, self, window, cx)
6993 }
6994 div
6995 }
6996
6997 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
6998 self.modal_layer.read(cx).has_active_modal()
6999 }
7000
7001 pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
7002 self.modal_layer
7003 .read(cx)
7004 .is_active_modal_command_palette(cx)
7005 }
7006
7007 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
7008 self.modal_layer.read(cx).active_modal()
7009 }
7010
7011 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
7012 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
7013 /// If no modal is active, the new modal will be shown.
7014 ///
7015 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
7016 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
7017 /// will not be shown.
7018 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
7019 where
7020 B: FnOnce(&mut Window, &mut Context<V>) -> V,
7021 {
7022 self.modal_layer.update(cx, |modal_layer, cx| {
7023 modal_layer.toggle_modal(window, cx, build)
7024 })
7025 }
7026
7027 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
7028 self.modal_layer
7029 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
7030 }
7031
7032 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
7033 self.toast_layer
7034 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
7035 }
7036
7037 pub fn toggle_centered_layout(
7038 &mut self,
7039 _: &ToggleCenteredLayout,
7040 _: &mut Window,
7041 cx: &mut Context<Self>,
7042 ) {
7043 self.centered_layout = !self.centered_layout;
7044 if let Some(database_id) = self.database_id() {
7045 let db = WorkspaceDb::global(cx);
7046 let centered_layout = self.centered_layout;
7047 cx.background_spawn(async move {
7048 db.set_centered_layout(database_id, centered_layout).await
7049 })
7050 .detach_and_log_err(cx);
7051 }
7052 cx.notify();
7053 }
7054
7055 fn adjust_padding(padding: Option<f32>) -> f32 {
7056 padding
7057 .unwrap_or(CenteredPaddingSettings::default().0)
7058 .clamp(
7059 CenteredPaddingSettings::MIN_PADDING,
7060 CenteredPaddingSettings::MAX_PADDING,
7061 )
7062 }
7063
7064 fn render_dock(
7065 &self,
7066 position: DockPosition,
7067 dock: &Entity<Dock>,
7068 window: &mut Window,
7069 cx: &mut App,
7070 ) -> Option<Div> {
7071 if self.zoomed_position == Some(position) {
7072 return None;
7073 }
7074
7075 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7076 let pane = panel.pane(cx)?;
7077 let follower_states = &self.follower_states;
7078 leader_border_for_pane(follower_states, &pane, window, cx)
7079 });
7080
7081 Some(
7082 div()
7083 .flex()
7084 .flex_none()
7085 .overflow_hidden()
7086 .child(dock.clone())
7087 .children(leader_border),
7088 )
7089 }
7090
7091 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7092 window
7093 .root::<MultiWorkspace>()
7094 .flatten()
7095 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7096 }
7097
7098 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7099 self.zoomed.as_ref()
7100 }
7101
7102 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7103 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7104 return;
7105 };
7106 let windows = cx.windows();
7107 let next_window =
7108 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7109 || {
7110 windows
7111 .iter()
7112 .cycle()
7113 .skip_while(|window| window.window_id() != current_window_id)
7114 .nth(1)
7115 },
7116 );
7117
7118 if let Some(window) = next_window {
7119 window
7120 .update(cx, |_, window, _| window.activate_window())
7121 .ok();
7122 }
7123 }
7124
7125 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7126 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7127 return;
7128 };
7129 let windows = cx.windows();
7130 let prev_window =
7131 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7132 || {
7133 windows
7134 .iter()
7135 .rev()
7136 .cycle()
7137 .skip_while(|window| window.window_id() != current_window_id)
7138 .nth(1)
7139 },
7140 );
7141
7142 if let Some(window) = prev_window {
7143 window
7144 .update(cx, |_, window, _| window.activate_window())
7145 .ok();
7146 }
7147 }
7148
7149 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7150 if cx.stop_active_drag(window) {
7151 } else if let Some((notification_id, _)) = self.notifications.pop() {
7152 dismiss_app_notification(¬ification_id, cx);
7153 } else {
7154 cx.propagate();
7155 }
7156 }
7157
7158 fn adjust_dock_size_by_px(
7159 &mut self,
7160 panel_size: Pixels,
7161 dock_pos: DockPosition,
7162 px: Pixels,
7163 window: &mut Window,
7164 cx: &mut Context<Self>,
7165 ) {
7166 match dock_pos {
7167 DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
7168 DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
7169 DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
7170 }
7171 }
7172
7173 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7174 let workspace_width = self.bounds.size.width;
7175 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7176
7177 self.right_dock.read_with(cx, |right_dock, cx| {
7178 let right_dock_size = right_dock
7179 .active_panel_size(window, cx)
7180 .unwrap_or(Pixels::ZERO);
7181 if right_dock_size + size > workspace_width {
7182 size = workspace_width - right_dock_size
7183 }
7184 });
7185
7186 self.left_dock.update(cx, |left_dock, cx| {
7187 if WorkspaceSettings::get_global(cx)
7188 .resize_all_panels_in_dock
7189 .contains(&DockPosition::Left)
7190 {
7191 left_dock.resize_all_panels(Some(size), window, cx);
7192 } else {
7193 left_dock.resize_active_panel(Some(size), window, cx);
7194 }
7195 });
7196 }
7197
7198 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7199 let workspace_width = self.bounds.size.width;
7200 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7201 self.left_dock.read_with(cx, |left_dock, cx| {
7202 let left_dock_size = left_dock
7203 .active_panel_size(window, cx)
7204 .unwrap_or(Pixels::ZERO);
7205 if left_dock_size + size > workspace_width {
7206 size = workspace_width - left_dock_size
7207 }
7208 });
7209 self.right_dock.update(cx, |right_dock, cx| {
7210 if WorkspaceSettings::get_global(cx)
7211 .resize_all_panels_in_dock
7212 .contains(&DockPosition::Right)
7213 {
7214 right_dock.resize_all_panels(Some(size), window, cx);
7215 } else {
7216 right_dock.resize_active_panel(Some(size), window, cx);
7217 }
7218 });
7219 }
7220
7221 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7222 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7223 self.bottom_dock.update(cx, |bottom_dock, cx| {
7224 if WorkspaceSettings::get_global(cx)
7225 .resize_all_panels_in_dock
7226 .contains(&DockPosition::Bottom)
7227 {
7228 bottom_dock.resize_all_panels(Some(size), window, cx);
7229 } else {
7230 bottom_dock.resize_active_panel(Some(size), window, cx);
7231 }
7232 });
7233 }
7234
7235 fn toggle_edit_predictions_all_files(
7236 &mut self,
7237 _: &ToggleEditPrediction,
7238 _window: &mut Window,
7239 cx: &mut Context<Self>,
7240 ) {
7241 let fs = self.project().read(cx).fs().clone();
7242 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7243 update_settings_file(fs, cx, move |file, _| {
7244 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7245 });
7246 }
7247
7248 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7249 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7250 let next_mode = match current_mode {
7251 Some(theme::ThemeAppearanceMode::Light) => theme::ThemeAppearanceMode::Dark,
7252 Some(theme::ThemeAppearanceMode::Dark) => theme::ThemeAppearanceMode::Light,
7253 Some(theme::ThemeAppearanceMode::System) | None => match cx.theme().appearance() {
7254 theme::Appearance::Light => theme::ThemeAppearanceMode::Dark,
7255 theme::Appearance::Dark => theme::ThemeAppearanceMode::Light,
7256 },
7257 };
7258
7259 let fs = self.project().read(cx).fs().clone();
7260 settings::update_settings_file(fs, cx, move |settings, _cx| {
7261 theme::set_mode(settings, next_mode);
7262 });
7263 }
7264
7265 pub fn show_worktree_trust_security_modal(
7266 &mut self,
7267 toggle: bool,
7268 window: &mut Window,
7269 cx: &mut Context<Self>,
7270 ) {
7271 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7272 if toggle {
7273 security_modal.update(cx, |security_modal, cx| {
7274 security_modal.dismiss(cx);
7275 })
7276 } else {
7277 security_modal.update(cx, |security_modal, cx| {
7278 security_modal.refresh_restricted_paths(cx);
7279 });
7280 }
7281 } else {
7282 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7283 .map(|trusted_worktrees| {
7284 trusted_worktrees
7285 .read(cx)
7286 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7287 })
7288 .unwrap_or(false);
7289 if has_restricted_worktrees {
7290 let project = self.project().read(cx);
7291 let remote_host = project
7292 .remote_connection_options(cx)
7293 .map(RemoteHostLocation::from);
7294 let worktree_store = project.worktree_store().downgrade();
7295 self.toggle_modal(window, cx, |_, cx| {
7296 SecurityModal::new(worktree_store, remote_host, cx)
7297 });
7298 }
7299 }
7300 }
7301}
7302
7303pub trait AnyActiveCall {
7304 fn entity(&self) -> AnyEntity;
7305 fn is_in_room(&self, _: &App) -> bool;
7306 fn room_id(&self, _: &App) -> Option<u64>;
7307 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7308 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7309 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7310 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7311 fn is_sharing_project(&self, _: &App) -> bool;
7312 fn has_remote_participants(&self, _: &App) -> bool;
7313 fn local_participant_is_guest(&self, _: &App) -> bool;
7314 fn client(&self, _: &App) -> Arc<Client>;
7315 fn share_on_join(&self, _: &App) -> bool;
7316 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7317 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7318 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7319 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7320 fn join_project(
7321 &self,
7322 _: u64,
7323 _: Arc<LanguageRegistry>,
7324 _: Arc<dyn Fs>,
7325 _: &mut App,
7326 ) -> Task<Result<Entity<Project>>>;
7327 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7328 fn subscribe(
7329 &self,
7330 _: &mut Window,
7331 _: &mut Context<Workspace>,
7332 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7333 ) -> Subscription;
7334 fn create_shared_screen(
7335 &self,
7336 _: PeerId,
7337 _: &Entity<Pane>,
7338 _: &mut Window,
7339 _: &mut App,
7340 ) -> Option<Entity<SharedScreen>>;
7341}
7342
7343#[derive(Clone)]
7344pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7345impl Global for GlobalAnyActiveCall {}
7346
7347impl GlobalAnyActiveCall {
7348 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7349 cx.try_global()
7350 }
7351
7352 pub(crate) fn global(cx: &App) -> &Self {
7353 cx.global()
7354 }
7355}
7356
7357pub fn merge_conflict_notification_id() -> NotificationId {
7358 struct MergeConflictNotification;
7359 NotificationId::unique::<MergeConflictNotification>()
7360}
7361
7362/// Workspace-local view of a remote participant's location.
7363#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7364pub enum ParticipantLocation {
7365 SharedProject { project_id: u64 },
7366 UnsharedProject,
7367 External,
7368}
7369
7370impl ParticipantLocation {
7371 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7372 match location
7373 .and_then(|l| l.variant)
7374 .context("participant location was not provided")?
7375 {
7376 proto::participant_location::Variant::SharedProject(project) => {
7377 Ok(Self::SharedProject {
7378 project_id: project.id,
7379 })
7380 }
7381 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7382 proto::participant_location::Variant::External(_) => Ok(Self::External),
7383 }
7384 }
7385}
7386/// Workspace-local view of a remote collaborator's state.
7387/// This is the subset of `call::RemoteParticipant` that workspace needs.
7388#[derive(Clone)]
7389pub struct RemoteCollaborator {
7390 pub user: Arc<User>,
7391 pub peer_id: PeerId,
7392 pub location: ParticipantLocation,
7393 pub participant_index: ParticipantIndex,
7394}
7395
7396pub enum ActiveCallEvent {
7397 ParticipantLocationChanged { participant_id: PeerId },
7398 RemoteVideoTracksChanged { participant_id: PeerId },
7399}
7400
7401fn leader_border_for_pane(
7402 follower_states: &HashMap<CollaboratorId, FollowerState>,
7403 pane: &Entity<Pane>,
7404 _: &Window,
7405 cx: &App,
7406) -> Option<Div> {
7407 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7408 if state.pane() == pane {
7409 Some((*leader_id, state))
7410 } else {
7411 None
7412 }
7413 })?;
7414
7415 let mut leader_color = match leader_id {
7416 CollaboratorId::PeerId(leader_peer_id) => {
7417 let leader = GlobalAnyActiveCall::try_global(cx)?
7418 .0
7419 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7420
7421 cx.theme()
7422 .players()
7423 .color_for_participant(leader.participant_index.0)
7424 .cursor
7425 }
7426 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7427 };
7428 leader_color.fade_out(0.3);
7429 Some(
7430 div()
7431 .absolute()
7432 .size_full()
7433 .left_0()
7434 .top_0()
7435 .border_2()
7436 .border_color(leader_color),
7437 )
7438}
7439
7440fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7441 ZED_WINDOW_POSITION
7442 .zip(*ZED_WINDOW_SIZE)
7443 .map(|(position, size)| Bounds {
7444 origin: position,
7445 size,
7446 })
7447}
7448
7449fn open_items(
7450 serialized_workspace: Option<SerializedWorkspace>,
7451 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7452 window: &mut Window,
7453 cx: &mut Context<Workspace>,
7454) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7455 let restored_items = serialized_workspace.map(|serialized_workspace| {
7456 Workspace::load_workspace(
7457 serialized_workspace,
7458 project_paths_to_open
7459 .iter()
7460 .map(|(_, project_path)| project_path)
7461 .cloned()
7462 .collect(),
7463 window,
7464 cx,
7465 )
7466 });
7467
7468 cx.spawn_in(window, async move |workspace, cx| {
7469 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7470
7471 if let Some(restored_items) = restored_items {
7472 let restored_items = restored_items.await?;
7473
7474 let restored_project_paths = restored_items
7475 .iter()
7476 .filter_map(|item| {
7477 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7478 .ok()
7479 .flatten()
7480 })
7481 .collect::<HashSet<_>>();
7482
7483 for restored_item in restored_items {
7484 opened_items.push(restored_item.map(Ok));
7485 }
7486
7487 project_paths_to_open
7488 .iter_mut()
7489 .for_each(|(_, project_path)| {
7490 if let Some(project_path_to_open) = project_path
7491 && restored_project_paths.contains(project_path_to_open)
7492 {
7493 *project_path = None;
7494 }
7495 });
7496 } else {
7497 for _ in 0..project_paths_to_open.len() {
7498 opened_items.push(None);
7499 }
7500 }
7501 assert!(opened_items.len() == project_paths_to_open.len());
7502
7503 let tasks =
7504 project_paths_to_open
7505 .into_iter()
7506 .enumerate()
7507 .map(|(ix, (abs_path, project_path))| {
7508 let workspace = workspace.clone();
7509 cx.spawn(async move |cx| {
7510 let file_project_path = project_path?;
7511 let abs_path_task = workspace.update(cx, |workspace, cx| {
7512 workspace.project().update(cx, |project, cx| {
7513 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7514 })
7515 });
7516
7517 // We only want to open file paths here. If one of the items
7518 // here is a directory, it was already opened further above
7519 // with a `find_or_create_worktree`.
7520 if let Ok(task) = abs_path_task
7521 && task.await.is_none_or(|p| p.is_file())
7522 {
7523 return Some((
7524 ix,
7525 workspace
7526 .update_in(cx, |workspace, window, cx| {
7527 workspace.open_path(
7528 file_project_path,
7529 None,
7530 true,
7531 window,
7532 cx,
7533 )
7534 })
7535 .log_err()?
7536 .await,
7537 ));
7538 }
7539 None
7540 })
7541 });
7542
7543 let tasks = tasks.collect::<Vec<_>>();
7544
7545 let tasks = futures::future::join_all(tasks);
7546 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7547 opened_items[ix] = Some(path_open_result);
7548 }
7549
7550 Ok(opened_items)
7551 })
7552}
7553
7554#[derive(Clone)]
7555enum ActivateInDirectionTarget {
7556 Pane(Entity<Pane>),
7557 Dock(Entity<Dock>),
7558 Sidebar(FocusHandle),
7559}
7560
7561fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7562 window
7563 .update(cx, |multi_workspace, _, cx| {
7564 let workspace = multi_workspace.workspace().clone();
7565 workspace.update(cx, |workspace, cx| {
7566 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7567 struct DatabaseFailedNotification;
7568
7569 workspace.show_notification(
7570 NotificationId::unique::<DatabaseFailedNotification>(),
7571 cx,
7572 |cx| {
7573 cx.new(|cx| {
7574 MessageNotification::new("Failed to load the database file.", cx)
7575 .primary_message("File an Issue")
7576 .primary_icon(IconName::Plus)
7577 .primary_on_click(|window, cx| {
7578 window.dispatch_action(Box::new(FileBugReport), cx)
7579 })
7580 })
7581 },
7582 );
7583 }
7584 });
7585 })
7586 .log_err();
7587}
7588
7589fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7590 if val == 0 {
7591 ThemeSettings::get_global(cx).ui_font_size(cx)
7592 } else {
7593 px(val as f32)
7594 }
7595}
7596
7597fn adjust_active_dock_size_by_px(
7598 px: Pixels,
7599 workspace: &mut Workspace,
7600 window: &mut Window,
7601 cx: &mut Context<Workspace>,
7602) {
7603 let Some(active_dock) = workspace
7604 .all_docks()
7605 .into_iter()
7606 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7607 else {
7608 return;
7609 };
7610 let dock = active_dock.read(cx);
7611 let Some(panel_size) = dock.active_panel_size(window, cx) else {
7612 return;
7613 };
7614 let dock_pos = dock.position();
7615 workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
7616}
7617
7618fn adjust_open_docks_size_by_px(
7619 px: Pixels,
7620 workspace: &mut Workspace,
7621 window: &mut Window,
7622 cx: &mut Context<Workspace>,
7623) {
7624 let docks = workspace
7625 .all_docks()
7626 .into_iter()
7627 .filter_map(|dock| {
7628 if dock.read(cx).is_open() {
7629 let dock = dock.read(cx);
7630 let panel_size = dock.active_panel_size(window, cx)?;
7631 let dock_pos = dock.position();
7632 Some((panel_size, dock_pos, px))
7633 } else {
7634 None
7635 }
7636 })
7637 .collect::<Vec<_>>();
7638
7639 docks
7640 .into_iter()
7641 .for_each(|(panel_size, dock_pos, offset)| {
7642 workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
7643 });
7644}
7645
7646impl Focusable for Workspace {
7647 fn focus_handle(&self, cx: &App) -> FocusHandle {
7648 self.active_pane.focus_handle(cx)
7649 }
7650}
7651
7652#[derive(Clone)]
7653struct DraggedDock(DockPosition);
7654
7655impl Render for DraggedDock {
7656 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7657 gpui::Empty
7658 }
7659}
7660
7661impl Render for Workspace {
7662 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7663 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7664 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7665 log::info!("Rendered first frame");
7666 }
7667
7668 let centered_layout = self.centered_layout
7669 && self.center.panes().len() == 1
7670 && self.active_item(cx).is_some();
7671 let render_padding = |size| {
7672 (size > 0.0).then(|| {
7673 div()
7674 .h_full()
7675 .w(relative(size))
7676 .bg(cx.theme().colors().editor_background)
7677 .border_color(cx.theme().colors().pane_group_border)
7678 })
7679 };
7680 let paddings = if centered_layout {
7681 let settings = WorkspaceSettings::get_global(cx).centered_layout;
7682 (
7683 render_padding(Self::adjust_padding(
7684 settings.left_padding.map(|padding| padding.0),
7685 )),
7686 render_padding(Self::adjust_padding(
7687 settings.right_padding.map(|padding| padding.0),
7688 )),
7689 )
7690 } else {
7691 (None, None)
7692 };
7693 let ui_font = theme::setup_ui_font(window, cx);
7694
7695 let theme = cx.theme().clone();
7696 let colors = theme.colors();
7697 let notification_entities = self
7698 .notifications
7699 .iter()
7700 .map(|(_, notification)| notification.entity_id())
7701 .collect::<Vec<_>>();
7702 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
7703
7704 div()
7705 .relative()
7706 .size_full()
7707 .flex()
7708 .flex_col()
7709 .font(ui_font)
7710 .gap_0()
7711 .justify_start()
7712 .items_start()
7713 .text_color(colors.text)
7714 .overflow_hidden()
7715 .children(self.titlebar_item.clone())
7716 .on_modifiers_changed(move |_, _, cx| {
7717 for &id in ¬ification_entities {
7718 cx.notify(id);
7719 }
7720 })
7721 .child(
7722 div()
7723 .size_full()
7724 .relative()
7725 .flex_1()
7726 .flex()
7727 .flex_col()
7728 .child(
7729 div()
7730 .id("workspace")
7731 .bg(colors.background)
7732 .relative()
7733 .flex_1()
7734 .w_full()
7735 .flex()
7736 .flex_col()
7737 .overflow_hidden()
7738 .border_t_1()
7739 .border_b_1()
7740 .border_color(colors.border)
7741 .child({
7742 let this = cx.entity();
7743 canvas(
7744 move |bounds, window, cx| {
7745 this.update(cx, |this, cx| {
7746 let bounds_changed = this.bounds != bounds;
7747 this.bounds = bounds;
7748
7749 if bounds_changed {
7750 this.left_dock.update(cx, |dock, cx| {
7751 dock.clamp_panel_size(
7752 bounds.size.width,
7753 window,
7754 cx,
7755 )
7756 });
7757
7758 this.right_dock.update(cx, |dock, cx| {
7759 dock.clamp_panel_size(
7760 bounds.size.width,
7761 window,
7762 cx,
7763 )
7764 });
7765
7766 this.bottom_dock.update(cx, |dock, cx| {
7767 dock.clamp_panel_size(
7768 bounds.size.height,
7769 window,
7770 cx,
7771 )
7772 });
7773 }
7774 })
7775 },
7776 |_, _, _, _| {},
7777 )
7778 .absolute()
7779 .size_full()
7780 })
7781 .when(self.zoomed.is_none(), |this| {
7782 this.on_drag_move(cx.listener(
7783 move |workspace,
7784 e: &DragMoveEvent<DraggedDock>,
7785 window,
7786 cx| {
7787 if workspace.previous_dock_drag_coordinates
7788 != Some(e.event.position)
7789 {
7790 workspace.previous_dock_drag_coordinates =
7791 Some(e.event.position);
7792
7793 match e.drag(cx).0 {
7794 DockPosition::Left => {
7795 workspace.resize_left_dock(
7796 e.event.position.x
7797 - workspace.bounds.left(),
7798 window,
7799 cx,
7800 );
7801 }
7802 DockPosition::Right => {
7803 workspace.resize_right_dock(
7804 workspace.bounds.right()
7805 - e.event.position.x,
7806 window,
7807 cx,
7808 );
7809 }
7810 DockPosition::Bottom => {
7811 workspace.resize_bottom_dock(
7812 workspace.bounds.bottom()
7813 - e.event.position.y,
7814 window,
7815 cx,
7816 );
7817 }
7818 };
7819 workspace.serialize_workspace(window, cx);
7820 }
7821 },
7822 ))
7823
7824 })
7825 .child({
7826 match bottom_dock_layout {
7827 BottomDockLayout::Full => div()
7828 .flex()
7829 .flex_col()
7830 .h_full()
7831 .child(
7832 div()
7833 .flex()
7834 .flex_row()
7835 .flex_1()
7836 .overflow_hidden()
7837 .children(self.render_dock(
7838 DockPosition::Left,
7839 &self.left_dock,
7840 window,
7841 cx,
7842 ))
7843
7844 .child(
7845 div()
7846 .flex()
7847 .flex_col()
7848 .flex_1()
7849 .overflow_hidden()
7850 .child(
7851 h_flex()
7852 .flex_1()
7853 .when_some(
7854 paddings.0,
7855 |this, p| {
7856 this.child(
7857 p.border_r_1(),
7858 )
7859 },
7860 )
7861 .child(self.center.render(
7862 self.zoomed.as_ref(),
7863 &PaneRenderContext {
7864 follower_states:
7865 &self.follower_states,
7866 active_call: self.active_call(),
7867 active_pane: &self.active_pane,
7868 app_state: &self.app_state,
7869 project: &self.project,
7870 workspace: &self.weak_self,
7871 },
7872 window,
7873 cx,
7874 ))
7875 .when_some(
7876 paddings.1,
7877 |this, p| {
7878 this.child(
7879 p.border_l_1(),
7880 )
7881 },
7882 ),
7883 ),
7884 )
7885
7886 .children(self.render_dock(
7887 DockPosition::Right,
7888 &self.right_dock,
7889 window,
7890 cx,
7891 )),
7892 )
7893 .child(div().w_full().children(self.render_dock(
7894 DockPosition::Bottom,
7895 &self.bottom_dock,
7896 window,
7897 cx
7898 ))),
7899
7900 BottomDockLayout::LeftAligned => div()
7901 .flex()
7902 .flex_row()
7903 .h_full()
7904 .child(
7905 div()
7906 .flex()
7907 .flex_col()
7908 .flex_1()
7909 .h_full()
7910 .child(
7911 div()
7912 .flex()
7913 .flex_row()
7914 .flex_1()
7915 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
7916
7917 .child(
7918 div()
7919 .flex()
7920 .flex_col()
7921 .flex_1()
7922 .overflow_hidden()
7923 .child(
7924 h_flex()
7925 .flex_1()
7926 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7927 .child(self.center.render(
7928 self.zoomed.as_ref(),
7929 &PaneRenderContext {
7930 follower_states:
7931 &self.follower_states,
7932 active_call: self.active_call(),
7933 active_pane: &self.active_pane,
7934 app_state: &self.app_state,
7935 project: &self.project,
7936 workspace: &self.weak_self,
7937 },
7938 window,
7939 cx,
7940 ))
7941 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7942 )
7943 )
7944
7945 )
7946 .child(
7947 div()
7948 .w_full()
7949 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7950 ),
7951 )
7952 .children(self.render_dock(
7953 DockPosition::Right,
7954 &self.right_dock,
7955 window,
7956 cx,
7957 )),
7958 BottomDockLayout::RightAligned => div()
7959 .flex()
7960 .flex_row()
7961 .h_full()
7962 .children(self.render_dock(
7963 DockPosition::Left,
7964 &self.left_dock,
7965 window,
7966 cx,
7967 ))
7968
7969 .child(
7970 div()
7971 .flex()
7972 .flex_col()
7973 .flex_1()
7974 .h_full()
7975 .child(
7976 div()
7977 .flex()
7978 .flex_row()
7979 .flex_1()
7980 .child(
7981 div()
7982 .flex()
7983 .flex_col()
7984 .flex_1()
7985 .overflow_hidden()
7986 .child(
7987 h_flex()
7988 .flex_1()
7989 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7990 .child(self.center.render(
7991 self.zoomed.as_ref(),
7992 &PaneRenderContext {
7993 follower_states:
7994 &self.follower_states,
7995 active_call: self.active_call(),
7996 active_pane: &self.active_pane,
7997 app_state: &self.app_state,
7998 project: &self.project,
7999 workspace: &self.weak_self,
8000 },
8001 window,
8002 cx,
8003 ))
8004 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8005 )
8006 )
8007
8008 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
8009 )
8010 .child(
8011 div()
8012 .w_full()
8013 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8014 ),
8015 ),
8016 BottomDockLayout::Contained => div()
8017 .flex()
8018 .flex_row()
8019 .h_full()
8020 .children(self.render_dock(
8021 DockPosition::Left,
8022 &self.left_dock,
8023 window,
8024 cx,
8025 ))
8026
8027 .child(
8028 div()
8029 .flex()
8030 .flex_col()
8031 .flex_1()
8032 .overflow_hidden()
8033 .child(
8034 h_flex()
8035 .flex_1()
8036 .when_some(paddings.0, |this, p| {
8037 this.child(p.border_r_1())
8038 })
8039 .child(self.center.render(
8040 self.zoomed.as_ref(),
8041 &PaneRenderContext {
8042 follower_states:
8043 &self.follower_states,
8044 active_call: self.active_call(),
8045 active_pane: &self.active_pane,
8046 app_state: &self.app_state,
8047 project: &self.project,
8048 workspace: &self.weak_self,
8049 },
8050 window,
8051 cx,
8052 ))
8053 .when_some(paddings.1, |this, p| {
8054 this.child(p.border_l_1())
8055 }),
8056 )
8057 .children(self.render_dock(
8058 DockPosition::Bottom,
8059 &self.bottom_dock,
8060 window,
8061 cx,
8062 )),
8063 )
8064
8065 .children(self.render_dock(
8066 DockPosition::Right,
8067 &self.right_dock,
8068 window,
8069 cx,
8070 )),
8071 }
8072 })
8073 .children(self.zoomed.as_ref().and_then(|view| {
8074 let zoomed_view = view.upgrade()?;
8075 let div = div()
8076 .occlude()
8077 .absolute()
8078 .overflow_hidden()
8079 .border_color(colors.border)
8080 .bg(colors.background)
8081 .child(zoomed_view)
8082 .inset_0()
8083 .shadow_lg();
8084
8085 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8086 return Some(div);
8087 }
8088
8089 Some(match self.zoomed_position {
8090 Some(DockPosition::Left) => div.right_2().border_r_1(),
8091 Some(DockPosition::Right) => div.left_2().border_l_1(),
8092 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8093 None => {
8094 div.top_2().bottom_2().left_2().right_2().border_1()
8095 }
8096 })
8097 }))
8098 .children(self.render_notifications(window, cx)),
8099 )
8100 .when(self.status_bar_visible(cx), |parent| {
8101 parent.child(self.status_bar.clone())
8102 })
8103 .child(self.toast_layer.clone()),
8104 )
8105 }
8106}
8107
8108impl WorkspaceStore {
8109 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8110 Self {
8111 workspaces: Default::default(),
8112 _subscriptions: vec![
8113 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8114 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8115 ],
8116 client,
8117 }
8118 }
8119
8120 pub fn update_followers(
8121 &self,
8122 project_id: Option<u64>,
8123 update: proto::update_followers::Variant,
8124 cx: &App,
8125 ) -> Option<()> {
8126 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8127 let room_id = active_call.0.room_id(cx)?;
8128 self.client
8129 .send(proto::UpdateFollowers {
8130 room_id,
8131 project_id,
8132 variant: Some(update),
8133 })
8134 .log_err()
8135 }
8136
8137 pub async fn handle_follow(
8138 this: Entity<Self>,
8139 envelope: TypedEnvelope<proto::Follow>,
8140 mut cx: AsyncApp,
8141 ) -> Result<proto::FollowResponse> {
8142 this.update(&mut cx, |this, cx| {
8143 let follower = Follower {
8144 project_id: envelope.payload.project_id,
8145 peer_id: envelope.original_sender_id()?,
8146 };
8147
8148 let mut response = proto::FollowResponse::default();
8149
8150 this.workspaces.retain(|(window_handle, weak_workspace)| {
8151 let Some(workspace) = weak_workspace.upgrade() else {
8152 return false;
8153 };
8154 window_handle
8155 .update(cx, |_, window, cx| {
8156 workspace.update(cx, |workspace, cx| {
8157 let handler_response =
8158 workspace.handle_follow(follower.project_id, window, cx);
8159 if let Some(active_view) = handler_response.active_view
8160 && workspace.project.read(cx).remote_id() == follower.project_id
8161 {
8162 response.active_view = Some(active_view)
8163 }
8164 });
8165 })
8166 .is_ok()
8167 });
8168
8169 Ok(response)
8170 })
8171 }
8172
8173 async fn handle_update_followers(
8174 this: Entity<Self>,
8175 envelope: TypedEnvelope<proto::UpdateFollowers>,
8176 mut cx: AsyncApp,
8177 ) -> Result<()> {
8178 let leader_id = envelope.original_sender_id()?;
8179 let update = envelope.payload;
8180
8181 this.update(&mut cx, |this, cx| {
8182 this.workspaces.retain(|(window_handle, weak_workspace)| {
8183 let Some(workspace) = weak_workspace.upgrade() else {
8184 return false;
8185 };
8186 window_handle
8187 .update(cx, |_, window, cx| {
8188 workspace.update(cx, |workspace, cx| {
8189 let project_id = workspace.project.read(cx).remote_id();
8190 if update.project_id != project_id && update.project_id.is_some() {
8191 return;
8192 }
8193 workspace.handle_update_followers(
8194 leader_id,
8195 update.clone(),
8196 window,
8197 cx,
8198 );
8199 });
8200 })
8201 .is_ok()
8202 });
8203 Ok(())
8204 })
8205 }
8206
8207 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8208 self.workspaces.iter().map(|(_, weak)| weak)
8209 }
8210
8211 pub fn workspaces_with_windows(
8212 &self,
8213 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8214 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8215 }
8216}
8217
8218impl ViewId {
8219 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8220 Ok(Self {
8221 creator: message
8222 .creator
8223 .map(CollaboratorId::PeerId)
8224 .context("creator is missing")?,
8225 id: message.id,
8226 })
8227 }
8228
8229 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8230 if let CollaboratorId::PeerId(peer_id) = self.creator {
8231 Some(proto::ViewId {
8232 creator: Some(peer_id),
8233 id: self.id,
8234 })
8235 } else {
8236 None
8237 }
8238 }
8239}
8240
8241impl FollowerState {
8242 fn pane(&self) -> &Entity<Pane> {
8243 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8244 }
8245}
8246
8247pub trait WorkspaceHandle {
8248 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8249}
8250
8251impl WorkspaceHandle for Entity<Workspace> {
8252 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8253 self.read(cx)
8254 .worktrees(cx)
8255 .flat_map(|worktree| {
8256 let worktree_id = worktree.read(cx).id();
8257 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8258 worktree_id,
8259 path: f.path.clone(),
8260 })
8261 })
8262 .collect::<Vec<_>>()
8263 }
8264}
8265
8266pub async fn last_opened_workspace_location(
8267 db: &WorkspaceDb,
8268 fs: &dyn fs::Fs,
8269) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8270 db.last_workspace(fs)
8271 .await
8272 .log_err()
8273 .flatten()
8274 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8275}
8276
8277pub async fn last_session_workspace_locations(
8278 db: &WorkspaceDb,
8279 last_session_id: &str,
8280 last_session_window_stack: Option<Vec<WindowId>>,
8281 fs: &dyn fs::Fs,
8282) -> Option<Vec<SessionWorkspace>> {
8283 db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8284 .await
8285 .log_err()
8286}
8287
8288pub struct MultiWorkspaceRestoreResult {
8289 pub window_handle: WindowHandle<MultiWorkspace>,
8290 pub errors: Vec<anyhow::Error>,
8291}
8292
8293pub async fn restore_multiworkspace(
8294 multi_workspace: SerializedMultiWorkspace,
8295 app_state: Arc<AppState>,
8296 cx: &mut AsyncApp,
8297) -> anyhow::Result<MultiWorkspaceRestoreResult> {
8298 let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
8299 let mut group_iter = workspaces.into_iter();
8300 let first = group_iter
8301 .next()
8302 .context("window group must not be empty")?;
8303
8304 let window_handle = if first.paths.is_empty() {
8305 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
8306 .await?
8307 } else {
8308 let OpenResult { window, .. } = cx
8309 .update(|cx| {
8310 Workspace::new_local(
8311 first.paths.paths().to_vec(),
8312 app_state.clone(),
8313 None,
8314 None,
8315 None,
8316 true,
8317 cx,
8318 )
8319 })
8320 .await?;
8321 window
8322 };
8323
8324 let mut errors = Vec::new();
8325
8326 for session_workspace in group_iter {
8327 let error = if session_workspace.paths.is_empty() {
8328 cx.update(|cx| {
8329 open_workspace_by_id(
8330 session_workspace.workspace_id,
8331 app_state.clone(),
8332 Some(window_handle),
8333 cx,
8334 )
8335 })
8336 .await
8337 .err()
8338 } else {
8339 cx.update(|cx| {
8340 Workspace::new_local(
8341 session_workspace.paths.paths().to_vec(),
8342 app_state.clone(),
8343 Some(window_handle),
8344 None,
8345 None,
8346 false,
8347 cx,
8348 )
8349 })
8350 .await
8351 .err()
8352 };
8353
8354 if let Some(error) = error {
8355 errors.push(error);
8356 }
8357 }
8358
8359 if let Some(target_id) = state.active_workspace_id {
8360 window_handle
8361 .update(cx, |multi_workspace, window, cx| {
8362 let target_index = multi_workspace
8363 .workspaces()
8364 .iter()
8365 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8366 if let Some(index) = target_index {
8367 multi_workspace.activate_index(index, window, cx);
8368 } else if !multi_workspace.workspaces().is_empty() {
8369 multi_workspace.activate_index(0, window, cx);
8370 }
8371 })
8372 .ok();
8373 } else {
8374 window_handle
8375 .update(cx, |multi_workspace, window, cx| {
8376 if !multi_workspace.workspaces().is_empty() {
8377 multi_workspace.activate_index(0, window, cx);
8378 }
8379 })
8380 .ok();
8381 }
8382
8383 if state.sidebar_open {
8384 window_handle
8385 .update(cx, |multi_workspace, _, cx| {
8386 multi_workspace.open_sidebar(cx);
8387 })
8388 .ok();
8389 }
8390
8391 window_handle
8392 .update(cx, |_, window, _cx| {
8393 window.activate_window();
8394 })
8395 .ok();
8396
8397 Ok(MultiWorkspaceRestoreResult {
8398 window_handle,
8399 errors,
8400 })
8401}
8402
8403actions!(
8404 collab,
8405 [
8406 /// Opens the channel notes for the current call.
8407 ///
8408 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8409 /// channel in the collab panel.
8410 ///
8411 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8412 /// can be copied via "Copy link to section" in the context menu of the channel notes
8413 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8414 OpenChannelNotes,
8415 /// Mutes your microphone.
8416 Mute,
8417 /// Deafens yourself (mute both microphone and speakers).
8418 Deafen,
8419 /// Leaves the current call.
8420 LeaveCall,
8421 /// Shares the current project with collaborators.
8422 ShareProject,
8423 /// Shares your screen with collaborators.
8424 ScreenShare,
8425 /// Copies the current room name and session id for debugging purposes.
8426 CopyRoomId,
8427 ]
8428);
8429
8430/// Opens the channel notes for a specific channel by its ID.
8431#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8432#[action(namespace = collab)]
8433#[serde(deny_unknown_fields)]
8434pub struct OpenChannelNotesById {
8435 pub channel_id: u64,
8436}
8437
8438actions!(
8439 zed,
8440 [
8441 /// Opens the Zed log file.
8442 OpenLog,
8443 /// Reveals the Zed log file in the system file manager.
8444 RevealLogInFileManager
8445 ]
8446);
8447
8448async fn join_channel_internal(
8449 channel_id: ChannelId,
8450 app_state: &Arc<AppState>,
8451 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8452 requesting_workspace: Option<WeakEntity<Workspace>>,
8453 active_call: &dyn AnyActiveCall,
8454 cx: &mut AsyncApp,
8455) -> Result<bool> {
8456 let (should_prompt, already_in_channel) = cx.update(|cx| {
8457 if !active_call.is_in_room(cx) {
8458 return (false, false);
8459 }
8460
8461 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8462 let should_prompt = active_call.is_sharing_project(cx)
8463 && active_call.has_remote_participants(cx)
8464 && !already_in_channel;
8465 (should_prompt, already_in_channel)
8466 });
8467
8468 if already_in_channel {
8469 let task = cx.update(|cx| {
8470 if let Some((project, host)) = active_call.most_active_project(cx) {
8471 Some(join_in_room_project(project, host, app_state.clone(), cx))
8472 } else {
8473 None
8474 }
8475 });
8476 if let Some(task) = task {
8477 task.await?;
8478 }
8479 return anyhow::Ok(true);
8480 }
8481
8482 if should_prompt {
8483 if let Some(multi_workspace) = requesting_window {
8484 let answer = multi_workspace
8485 .update(cx, |_, window, cx| {
8486 window.prompt(
8487 PromptLevel::Warning,
8488 "Do you want to switch channels?",
8489 Some("Leaving this call will unshare your current project."),
8490 &["Yes, Join Channel", "Cancel"],
8491 cx,
8492 )
8493 })?
8494 .await;
8495
8496 if answer == Ok(1) {
8497 return Ok(false);
8498 }
8499 } else {
8500 return Ok(false);
8501 }
8502 }
8503
8504 let client = cx.update(|cx| active_call.client(cx));
8505
8506 let mut client_status = client.status();
8507
8508 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8509 'outer: loop {
8510 let Some(status) = client_status.recv().await else {
8511 anyhow::bail!("error connecting");
8512 };
8513
8514 match status {
8515 Status::Connecting
8516 | Status::Authenticating
8517 | Status::Authenticated
8518 | Status::Reconnecting
8519 | Status::Reauthenticating
8520 | Status::Reauthenticated => continue,
8521 Status::Connected { .. } => break 'outer,
8522 Status::SignedOut | Status::AuthenticationError => {
8523 return Err(ErrorCode::SignedOut.into());
8524 }
8525 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8526 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8527 return Err(ErrorCode::Disconnected.into());
8528 }
8529 }
8530 }
8531
8532 let joined = cx
8533 .update(|cx| active_call.join_channel(channel_id, cx))
8534 .await?;
8535
8536 if !joined {
8537 return anyhow::Ok(true);
8538 }
8539
8540 cx.update(|cx| active_call.room_update_completed(cx)).await;
8541
8542 let task = cx.update(|cx| {
8543 if let Some((project, host)) = active_call.most_active_project(cx) {
8544 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8545 }
8546
8547 // If you are the first to join a channel, see if you should share your project.
8548 if !active_call.has_remote_participants(cx)
8549 && !active_call.local_participant_is_guest(cx)
8550 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8551 {
8552 let project = workspace.update(cx, |workspace, cx| {
8553 let project = workspace.project.read(cx);
8554
8555 if !active_call.share_on_join(cx) {
8556 return None;
8557 }
8558
8559 if (project.is_local() || project.is_via_remote_server())
8560 && project.visible_worktrees(cx).any(|tree| {
8561 tree.read(cx)
8562 .root_entry()
8563 .is_some_and(|entry| entry.is_dir())
8564 })
8565 {
8566 Some(workspace.project.clone())
8567 } else {
8568 None
8569 }
8570 });
8571 if let Some(project) = project {
8572 let share_task = active_call.share_project(project, cx);
8573 return Some(cx.spawn(async move |_cx| -> Result<()> {
8574 share_task.await?;
8575 Ok(())
8576 }));
8577 }
8578 }
8579
8580 None
8581 });
8582 if let Some(task) = task {
8583 task.await?;
8584 return anyhow::Ok(true);
8585 }
8586 anyhow::Ok(false)
8587}
8588
8589pub fn join_channel(
8590 channel_id: ChannelId,
8591 app_state: Arc<AppState>,
8592 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8593 requesting_workspace: Option<WeakEntity<Workspace>>,
8594 cx: &mut App,
8595) -> Task<Result<()>> {
8596 let active_call = GlobalAnyActiveCall::global(cx).clone();
8597 cx.spawn(async move |cx| {
8598 let result = join_channel_internal(
8599 channel_id,
8600 &app_state,
8601 requesting_window,
8602 requesting_workspace,
8603 &*active_call.0,
8604 cx,
8605 )
8606 .await;
8607
8608 // join channel succeeded, and opened a window
8609 if matches!(result, Ok(true)) {
8610 return anyhow::Ok(());
8611 }
8612
8613 // find an existing workspace to focus and show call controls
8614 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8615 if active_window.is_none() {
8616 // no open workspaces, make one to show the error in (blergh)
8617 let OpenResult {
8618 window: window_handle,
8619 ..
8620 } = cx
8621 .update(|cx| {
8622 Workspace::new_local(
8623 vec![],
8624 app_state.clone(),
8625 requesting_window,
8626 None,
8627 None,
8628 true,
8629 cx,
8630 )
8631 })
8632 .await?;
8633
8634 window_handle
8635 .update(cx, |_, window, _cx| {
8636 window.activate_window();
8637 })
8638 .ok();
8639
8640 if result.is_ok() {
8641 cx.update(|cx| {
8642 cx.dispatch_action(&OpenChannelNotes);
8643 });
8644 }
8645
8646 active_window = Some(window_handle);
8647 }
8648
8649 if let Err(err) = result {
8650 log::error!("failed to join channel: {}", err);
8651 if let Some(active_window) = active_window {
8652 active_window
8653 .update(cx, |_, window, cx| {
8654 let detail: SharedString = match err.error_code() {
8655 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8656 ErrorCode::UpgradeRequired => concat!(
8657 "Your are running an unsupported version of Zed. ",
8658 "Please update to continue."
8659 )
8660 .into(),
8661 ErrorCode::NoSuchChannel => concat!(
8662 "No matching channel was found. ",
8663 "Please check the link and try again."
8664 )
8665 .into(),
8666 ErrorCode::Forbidden => concat!(
8667 "This channel is private, and you do not have access. ",
8668 "Please ask someone to add you and try again."
8669 )
8670 .into(),
8671 ErrorCode::Disconnected => {
8672 "Please check your internet connection and try again.".into()
8673 }
8674 _ => format!("{}\n\nPlease try again.", err).into(),
8675 };
8676 window.prompt(
8677 PromptLevel::Critical,
8678 "Failed to join channel",
8679 Some(&detail),
8680 &["Ok"],
8681 cx,
8682 )
8683 })?
8684 .await
8685 .ok();
8686 }
8687 }
8688
8689 // return ok, we showed the error to the user.
8690 anyhow::Ok(())
8691 })
8692}
8693
8694pub async fn get_any_active_multi_workspace(
8695 app_state: Arc<AppState>,
8696 mut cx: AsyncApp,
8697) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8698 // find an existing workspace to focus and show call controls
8699 let active_window = activate_any_workspace_window(&mut cx);
8700 if active_window.is_none() {
8701 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
8702 .await?;
8703 }
8704 activate_any_workspace_window(&mut cx).context("could not open zed")
8705}
8706
8707fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
8708 cx.update(|cx| {
8709 if let Some(workspace_window) = cx
8710 .active_window()
8711 .and_then(|window| window.downcast::<MultiWorkspace>())
8712 {
8713 return Some(workspace_window);
8714 }
8715
8716 for window in cx.windows() {
8717 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
8718 workspace_window
8719 .update(cx, |_, window, _| window.activate_window())
8720 .ok();
8721 return Some(workspace_window);
8722 }
8723 }
8724 None
8725 })
8726}
8727
8728pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
8729 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
8730}
8731
8732pub fn workspace_windows_for_location(
8733 serialized_location: &SerializedWorkspaceLocation,
8734 cx: &App,
8735) -> Vec<WindowHandle<MultiWorkspace>> {
8736 cx.windows()
8737 .into_iter()
8738 .filter_map(|window| window.downcast::<MultiWorkspace>())
8739 .filter(|multi_workspace| {
8740 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
8741 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
8742 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
8743 }
8744 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
8745 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
8746 a.distro_name == b.distro_name
8747 }
8748 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
8749 a.container_id == b.container_id
8750 }
8751 #[cfg(any(test, feature = "test-support"))]
8752 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
8753 a.id == b.id
8754 }
8755 _ => false,
8756 };
8757
8758 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
8759 multi_workspace.workspaces().iter().any(|workspace| {
8760 match workspace.read(cx).workspace_location(cx) {
8761 WorkspaceLocation::Location(location, _) => {
8762 match (&location, serialized_location) {
8763 (
8764 SerializedWorkspaceLocation::Local,
8765 SerializedWorkspaceLocation::Local,
8766 ) => true,
8767 (
8768 SerializedWorkspaceLocation::Remote(a),
8769 SerializedWorkspaceLocation::Remote(b),
8770 ) => same_host(a, b),
8771 _ => false,
8772 }
8773 }
8774 _ => false,
8775 }
8776 })
8777 })
8778 })
8779 .collect()
8780}
8781
8782pub async fn find_existing_workspace(
8783 abs_paths: &[PathBuf],
8784 open_options: &OpenOptions,
8785 location: &SerializedWorkspaceLocation,
8786 cx: &mut AsyncApp,
8787) -> (
8788 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
8789 OpenVisible,
8790) {
8791 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
8792 let mut open_visible = OpenVisible::All;
8793 let mut best_match = None;
8794
8795 if open_options.open_new_workspace != Some(true) {
8796 cx.update(|cx| {
8797 for window in workspace_windows_for_location(location, cx) {
8798 if let Ok(multi_workspace) = window.read(cx) {
8799 for workspace in multi_workspace.workspaces() {
8800 let project = workspace.read(cx).project.read(cx);
8801 let m = project.visibility_for_paths(
8802 abs_paths,
8803 open_options.open_new_workspace == None,
8804 cx,
8805 );
8806 if m > best_match {
8807 existing = Some((window, workspace.clone()));
8808 best_match = m;
8809 } else if best_match.is_none()
8810 && open_options.open_new_workspace == Some(false)
8811 {
8812 existing = Some((window, workspace.clone()))
8813 }
8814 }
8815 }
8816 }
8817 });
8818
8819 let all_paths_are_files = existing
8820 .as_ref()
8821 .and_then(|(_, target_workspace)| {
8822 cx.update(|cx| {
8823 let workspace = target_workspace.read(cx);
8824 let project = workspace.project.read(cx);
8825 let path_style = workspace.path_style(cx);
8826 Some(!abs_paths.iter().any(|path| {
8827 let path = util::paths::SanitizedPath::new(path);
8828 project.worktrees(cx).any(|worktree| {
8829 let worktree = worktree.read(cx);
8830 let abs_path = worktree.abs_path();
8831 path_style
8832 .strip_prefix(path.as_ref(), abs_path.as_ref())
8833 .and_then(|rel| worktree.entry_for_path(&rel))
8834 .is_some_and(|e| e.is_dir())
8835 })
8836 }))
8837 })
8838 })
8839 .unwrap_or(false);
8840
8841 if open_options.open_new_workspace.is_none()
8842 && existing.is_some()
8843 && open_options.wait
8844 && all_paths_are_files
8845 {
8846 cx.update(|cx| {
8847 let windows = workspace_windows_for_location(location, cx);
8848 let window = cx
8849 .active_window()
8850 .and_then(|window| window.downcast::<MultiWorkspace>())
8851 .filter(|window| windows.contains(window))
8852 .or_else(|| windows.into_iter().next());
8853 if let Some(window) = window {
8854 if let Ok(multi_workspace) = window.read(cx) {
8855 let active_workspace = multi_workspace.workspace().clone();
8856 existing = Some((window, active_workspace));
8857 open_visible = OpenVisible::None;
8858 }
8859 }
8860 });
8861 }
8862 }
8863 (existing, open_visible)
8864}
8865
8866#[derive(Default, Clone)]
8867pub struct OpenOptions {
8868 pub visible: Option<OpenVisible>,
8869 pub focus: Option<bool>,
8870 pub open_new_workspace: Option<bool>,
8871 pub wait: bool,
8872 pub replace_window: Option<WindowHandle<MultiWorkspace>>,
8873 pub env: Option<HashMap<String, String>>,
8874}
8875
8876/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
8877/// or [`Workspace::open_workspace_for_paths`].
8878pub struct OpenResult {
8879 pub window: WindowHandle<MultiWorkspace>,
8880 pub workspace: Entity<Workspace>,
8881 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
8882}
8883
8884/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
8885pub fn open_workspace_by_id(
8886 workspace_id: WorkspaceId,
8887 app_state: Arc<AppState>,
8888 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8889 cx: &mut App,
8890) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
8891 let project_handle = Project::local(
8892 app_state.client.clone(),
8893 app_state.node_runtime.clone(),
8894 app_state.user_store.clone(),
8895 app_state.languages.clone(),
8896 app_state.fs.clone(),
8897 None,
8898 project::LocalProjectFlags {
8899 init_worktree_trust: true,
8900 ..project::LocalProjectFlags::default()
8901 },
8902 cx,
8903 );
8904
8905 let db = WorkspaceDb::global(cx);
8906 let kvp = db::kvp::KeyValueStore::global(cx);
8907 cx.spawn(async move |cx| {
8908 let serialized_workspace = db
8909 .workspace_for_id(workspace_id)
8910 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
8911
8912 let centered_layout = serialized_workspace.centered_layout;
8913
8914 let (window, workspace) = if let Some(window) = requesting_window {
8915 let workspace = window.update(cx, |multi_workspace, window, cx| {
8916 let workspace = cx.new(|cx| {
8917 let mut workspace = Workspace::new(
8918 Some(workspace_id),
8919 project_handle.clone(),
8920 app_state.clone(),
8921 window,
8922 cx,
8923 );
8924 workspace.centered_layout = centered_layout;
8925 workspace
8926 });
8927 multi_workspace.add_workspace(workspace.clone(), cx);
8928 workspace
8929 })?;
8930 (window, workspace)
8931 } else {
8932 let window_bounds_override = window_bounds_env_override();
8933
8934 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
8935 (Some(WindowBounds::Windowed(bounds)), None)
8936 } else if let Some(display) = serialized_workspace.display
8937 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
8938 {
8939 (Some(bounds.0), Some(display))
8940 } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
8941 (Some(bounds), Some(display))
8942 } else {
8943 (None, None)
8944 };
8945
8946 let options = cx.update(|cx| {
8947 let mut options = (app_state.build_window_options)(display, cx);
8948 options.window_bounds = window_bounds;
8949 options
8950 });
8951
8952 let window = cx.open_window(options, {
8953 let app_state = app_state.clone();
8954 let project_handle = project_handle.clone();
8955 move |window, cx| {
8956 let workspace = cx.new(|cx| {
8957 let mut workspace = Workspace::new(
8958 Some(workspace_id),
8959 project_handle,
8960 app_state,
8961 window,
8962 cx,
8963 );
8964 workspace.centered_layout = centered_layout;
8965 workspace
8966 });
8967 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
8968 }
8969 })?;
8970
8971 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
8972 multi_workspace.workspace().clone()
8973 })?;
8974
8975 (window, workspace)
8976 };
8977
8978 notify_if_database_failed(window, cx);
8979
8980 // Restore items from the serialized workspace
8981 window
8982 .update(cx, |_, window, cx| {
8983 workspace.update(cx, |_workspace, cx| {
8984 open_items(Some(serialized_workspace), vec![], window, cx)
8985 })
8986 })?
8987 .await?;
8988
8989 window.update(cx, |_, window, cx| {
8990 workspace.update(cx, |workspace, cx| {
8991 workspace.serialize_workspace(window, cx);
8992 });
8993 })?;
8994
8995 Ok(window)
8996 })
8997}
8998
8999#[allow(clippy::type_complexity)]
9000pub fn open_paths(
9001 abs_paths: &[PathBuf],
9002 app_state: Arc<AppState>,
9003 open_options: OpenOptions,
9004 cx: &mut App,
9005) -> Task<anyhow::Result<OpenResult>> {
9006 let abs_paths = abs_paths.to_vec();
9007 #[cfg(target_os = "windows")]
9008 let wsl_path = abs_paths
9009 .iter()
9010 .find_map(|p| util::paths::WslPath::from_path(p));
9011
9012 cx.spawn(async move |cx| {
9013 let (mut existing, mut open_visible) = find_existing_workspace(
9014 &abs_paths,
9015 &open_options,
9016 &SerializedWorkspaceLocation::Local,
9017 cx,
9018 )
9019 .await;
9020
9021 // Fallback: if no workspace contains the paths and all paths are files,
9022 // prefer an existing local workspace window (active window first).
9023 if open_options.open_new_workspace.is_none() && existing.is_none() {
9024 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9025 let all_metadatas = futures::future::join_all(all_paths)
9026 .await
9027 .into_iter()
9028 .filter_map(|result| result.ok().flatten())
9029 .collect::<Vec<_>>();
9030
9031 if all_metadatas.iter().all(|file| !file.is_dir) {
9032 cx.update(|cx| {
9033 let windows = workspace_windows_for_location(
9034 &SerializedWorkspaceLocation::Local,
9035 cx,
9036 );
9037 let window = cx
9038 .active_window()
9039 .and_then(|window| window.downcast::<MultiWorkspace>())
9040 .filter(|window| windows.contains(window))
9041 .or_else(|| windows.into_iter().next());
9042 if let Some(window) = window {
9043 if let Ok(multi_workspace) = window.read(cx) {
9044 let active_workspace = multi_workspace.workspace().clone();
9045 existing = Some((window, active_workspace));
9046 open_visible = OpenVisible::None;
9047 }
9048 }
9049 });
9050 }
9051 }
9052
9053 let result = if let Some((existing, target_workspace)) = existing {
9054 let open_task = existing
9055 .update(cx, |multi_workspace, window, cx| {
9056 window.activate_window();
9057 multi_workspace.activate(target_workspace.clone(), cx);
9058 target_workspace.update(cx, |workspace, cx| {
9059 workspace.open_paths(
9060 abs_paths,
9061 OpenOptions {
9062 visible: Some(open_visible),
9063 ..Default::default()
9064 },
9065 None,
9066 window,
9067 cx,
9068 )
9069 })
9070 })?
9071 .await;
9072
9073 _ = existing.update(cx, |multi_workspace, _, cx| {
9074 let workspace = multi_workspace.workspace().clone();
9075 workspace.update(cx, |workspace, cx| {
9076 for item in open_task.iter().flatten() {
9077 if let Err(e) = item {
9078 workspace.show_error(&e, cx);
9079 }
9080 }
9081 });
9082 });
9083
9084 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9085 } else {
9086 let result = cx
9087 .update(move |cx| {
9088 Workspace::new_local(
9089 abs_paths,
9090 app_state.clone(),
9091 open_options.replace_window,
9092 open_options.env,
9093 None,
9094 true,
9095 cx,
9096 )
9097 })
9098 .await;
9099
9100 if let Ok(ref result) = result {
9101 result.window
9102 .update(cx, |_, window, _cx| {
9103 window.activate_window();
9104 })
9105 .log_err();
9106 }
9107
9108 result
9109 };
9110
9111 #[cfg(target_os = "windows")]
9112 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9113 && let Ok(ref result) = result
9114 {
9115 result.window
9116 .update(cx, move |multi_workspace, _window, cx| {
9117 struct OpenInWsl;
9118 let workspace = multi_workspace.workspace().clone();
9119 workspace.update(cx, |workspace, cx| {
9120 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9121 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9122 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9123 cx.new(move |cx| {
9124 MessageNotification::new(msg, cx)
9125 .primary_message("Open in WSL")
9126 .primary_icon(IconName::FolderOpen)
9127 .primary_on_click(move |window, cx| {
9128 window.dispatch_action(Box::new(remote::OpenWslPath {
9129 distro: remote::WslConnectionOptions {
9130 distro_name: distro.clone(),
9131 user: None,
9132 },
9133 paths: vec![path.clone().into()],
9134 }), cx)
9135 })
9136 })
9137 });
9138 });
9139 })
9140 .unwrap();
9141 };
9142 result
9143 })
9144}
9145
9146pub fn open_new(
9147 open_options: OpenOptions,
9148 app_state: Arc<AppState>,
9149 cx: &mut App,
9150 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9151) -> Task<anyhow::Result<()>> {
9152 let task = Workspace::new_local(
9153 Vec::new(),
9154 app_state,
9155 open_options.replace_window,
9156 open_options.env,
9157 Some(Box::new(init)),
9158 true,
9159 cx,
9160 );
9161 cx.spawn(async move |cx| {
9162 let OpenResult { window, .. } = task.await?;
9163 window
9164 .update(cx, |_, window, _cx| {
9165 window.activate_window();
9166 })
9167 .ok();
9168 Ok(())
9169 })
9170}
9171
9172pub fn create_and_open_local_file(
9173 path: &'static Path,
9174 window: &mut Window,
9175 cx: &mut Context<Workspace>,
9176 default_content: impl 'static + Send + FnOnce() -> Rope,
9177) -> Task<Result<Box<dyn ItemHandle>>> {
9178 cx.spawn_in(window, async move |workspace, cx| {
9179 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9180 if !fs.is_file(path).await {
9181 fs.create_file(path, Default::default()).await?;
9182 fs.save(path, &default_content(), Default::default())
9183 .await?;
9184 }
9185
9186 workspace
9187 .update_in(cx, |workspace, window, cx| {
9188 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9189 let path = workspace
9190 .project
9191 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9192 cx.spawn_in(window, async move |workspace, cx| {
9193 let path = path.await?;
9194 let mut items = workspace
9195 .update_in(cx, |workspace, window, cx| {
9196 workspace.open_paths(
9197 vec![path.to_path_buf()],
9198 OpenOptions {
9199 visible: Some(OpenVisible::None),
9200 ..Default::default()
9201 },
9202 None,
9203 window,
9204 cx,
9205 )
9206 })?
9207 .await;
9208 let item = items.pop().flatten();
9209 item.with_context(|| format!("path {path:?} is not a file"))?
9210 })
9211 })
9212 })?
9213 .await?
9214 .await
9215 })
9216}
9217
9218pub fn open_remote_project_with_new_connection(
9219 window: WindowHandle<MultiWorkspace>,
9220 remote_connection: Arc<dyn RemoteConnection>,
9221 cancel_rx: oneshot::Receiver<()>,
9222 delegate: Arc<dyn RemoteClientDelegate>,
9223 app_state: Arc<AppState>,
9224 paths: Vec<PathBuf>,
9225 cx: &mut App,
9226) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9227 cx.spawn(async move |cx| {
9228 let (workspace_id, serialized_workspace) =
9229 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9230 .await?;
9231
9232 let session = match cx
9233 .update(|cx| {
9234 remote::RemoteClient::new(
9235 ConnectionIdentifier::Workspace(workspace_id.0),
9236 remote_connection,
9237 cancel_rx,
9238 delegate,
9239 cx,
9240 )
9241 })
9242 .await?
9243 {
9244 Some(result) => result,
9245 None => return Ok(Vec::new()),
9246 };
9247
9248 let project = cx.update(|cx| {
9249 project::Project::remote(
9250 session,
9251 app_state.client.clone(),
9252 app_state.node_runtime.clone(),
9253 app_state.user_store.clone(),
9254 app_state.languages.clone(),
9255 app_state.fs.clone(),
9256 true,
9257 cx,
9258 )
9259 });
9260
9261 open_remote_project_inner(
9262 project,
9263 paths,
9264 workspace_id,
9265 serialized_workspace,
9266 app_state,
9267 window,
9268 cx,
9269 )
9270 .await
9271 })
9272}
9273
9274pub fn open_remote_project_with_existing_connection(
9275 connection_options: RemoteConnectionOptions,
9276 project: Entity<Project>,
9277 paths: Vec<PathBuf>,
9278 app_state: Arc<AppState>,
9279 window: WindowHandle<MultiWorkspace>,
9280 cx: &mut AsyncApp,
9281) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9282 cx.spawn(async move |cx| {
9283 let (workspace_id, serialized_workspace) =
9284 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9285
9286 open_remote_project_inner(
9287 project,
9288 paths,
9289 workspace_id,
9290 serialized_workspace,
9291 app_state,
9292 window,
9293 cx,
9294 )
9295 .await
9296 })
9297}
9298
9299async fn open_remote_project_inner(
9300 project: Entity<Project>,
9301 paths: Vec<PathBuf>,
9302 workspace_id: WorkspaceId,
9303 serialized_workspace: Option<SerializedWorkspace>,
9304 app_state: Arc<AppState>,
9305 window: WindowHandle<MultiWorkspace>,
9306 cx: &mut AsyncApp,
9307) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9308 let db = cx.update(|cx| WorkspaceDb::global(cx));
9309 let toolchains = db.toolchains(workspace_id).await?;
9310 for (toolchain, worktree_path, path) in toolchains {
9311 project
9312 .update(cx, |this, cx| {
9313 let Some(worktree_id) =
9314 this.find_worktree(&worktree_path, cx)
9315 .and_then(|(worktree, rel_path)| {
9316 if rel_path.is_empty() {
9317 Some(worktree.read(cx).id())
9318 } else {
9319 None
9320 }
9321 })
9322 else {
9323 return Task::ready(None);
9324 };
9325
9326 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9327 })
9328 .await;
9329 }
9330 let mut project_paths_to_open = vec![];
9331 let mut project_path_errors = vec![];
9332
9333 for path in paths {
9334 let result = cx
9335 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9336 .await;
9337 match result {
9338 Ok((_, project_path)) => {
9339 project_paths_to_open.push((path.clone(), Some(project_path)));
9340 }
9341 Err(error) => {
9342 project_path_errors.push(error);
9343 }
9344 };
9345 }
9346
9347 if project_paths_to_open.is_empty() {
9348 return Err(project_path_errors.pop().context("no paths given")?);
9349 }
9350
9351 let workspace = window.update(cx, |multi_workspace, window, cx| {
9352 telemetry::event!("SSH Project Opened");
9353
9354 let new_workspace = cx.new(|cx| {
9355 let mut workspace =
9356 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9357 workspace.update_history(cx);
9358
9359 if let Some(ref serialized) = serialized_workspace {
9360 workspace.centered_layout = serialized.centered_layout;
9361 }
9362
9363 workspace
9364 });
9365
9366 multi_workspace.activate(new_workspace.clone(), cx);
9367 new_workspace
9368 })?;
9369
9370 let items = window
9371 .update(cx, |_, window, cx| {
9372 window.activate_window();
9373 workspace.update(cx, |_workspace, cx| {
9374 open_items(serialized_workspace, project_paths_to_open, window, cx)
9375 })
9376 })?
9377 .await?;
9378
9379 workspace.update(cx, |workspace, cx| {
9380 for error in project_path_errors {
9381 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9382 if let Some(path) = error.error_tag("path") {
9383 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9384 }
9385 } else {
9386 workspace.show_error(&error, cx)
9387 }
9388 }
9389 });
9390
9391 Ok(items.into_iter().map(|item| item?.ok()).collect())
9392}
9393
9394fn deserialize_remote_project(
9395 connection_options: RemoteConnectionOptions,
9396 paths: Vec<PathBuf>,
9397 cx: &AsyncApp,
9398) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9399 let db = cx.update(|cx| WorkspaceDb::global(cx));
9400 cx.background_spawn(async move {
9401 let remote_connection_id = db
9402 .get_or_create_remote_connection(connection_options)
9403 .await?;
9404
9405 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9406
9407 let workspace_id = if let Some(workspace_id) =
9408 serialized_workspace.as_ref().map(|workspace| workspace.id)
9409 {
9410 workspace_id
9411 } else {
9412 db.next_id().await?
9413 };
9414
9415 Ok((workspace_id, serialized_workspace))
9416 })
9417}
9418
9419pub fn join_in_room_project(
9420 project_id: u64,
9421 follow_user_id: u64,
9422 app_state: Arc<AppState>,
9423 cx: &mut App,
9424) -> Task<Result<()>> {
9425 let windows = cx.windows();
9426 cx.spawn(async move |cx| {
9427 let existing_window_and_workspace: Option<(
9428 WindowHandle<MultiWorkspace>,
9429 Entity<Workspace>,
9430 )> = windows.into_iter().find_map(|window_handle| {
9431 window_handle
9432 .downcast::<MultiWorkspace>()
9433 .and_then(|window_handle| {
9434 window_handle
9435 .update(cx, |multi_workspace, _window, cx| {
9436 for workspace in multi_workspace.workspaces() {
9437 if workspace.read(cx).project().read(cx).remote_id()
9438 == Some(project_id)
9439 {
9440 return Some((window_handle, workspace.clone()));
9441 }
9442 }
9443 None
9444 })
9445 .unwrap_or(None)
9446 })
9447 });
9448
9449 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9450 existing_window_and_workspace
9451 {
9452 existing_window
9453 .update(cx, |multi_workspace, _, cx| {
9454 multi_workspace.activate(target_workspace, cx);
9455 })
9456 .ok();
9457 existing_window
9458 } else {
9459 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9460 let project = cx
9461 .update(|cx| {
9462 active_call.0.join_project(
9463 project_id,
9464 app_state.languages.clone(),
9465 app_state.fs.clone(),
9466 cx,
9467 )
9468 })
9469 .await?;
9470
9471 let window_bounds_override = window_bounds_env_override();
9472 cx.update(|cx| {
9473 let mut options = (app_state.build_window_options)(None, cx);
9474 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9475 cx.open_window(options, |window, cx| {
9476 let workspace = cx.new(|cx| {
9477 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9478 });
9479 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9480 })
9481 })?
9482 };
9483
9484 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9485 cx.activate(true);
9486 window.activate_window();
9487
9488 // We set the active workspace above, so this is the correct workspace.
9489 let workspace = multi_workspace.workspace().clone();
9490 workspace.update(cx, |workspace, cx| {
9491 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9492 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9493 .or_else(|| {
9494 // If we couldn't follow the given user, follow the host instead.
9495 let collaborator = workspace
9496 .project()
9497 .read(cx)
9498 .collaborators()
9499 .values()
9500 .find(|collaborator| collaborator.is_host)?;
9501 Some(collaborator.peer_id)
9502 });
9503
9504 if let Some(follow_peer_id) = follow_peer_id {
9505 workspace.follow(follow_peer_id, window, cx);
9506 }
9507 });
9508 })?;
9509
9510 anyhow::Ok(())
9511 })
9512}
9513
9514pub fn reload(cx: &mut App) {
9515 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9516 let mut workspace_windows = cx
9517 .windows()
9518 .into_iter()
9519 .filter_map(|window| window.downcast::<MultiWorkspace>())
9520 .collect::<Vec<_>>();
9521
9522 // If multiple windows have unsaved changes, and need a save prompt,
9523 // prompt in the active window before switching to a different window.
9524 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9525
9526 let mut prompt = None;
9527 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9528 prompt = window
9529 .update(cx, |_, window, cx| {
9530 window.prompt(
9531 PromptLevel::Info,
9532 "Are you sure you want to restart?",
9533 None,
9534 &["Restart", "Cancel"],
9535 cx,
9536 )
9537 })
9538 .ok();
9539 }
9540
9541 cx.spawn(async move |cx| {
9542 if let Some(prompt) = prompt {
9543 let answer = prompt.await?;
9544 if answer != 0 {
9545 return anyhow::Ok(());
9546 }
9547 }
9548
9549 // If the user cancels any save prompt, then keep the app open.
9550 for window in workspace_windows {
9551 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9552 let workspace = multi_workspace.workspace().clone();
9553 workspace.update(cx, |workspace, cx| {
9554 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9555 })
9556 }) && !should_close.await?
9557 {
9558 return anyhow::Ok(());
9559 }
9560 }
9561 cx.update(|cx| cx.restart());
9562 anyhow::Ok(())
9563 })
9564 .detach_and_log_err(cx);
9565}
9566
9567fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9568 let mut parts = value.split(',');
9569 let x: usize = parts.next()?.parse().ok()?;
9570 let y: usize = parts.next()?.parse().ok()?;
9571 Some(point(px(x as f32), px(y as f32)))
9572}
9573
9574fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9575 let mut parts = value.split(',');
9576 let width: usize = parts.next()?.parse().ok()?;
9577 let height: usize = parts.next()?.parse().ok()?;
9578 Some(size(px(width as f32), px(height as f32)))
9579}
9580
9581/// Add client-side decorations (rounded corners, shadows, resize handling) when
9582/// appropriate.
9583///
9584/// The `border_radius_tiling` parameter allows overriding which corners get
9585/// rounded, independently of the actual window tiling state. This is used
9586/// specifically for the workspace switcher sidebar: when the sidebar is open,
9587/// we want square corners on the left (so the sidebar appears flush with the
9588/// window edge) but we still need the shadow padding for proper visual
9589/// appearance. Unlike actual window tiling, this only affects border radius -
9590/// not padding or shadows.
9591pub fn client_side_decorations(
9592 element: impl IntoElement,
9593 window: &mut Window,
9594 cx: &mut App,
9595 border_radius_tiling: Tiling,
9596) -> Stateful<Div> {
9597 const BORDER_SIZE: Pixels = px(1.0);
9598 let decorations = window.window_decorations();
9599 let tiling = match decorations {
9600 Decorations::Server => Tiling::default(),
9601 Decorations::Client { tiling } => tiling,
9602 };
9603
9604 match decorations {
9605 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9606 Decorations::Server => window.set_client_inset(px(0.0)),
9607 }
9608
9609 struct GlobalResizeEdge(ResizeEdge);
9610 impl Global for GlobalResizeEdge {}
9611
9612 div()
9613 .id("window-backdrop")
9614 .bg(transparent_black())
9615 .map(|div| match decorations {
9616 Decorations::Server => div,
9617 Decorations::Client { .. } => div
9618 .when(
9619 !(tiling.top
9620 || tiling.right
9621 || border_radius_tiling.top
9622 || border_radius_tiling.right),
9623 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9624 )
9625 .when(
9626 !(tiling.top
9627 || tiling.left
9628 || border_radius_tiling.top
9629 || border_radius_tiling.left),
9630 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9631 )
9632 .when(
9633 !(tiling.bottom
9634 || tiling.right
9635 || border_radius_tiling.bottom
9636 || border_radius_tiling.right),
9637 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9638 )
9639 .when(
9640 !(tiling.bottom
9641 || tiling.left
9642 || border_radius_tiling.bottom
9643 || border_radius_tiling.left),
9644 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9645 )
9646 .when(!tiling.top, |div| {
9647 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9648 })
9649 .when(!tiling.bottom, |div| {
9650 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9651 })
9652 .when(!tiling.left, |div| {
9653 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9654 })
9655 .when(!tiling.right, |div| {
9656 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9657 })
9658 .on_mouse_move(move |e, window, cx| {
9659 let size = window.window_bounds().get_bounds().size;
9660 let pos = e.position;
9661
9662 let new_edge =
9663 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9664
9665 let edge = cx.try_global::<GlobalResizeEdge>();
9666 if new_edge != edge.map(|edge| edge.0) {
9667 window
9668 .window_handle()
9669 .update(cx, |workspace, _, cx| {
9670 cx.notify(workspace.entity_id());
9671 })
9672 .ok();
9673 }
9674 })
9675 .on_mouse_down(MouseButton::Left, move |e, window, _| {
9676 let size = window.window_bounds().get_bounds().size;
9677 let pos = e.position;
9678
9679 let edge = match resize_edge(
9680 pos,
9681 theme::CLIENT_SIDE_DECORATION_SHADOW,
9682 size,
9683 tiling,
9684 ) {
9685 Some(value) => value,
9686 None => return,
9687 };
9688
9689 window.start_window_resize(edge);
9690 }),
9691 })
9692 .size_full()
9693 .child(
9694 div()
9695 .cursor(CursorStyle::Arrow)
9696 .map(|div| match decorations {
9697 Decorations::Server => div,
9698 Decorations::Client { .. } => div
9699 .border_color(cx.theme().colors().border)
9700 .when(
9701 !(tiling.top
9702 || tiling.right
9703 || border_radius_tiling.top
9704 || border_radius_tiling.right),
9705 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9706 )
9707 .when(
9708 !(tiling.top
9709 || tiling.left
9710 || border_radius_tiling.top
9711 || border_radius_tiling.left),
9712 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9713 )
9714 .when(
9715 !(tiling.bottom
9716 || tiling.right
9717 || border_radius_tiling.bottom
9718 || border_radius_tiling.right),
9719 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9720 )
9721 .when(
9722 !(tiling.bottom
9723 || tiling.left
9724 || border_radius_tiling.bottom
9725 || border_radius_tiling.left),
9726 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9727 )
9728 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
9729 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
9730 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
9731 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
9732 .when(!tiling.is_tiled(), |div| {
9733 div.shadow(vec![gpui::BoxShadow {
9734 color: Hsla {
9735 h: 0.,
9736 s: 0.,
9737 l: 0.,
9738 a: 0.4,
9739 },
9740 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
9741 spread_radius: px(0.),
9742 offset: point(px(0.0), px(0.0)),
9743 }])
9744 }),
9745 })
9746 .on_mouse_move(|_e, _, cx| {
9747 cx.stop_propagation();
9748 })
9749 .size_full()
9750 .child(element),
9751 )
9752 .map(|div| match decorations {
9753 Decorations::Server => div,
9754 Decorations::Client { tiling, .. } => div.child(
9755 canvas(
9756 |_bounds, window, _| {
9757 window.insert_hitbox(
9758 Bounds::new(
9759 point(px(0.0), px(0.0)),
9760 window.window_bounds().get_bounds().size,
9761 ),
9762 HitboxBehavior::Normal,
9763 )
9764 },
9765 move |_bounds, hitbox, window, cx| {
9766 let mouse = window.mouse_position();
9767 let size = window.window_bounds().get_bounds().size;
9768 let Some(edge) =
9769 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
9770 else {
9771 return;
9772 };
9773 cx.set_global(GlobalResizeEdge(edge));
9774 window.set_cursor_style(
9775 match edge {
9776 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
9777 ResizeEdge::Left | ResizeEdge::Right => {
9778 CursorStyle::ResizeLeftRight
9779 }
9780 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
9781 CursorStyle::ResizeUpLeftDownRight
9782 }
9783 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
9784 CursorStyle::ResizeUpRightDownLeft
9785 }
9786 },
9787 &hitbox,
9788 );
9789 },
9790 )
9791 .size_full()
9792 .absolute(),
9793 ),
9794 })
9795}
9796
9797fn resize_edge(
9798 pos: Point<Pixels>,
9799 shadow_size: Pixels,
9800 window_size: Size<Pixels>,
9801 tiling: Tiling,
9802) -> Option<ResizeEdge> {
9803 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
9804 if bounds.contains(&pos) {
9805 return None;
9806 }
9807
9808 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
9809 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
9810 if !tiling.top && top_left_bounds.contains(&pos) {
9811 return Some(ResizeEdge::TopLeft);
9812 }
9813
9814 let top_right_bounds = Bounds::new(
9815 Point::new(window_size.width - corner_size.width, px(0.)),
9816 corner_size,
9817 );
9818 if !tiling.top && top_right_bounds.contains(&pos) {
9819 return Some(ResizeEdge::TopRight);
9820 }
9821
9822 let bottom_left_bounds = Bounds::new(
9823 Point::new(px(0.), window_size.height - corner_size.height),
9824 corner_size,
9825 );
9826 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
9827 return Some(ResizeEdge::BottomLeft);
9828 }
9829
9830 let bottom_right_bounds = Bounds::new(
9831 Point::new(
9832 window_size.width - corner_size.width,
9833 window_size.height - corner_size.height,
9834 ),
9835 corner_size,
9836 );
9837 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
9838 return Some(ResizeEdge::BottomRight);
9839 }
9840
9841 if !tiling.top && pos.y < shadow_size {
9842 Some(ResizeEdge::Top)
9843 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
9844 Some(ResizeEdge::Bottom)
9845 } else if !tiling.left && pos.x < shadow_size {
9846 Some(ResizeEdge::Left)
9847 } else if !tiling.right && pos.x > window_size.width - shadow_size {
9848 Some(ResizeEdge::Right)
9849 } else {
9850 None
9851 }
9852}
9853
9854fn join_pane_into_active(
9855 active_pane: &Entity<Pane>,
9856 pane: &Entity<Pane>,
9857 window: &mut Window,
9858 cx: &mut App,
9859) {
9860 if pane == active_pane {
9861 } else if pane.read(cx).items_len() == 0 {
9862 pane.update(cx, |_, cx| {
9863 cx.emit(pane::Event::Remove {
9864 focus_on_pane: None,
9865 });
9866 })
9867 } else {
9868 move_all_items(pane, active_pane, window, cx);
9869 }
9870}
9871
9872fn move_all_items(
9873 from_pane: &Entity<Pane>,
9874 to_pane: &Entity<Pane>,
9875 window: &mut Window,
9876 cx: &mut App,
9877) {
9878 let destination_is_different = from_pane != to_pane;
9879 let mut moved_items = 0;
9880 for (item_ix, item_handle) in from_pane
9881 .read(cx)
9882 .items()
9883 .enumerate()
9884 .map(|(ix, item)| (ix, item.clone()))
9885 .collect::<Vec<_>>()
9886 {
9887 let ix = item_ix - moved_items;
9888 if destination_is_different {
9889 // Close item from previous pane
9890 from_pane.update(cx, |source, cx| {
9891 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
9892 });
9893 moved_items += 1;
9894 }
9895
9896 // This automatically removes duplicate items in the pane
9897 to_pane.update(cx, |destination, cx| {
9898 destination.add_item(item_handle, true, true, None, window, cx);
9899 window.focus(&destination.focus_handle(cx), cx)
9900 });
9901 }
9902}
9903
9904pub fn move_item(
9905 source: &Entity<Pane>,
9906 destination: &Entity<Pane>,
9907 item_id_to_move: EntityId,
9908 destination_index: usize,
9909 activate: bool,
9910 window: &mut Window,
9911 cx: &mut App,
9912) {
9913 let Some((item_ix, item_handle)) = source
9914 .read(cx)
9915 .items()
9916 .enumerate()
9917 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
9918 .map(|(ix, item)| (ix, item.clone()))
9919 else {
9920 // Tab was closed during drag
9921 return;
9922 };
9923
9924 if source != destination {
9925 // Close item from previous pane
9926 source.update(cx, |source, cx| {
9927 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
9928 });
9929 }
9930
9931 // This automatically removes duplicate items in the pane
9932 destination.update(cx, |destination, cx| {
9933 destination.add_item_inner(
9934 item_handle,
9935 activate,
9936 activate,
9937 activate,
9938 Some(destination_index),
9939 window,
9940 cx,
9941 );
9942 if activate {
9943 window.focus(&destination.focus_handle(cx), cx)
9944 }
9945 });
9946}
9947
9948pub fn move_active_item(
9949 source: &Entity<Pane>,
9950 destination: &Entity<Pane>,
9951 focus_destination: bool,
9952 close_if_empty: bool,
9953 window: &mut Window,
9954 cx: &mut App,
9955) {
9956 if source == destination {
9957 return;
9958 }
9959 let Some(active_item) = source.read(cx).active_item() else {
9960 return;
9961 };
9962 source.update(cx, |source_pane, cx| {
9963 let item_id = active_item.item_id();
9964 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
9965 destination.update(cx, |target_pane, cx| {
9966 target_pane.add_item(
9967 active_item,
9968 focus_destination,
9969 focus_destination,
9970 Some(target_pane.items_len()),
9971 window,
9972 cx,
9973 );
9974 });
9975 });
9976}
9977
9978pub fn clone_active_item(
9979 workspace_id: Option<WorkspaceId>,
9980 source: &Entity<Pane>,
9981 destination: &Entity<Pane>,
9982 focus_destination: bool,
9983 window: &mut Window,
9984 cx: &mut App,
9985) {
9986 if source == destination {
9987 return;
9988 }
9989 let Some(active_item) = source.read(cx).active_item() else {
9990 return;
9991 };
9992 if !active_item.can_split(cx) {
9993 return;
9994 }
9995 let destination = destination.downgrade();
9996 let task = active_item.clone_on_split(workspace_id, window, cx);
9997 window
9998 .spawn(cx, async move |cx| {
9999 let Some(clone) = task.await else {
10000 return;
10001 };
10002 destination
10003 .update_in(cx, |target_pane, window, cx| {
10004 target_pane.add_item(
10005 clone,
10006 focus_destination,
10007 focus_destination,
10008 Some(target_pane.items_len()),
10009 window,
10010 cx,
10011 );
10012 })
10013 .log_err();
10014 })
10015 .detach();
10016}
10017
10018#[derive(Debug)]
10019pub struct WorkspacePosition {
10020 pub window_bounds: Option<WindowBounds>,
10021 pub display: Option<Uuid>,
10022 pub centered_layout: bool,
10023}
10024
10025pub fn remote_workspace_position_from_db(
10026 connection_options: RemoteConnectionOptions,
10027 paths_to_open: &[PathBuf],
10028 cx: &App,
10029) -> Task<Result<WorkspacePosition>> {
10030 let paths = paths_to_open.to_vec();
10031 let db = WorkspaceDb::global(cx);
10032 let kvp = db::kvp::KeyValueStore::global(cx);
10033
10034 cx.background_spawn(async move {
10035 let remote_connection_id = db
10036 .get_or_create_remote_connection(connection_options)
10037 .await
10038 .context("fetching serialized ssh project")?;
10039 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10040
10041 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10042 (Some(WindowBounds::Windowed(bounds)), None)
10043 } else {
10044 let restorable_bounds = serialized_workspace
10045 .as_ref()
10046 .and_then(|workspace| {
10047 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10048 })
10049 .or_else(|| persistence::read_default_window_bounds(&kvp));
10050
10051 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10052 (Some(serialized_bounds), Some(serialized_display))
10053 } else {
10054 (None, None)
10055 }
10056 };
10057
10058 let centered_layout = serialized_workspace
10059 .as_ref()
10060 .map(|w| w.centered_layout)
10061 .unwrap_or(false);
10062
10063 Ok(WorkspacePosition {
10064 window_bounds,
10065 display,
10066 centered_layout,
10067 })
10068 })
10069}
10070
10071pub fn with_active_or_new_workspace(
10072 cx: &mut App,
10073 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10074) {
10075 match cx
10076 .active_window()
10077 .and_then(|w| w.downcast::<MultiWorkspace>())
10078 {
10079 Some(multi_workspace) => {
10080 cx.defer(move |cx| {
10081 multi_workspace
10082 .update(cx, |multi_workspace, window, cx| {
10083 let workspace = multi_workspace.workspace().clone();
10084 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10085 })
10086 .log_err();
10087 });
10088 }
10089 None => {
10090 let app_state = AppState::global(cx);
10091 if let Some(app_state) = app_state.upgrade() {
10092 open_new(
10093 OpenOptions::default(),
10094 app_state,
10095 cx,
10096 move |workspace, window, cx| f(workspace, window, cx),
10097 )
10098 .detach_and_log_err(cx);
10099 }
10100 }
10101 }
10102}
10103
10104#[cfg(test)]
10105mod tests {
10106 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10107
10108 use super::*;
10109 use crate::{
10110 dock::{PanelEvent, test::TestPanel},
10111 item::{
10112 ItemBufferKind, ItemEvent,
10113 test::{TestItem, TestProjectItem},
10114 },
10115 };
10116 use fs::FakeFs;
10117 use gpui::{
10118 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10119 UpdateGlobal, VisualTestContext, px,
10120 };
10121 use project::{Project, ProjectEntryId};
10122 use serde_json::json;
10123 use settings::SettingsStore;
10124 use util::path;
10125 use util::rel_path::rel_path;
10126
10127 #[gpui::test]
10128 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10129 init_test(cx);
10130
10131 let fs = FakeFs::new(cx.executor());
10132 let project = Project::test(fs, [], cx).await;
10133 let (workspace, cx) =
10134 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10135
10136 // Adding an item with no ambiguity renders the tab without detail.
10137 let item1 = cx.new(|cx| {
10138 let mut item = TestItem::new(cx);
10139 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10140 item
10141 });
10142 workspace.update_in(cx, |workspace, window, cx| {
10143 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10144 });
10145 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10146
10147 // Adding an item that creates ambiguity increases the level of detail on
10148 // both tabs.
10149 let item2 = cx.new_window_entity(|_window, cx| {
10150 let mut item = TestItem::new(cx);
10151 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10152 item
10153 });
10154 workspace.update_in(cx, |workspace, window, cx| {
10155 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10156 });
10157 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10158 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10159
10160 // Adding an item that creates ambiguity increases the level of detail only
10161 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10162 // we stop at the highest detail available.
10163 let item3 = cx.new(|cx| {
10164 let mut item = TestItem::new(cx);
10165 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10166 item
10167 });
10168 workspace.update_in(cx, |workspace, window, cx| {
10169 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10170 });
10171 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10172 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10173 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10174 }
10175
10176 #[gpui::test]
10177 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10178 init_test(cx);
10179
10180 let fs = FakeFs::new(cx.executor());
10181 fs.insert_tree(
10182 "/root1",
10183 json!({
10184 "one.txt": "",
10185 "two.txt": "",
10186 }),
10187 )
10188 .await;
10189 fs.insert_tree(
10190 "/root2",
10191 json!({
10192 "three.txt": "",
10193 }),
10194 )
10195 .await;
10196
10197 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10198 let (workspace, cx) =
10199 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10200 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10201 let worktree_id = project.update(cx, |project, cx| {
10202 project.worktrees(cx).next().unwrap().read(cx).id()
10203 });
10204
10205 let item1 = cx.new(|cx| {
10206 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10207 });
10208 let item2 = cx.new(|cx| {
10209 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10210 });
10211
10212 // Add an item to an empty pane
10213 workspace.update_in(cx, |workspace, window, cx| {
10214 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10215 });
10216 project.update(cx, |project, cx| {
10217 assert_eq!(
10218 project.active_entry(),
10219 project
10220 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10221 .map(|e| e.id)
10222 );
10223 });
10224 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10225
10226 // Add a second item to a non-empty pane
10227 workspace.update_in(cx, |workspace, window, cx| {
10228 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10229 });
10230 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10231 project.update(cx, |project, cx| {
10232 assert_eq!(
10233 project.active_entry(),
10234 project
10235 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10236 .map(|e| e.id)
10237 );
10238 });
10239
10240 // Close the active item
10241 pane.update_in(cx, |pane, window, cx| {
10242 pane.close_active_item(&Default::default(), window, cx)
10243 })
10244 .await
10245 .unwrap();
10246 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10247 project.update(cx, |project, cx| {
10248 assert_eq!(
10249 project.active_entry(),
10250 project
10251 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10252 .map(|e| e.id)
10253 );
10254 });
10255
10256 // Add a project folder
10257 project
10258 .update(cx, |project, cx| {
10259 project.find_or_create_worktree("root2", true, cx)
10260 })
10261 .await
10262 .unwrap();
10263 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10264
10265 // Remove a project folder
10266 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10267 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10268 }
10269
10270 #[gpui::test]
10271 async fn test_close_window(cx: &mut TestAppContext) {
10272 init_test(cx);
10273
10274 let fs = FakeFs::new(cx.executor());
10275 fs.insert_tree("/root", json!({ "one": "" })).await;
10276
10277 let project = Project::test(fs, ["root".as_ref()], cx).await;
10278 let (workspace, cx) =
10279 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10280
10281 // When there are no dirty items, there's nothing to do.
10282 let item1 = cx.new(TestItem::new);
10283 workspace.update_in(cx, |w, window, cx| {
10284 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10285 });
10286 let task = workspace.update_in(cx, |w, window, cx| {
10287 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10288 });
10289 assert!(task.await.unwrap());
10290
10291 // When there are dirty untitled items, prompt to save each one. If the user
10292 // cancels any prompt, then abort.
10293 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10294 let item3 = cx.new(|cx| {
10295 TestItem::new(cx)
10296 .with_dirty(true)
10297 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10298 });
10299 workspace.update_in(cx, |w, window, cx| {
10300 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10301 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10302 });
10303 let task = workspace.update_in(cx, |w, window, cx| {
10304 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10305 });
10306 cx.executor().run_until_parked();
10307 cx.simulate_prompt_answer("Cancel"); // cancel save all
10308 cx.executor().run_until_parked();
10309 assert!(!cx.has_pending_prompt());
10310 assert!(!task.await.unwrap());
10311 }
10312
10313 #[gpui::test]
10314 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10315 init_test(cx);
10316
10317 let fs = FakeFs::new(cx.executor());
10318 fs.insert_tree("/root", json!({ "one": "" })).await;
10319
10320 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10321 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10322 let multi_workspace_handle =
10323 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10324 cx.run_until_parked();
10325
10326 let workspace_a = multi_workspace_handle
10327 .read_with(cx, |mw, _| mw.workspace().clone())
10328 .unwrap();
10329
10330 let workspace_b = multi_workspace_handle
10331 .update(cx, |mw, window, cx| {
10332 mw.test_add_workspace(project_b, window, cx)
10333 })
10334 .unwrap();
10335
10336 // Activate workspace A
10337 multi_workspace_handle
10338 .update(cx, |mw, window, cx| {
10339 mw.activate_index(0, window, cx);
10340 })
10341 .unwrap();
10342
10343 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10344
10345 // Workspace A has a clean item
10346 let item_a = cx.new(TestItem::new);
10347 workspace_a.update_in(cx, |w, window, cx| {
10348 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10349 });
10350
10351 // Workspace B has a dirty item
10352 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10353 workspace_b.update_in(cx, |w, window, cx| {
10354 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10355 });
10356
10357 // Verify workspace A is active
10358 multi_workspace_handle
10359 .read_with(cx, |mw, _| {
10360 assert_eq!(mw.active_workspace_index(), 0);
10361 })
10362 .unwrap();
10363
10364 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10365 multi_workspace_handle
10366 .update(cx, |mw, window, cx| {
10367 mw.close_window(&CloseWindow, window, cx);
10368 })
10369 .unwrap();
10370 cx.run_until_parked();
10371
10372 // Workspace B should now be active since it has dirty items that need attention
10373 multi_workspace_handle
10374 .read_with(cx, |mw, _| {
10375 assert_eq!(
10376 mw.active_workspace_index(),
10377 1,
10378 "workspace B should be activated when it prompts"
10379 );
10380 })
10381 .unwrap();
10382
10383 // User cancels the save prompt from workspace B
10384 cx.simulate_prompt_answer("Cancel");
10385 cx.run_until_parked();
10386
10387 // Window should still exist because workspace B's close was cancelled
10388 assert!(
10389 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10390 "window should still exist after cancelling one workspace's close"
10391 );
10392 }
10393
10394 #[gpui::test]
10395 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10396 init_test(cx);
10397
10398 // Register TestItem as a serializable item
10399 cx.update(|cx| {
10400 register_serializable_item::<TestItem>(cx);
10401 });
10402
10403 let fs = FakeFs::new(cx.executor());
10404 fs.insert_tree("/root", json!({ "one": "" })).await;
10405
10406 let project = Project::test(fs, ["root".as_ref()], cx).await;
10407 let (workspace, cx) =
10408 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10409
10410 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10411 let item1 = cx.new(|cx| {
10412 TestItem::new(cx)
10413 .with_dirty(true)
10414 .with_serialize(|| Some(Task::ready(Ok(()))))
10415 });
10416 let item2 = cx.new(|cx| {
10417 TestItem::new(cx)
10418 .with_dirty(true)
10419 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10420 .with_serialize(|| Some(Task::ready(Ok(()))))
10421 });
10422 workspace.update_in(cx, |w, window, cx| {
10423 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10424 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10425 });
10426 let task = workspace.update_in(cx, |w, window, cx| {
10427 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10428 });
10429 assert!(task.await.unwrap());
10430 }
10431
10432 #[gpui::test]
10433 async fn test_close_pane_items(cx: &mut TestAppContext) {
10434 init_test(cx);
10435
10436 let fs = FakeFs::new(cx.executor());
10437
10438 let project = Project::test(fs, None, cx).await;
10439 let (workspace, cx) =
10440 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10441
10442 let item1 = cx.new(|cx| {
10443 TestItem::new(cx)
10444 .with_dirty(true)
10445 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10446 });
10447 let item2 = cx.new(|cx| {
10448 TestItem::new(cx)
10449 .with_dirty(true)
10450 .with_conflict(true)
10451 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10452 });
10453 let item3 = cx.new(|cx| {
10454 TestItem::new(cx)
10455 .with_dirty(true)
10456 .with_conflict(true)
10457 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10458 });
10459 let item4 = cx.new(|cx| {
10460 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10461 let project_item = TestProjectItem::new_untitled(cx);
10462 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10463 project_item
10464 }])
10465 });
10466 let pane = workspace.update_in(cx, |workspace, window, cx| {
10467 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10468 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10469 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10470 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10471 workspace.active_pane().clone()
10472 });
10473
10474 let close_items = pane.update_in(cx, |pane, window, cx| {
10475 pane.activate_item(1, true, true, window, cx);
10476 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10477 let item1_id = item1.item_id();
10478 let item3_id = item3.item_id();
10479 let item4_id = item4.item_id();
10480 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10481 [item1_id, item3_id, item4_id].contains(&id)
10482 })
10483 });
10484 cx.executor().run_until_parked();
10485
10486 assert!(cx.has_pending_prompt());
10487 cx.simulate_prompt_answer("Save all");
10488
10489 cx.executor().run_until_parked();
10490
10491 // Item 1 is saved. There's a prompt to save item 3.
10492 pane.update(cx, |pane, cx| {
10493 assert_eq!(item1.read(cx).save_count, 1);
10494 assert_eq!(item1.read(cx).save_as_count, 0);
10495 assert_eq!(item1.read(cx).reload_count, 0);
10496 assert_eq!(pane.items_len(), 3);
10497 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10498 });
10499 assert!(cx.has_pending_prompt());
10500
10501 // Cancel saving item 3.
10502 cx.simulate_prompt_answer("Discard");
10503 cx.executor().run_until_parked();
10504
10505 // Item 3 is reloaded. There's a prompt to save item 4.
10506 pane.update(cx, |pane, cx| {
10507 assert_eq!(item3.read(cx).save_count, 0);
10508 assert_eq!(item3.read(cx).save_as_count, 0);
10509 assert_eq!(item3.read(cx).reload_count, 1);
10510 assert_eq!(pane.items_len(), 2);
10511 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10512 });
10513
10514 // There's a prompt for a path for item 4.
10515 cx.simulate_new_path_selection(|_| Some(Default::default()));
10516 close_items.await.unwrap();
10517
10518 // The requested items are closed.
10519 pane.update(cx, |pane, cx| {
10520 assert_eq!(item4.read(cx).save_count, 0);
10521 assert_eq!(item4.read(cx).save_as_count, 1);
10522 assert_eq!(item4.read(cx).reload_count, 0);
10523 assert_eq!(pane.items_len(), 1);
10524 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10525 });
10526 }
10527
10528 #[gpui::test]
10529 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10530 init_test(cx);
10531
10532 let fs = FakeFs::new(cx.executor());
10533 let project = Project::test(fs, [], cx).await;
10534 let (workspace, cx) =
10535 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10536
10537 // Create several workspace items with single project entries, and two
10538 // workspace items with multiple project entries.
10539 let single_entry_items = (0..=4)
10540 .map(|project_entry_id| {
10541 cx.new(|cx| {
10542 TestItem::new(cx)
10543 .with_dirty(true)
10544 .with_project_items(&[dirty_project_item(
10545 project_entry_id,
10546 &format!("{project_entry_id}.txt"),
10547 cx,
10548 )])
10549 })
10550 })
10551 .collect::<Vec<_>>();
10552 let item_2_3 = cx.new(|cx| {
10553 TestItem::new(cx)
10554 .with_dirty(true)
10555 .with_buffer_kind(ItemBufferKind::Multibuffer)
10556 .with_project_items(&[
10557 single_entry_items[2].read(cx).project_items[0].clone(),
10558 single_entry_items[3].read(cx).project_items[0].clone(),
10559 ])
10560 });
10561 let item_3_4 = cx.new(|cx| {
10562 TestItem::new(cx)
10563 .with_dirty(true)
10564 .with_buffer_kind(ItemBufferKind::Multibuffer)
10565 .with_project_items(&[
10566 single_entry_items[3].read(cx).project_items[0].clone(),
10567 single_entry_items[4].read(cx).project_items[0].clone(),
10568 ])
10569 });
10570
10571 // Create two panes that contain the following project entries:
10572 // left pane:
10573 // multi-entry items: (2, 3)
10574 // single-entry items: 0, 2, 3, 4
10575 // right pane:
10576 // single-entry items: 4, 1
10577 // multi-entry items: (3, 4)
10578 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10579 let left_pane = workspace.active_pane().clone();
10580 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10581 workspace.add_item_to_active_pane(
10582 single_entry_items[0].boxed_clone(),
10583 None,
10584 true,
10585 window,
10586 cx,
10587 );
10588 workspace.add_item_to_active_pane(
10589 single_entry_items[2].boxed_clone(),
10590 None,
10591 true,
10592 window,
10593 cx,
10594 );
10595 workspace.add_item_to_active_pane(
10596 single_entry_items[3].boxed_clone(),
10597 None,
10598 true,
10599 window,
10600 cx,
10601 );
10602 workspace.add_item_to_active_pane(
10603 single_entry_items[4].boxed_clone(),
10604 None,
10605 true,
10606 window,
10607 cx,
10608 );
10609
10610 let right_pane =
10611 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10612
10613 let boxed_clone = single_entry_items[1].boxed_clone();
10614 let right_pane = window.spawn(cx, async move |cx| {
10615 right_pane.await.inspect(|right_pane| {
10616 right_pane
10617 .update_in(cx, |pane, window, cx| {
10618 pane.add_item(boxed_clone, true, true, None, window, cx);
10619 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10620 })
10621 .unwrap();
10622 })
10623 });
10624
10625 (left_pane, right_pane)
10626 });
10627 let right_pane = right_pane.await.unwrap();
10628 cx.focus(&right_pane);
10629
10630 let close = right_pane.update_in(cx, |pane, window, cx| {
10631 pane.close_all_items(&CloseAllItems::default(), window, cx)
10632 .unwrap()
10633 });
10634 cx.executor().run_until_parked();
10635
10636 let msg = cx.pending_prompt().unwrap().0;
10637 assert!(msg.contains("1.txt"));
10638 assert!(!msg.contains("2.txt"));
10639 assert!(!msg.contains("3.txt"));
10640 assert!(!msg.contains("4.txt"));
10641
10642 // With best-effort close, cancelling item 1 keeps it open but items 4
10643 // and (3,4) still close since their entries exist in left pane.
10644 cx.simulate_prompt_answer("Cancel");
10645 close.await;
10646
10647 right_pane.read_with(cx, |pane, _| {
10648 assert_eq!(pane.items_len(), 1);
10649 });
10650
10651 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10652 left_pane
10653 .update_in(cx, |left_pane, window, cx| {
10654 left_pane.close_item_by_id(
10655 single_entry_items[3].entity_id(),
10656 SaveIntent::Skip,
10657 window,
10658 cx,
10659 )
10660 })
10661 .await
10662 .unwrap();
10663
10664 let close = left_pane.update_in(cx, |pane, window, cx| {
10665 pane.close_all_items(&CloseAllItems::default(), window, cx)
10666 .unwrap()
10667 });
10668 cx.executor().run_until_parked();
10669
10670 let details = cx.pending_prompt().unwrap().1;
10671 assert!(details.contains("0.txt"));
10672 assert!(details.contains("3.txt"));
10673 assert!(details.contains("4.txt"));
10674 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10675 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10676 // assert!(!details.contains("2.txt"));
10677
10678 cx.simulate_prompt_answer("Save all");
10679 cx.executor().run_until_parked();
10680 close.await;
10681
10682 left_pane.read_with(cx, |pane, _| {
10683 assert_eq!(pane.items_len(), 0);
10684 });
10685 }
10686
10687 #[gpui::test]
10688 async fn test_autosave(cx: &mut gpui::TestAppContext) {
10689 init_test(cx);
10690
10691 let fs = FakeFs::new(cx.executor());
10692 let project = Project::test(fs, [], cx).await;
10693 let (workspace, cx) =
10694 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10695 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10696
10697 let item = cx.new(|cx| {
10698 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10699 });
10700 let item_id = item.entity_id();
10701 workspace.update_in(cx, |workspace, window, cx| {
10702 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10703 });
10704
10705 // Autosave on window change.
10706 item.update(cx, |item, cx| {
10707 SettingsStore::update_global(cx, |settings, cx| {
10708 settings.update_user_settings(cx, |settings| {
10709 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10710 })
10711 });
10712 item.is_dirty = true;
10713 });
10714
10715 // Deactivating the window saves the file.
10716 cx.deactivate_window();
10717 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10718
10719 // Re-activating the window doesn't save the file.
10720 cx.update(|window, _| window.activate_window());
10721 cx.executor().run_until_parked();
10722 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10723
10724 // Autosave on focus change.
10725 item.update_in(cx, |item, window, cx| {
10726 cx.focus_self(window);
10727 SettingsStore::update_global(cx, |settings, cx| {
10728 settings.update_user_settings(cx, |settings| {
10729 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10730 })
10731 });
10732 item.is_dirty = true;
10733 });
10734 // Blurring the item saves the file.
10735 item.update_in(cx, |_, window, _| window.blur());
10736 cx.executor().run_until_parked();
10737 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10738
10739 // Deactivating the window still saves the file.
10740 item.update_in(cx, |item, window, cx| {
10741 cx.focus_self(window);
10742 item.is_dirty = true;
10743 });
10744 cx.deactivate_window();
10745 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10746
10747 // Autosave after delay.
10748 item.update(cx, |item, cx| {
10749 SettingsStore::update_global(cx, |settings, cx| {
10750 settings.update_user_settings(cx, |settings| {
10751 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10752 milliseconds: 500.into(),
10753 });
10754 })
10755 });
10756 item.is_dirty = true;
10757 cx.emit(ItemEvent::Edit);
10758 });
10759
10760 // Delay hasn't fully expired, so the file is still dirty and unsaved.
10761 cx.executor().advance_clock(Duration::from_millis(250));
10762 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10763
10764 // After delay expires, the file is saved.
10765 cx.executor().advance_clock(Duration::from_millis(250));
10766 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10767
10768 // Autosave after delay, should save earlier than delay if tab is closed
10769 item.update(cx, |item, cx| {
10770 item.is_dirty = true;
10771 cx.emit(ItemEvent::Edit);
10772 });
10773 cx.executor().advance_clock(Duration::from_millis(250));
10774 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10775
10776 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10777 pane.update_in(cx, |pane, window, cx| {
10778 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10779 })
10780 .await
10781 .unwrap();
10782 assert!(!cx.has_pending_prompt());
10783 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10784
10785 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10786 workspace.update_in(cx, |workspace, window, cx| {
10787 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10788 });
10789 item.update_in(cx, |item, _window, cx| {
10790 item.is_dirty = true;
10791 for project_item in &mut item.project_items {
10792 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10793 }
10794 });
10795 cx.run_until_parked();
10796 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10797
10798 // Autosave on focus change, ensuring closing the tab counts as such.
10799 item.update(cx, |item, cx| {
10800 SettingsStore::update_global(cx, |settings, cx| {
10801 settings.update_user_settings(cx, |settings| {
10802 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10803 })
10804 });
10805 item.is_dirty = true;
10806 for project_item in &mut item.project_items {
10807 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10808 }
10809 });
10810
10811 pane.update_in(cx, |pane, window, cx| {
10812 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10813 })
10814 .await
10815 .unwrap();
10816 assert!(!cx.has_pending_prompt());
10817 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10818
10819 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10820 workspace.update_in(cx, |workspace, window, cx| {
10821 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10822 });
10823 item.update_in(cx, |item, window, cx| {
10824 item.project_items[0].update(cx, |item, _| {
10825 item.entry_id = None;
10826 });
10827 item.is_dirty = true;
10828 window.blur();
10829 });
10830 cx.run_until_parked();
10831 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10832
10833 // Ensure autosave is prevented for deleted files also when closing the buffer.
10834 let _close_items = pane.update_in(cx, |pane, window, cx| {
10835 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10836 });
10837 cx.run_until_parked();
10838 assert!(cx.has_pending_prompt());
10839 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10840 }
10841
10842 #[gpui::test]
10843 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
10844 init_test(cx);
10845
10846 let fs = FakeFs::new(cx.executor());
10847 let project = Project::test(fs, [], cx).await;
10848 let (workspace, cx) =
10849 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10850
10851 // Create a multibuffer-like item with two child focus handles,
10852 // simulating individual buffer editors within a multibuffer.
10853 let item = cx.new(|cx| {
10854 TestItem::new(cx)
10855 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10856 .with_child_focus_handles(2, cx)
10857 });
10858 workspace.update_in(cx, |workspace, window, cx| {
10859 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10860 });
10861
10862 // Set autosave to OnFocusChange and focus the first child handle,
10863 // simulating the user's cursor being inside one of the multibuffer's excerpts.
10864 item.update_in(cx, |item, window, cx| {
10865 SettingsStore::update_global(cx, |settings, cx| {
10866 settings.update_user_settings(cx, |settings| {
10867 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10868 })
10869 });
10870 item.is_dirty = true;
10871 window.focus(&item.child_focus_handles[0], cx);
10872 });
10873 cx.executor().run_until_parked();
10874 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
10875
10876 // Moving focus from one child to another within the same item should
10877 // NOT trigger autosave — focus is still within the item's focus hierarchy.
10878 item.update_in(cx, |item, window, cx| {
10879 window.focus(&item.child_focus_handles[1], cx);
10880 });
10881 cx.executor().run_until_parked();
10882 item.read_with(cx, |item, _| {
10883 assert_eq!(
10884 item.save_count, 0,
10885 "Switching focus between children within the same item should not autosave"
10886 );
10887 });
10888
10889 // Blurring the item saves the file. This is the core regression scenario:
10890 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
10891 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
10892 // the leaf is always a child focus handle, so `on_blur` never detected
10893 // focus leaving the item.
10894 item.update_in(cx, |_, window, _| window.blur());
10895 cx.executor().run_until_parked();
10896 item.read_with(cx, |item, _| {
10897 assert_eq!(
10898 item.save_count, 1,
10899 "Blurring should trigger autosave when focus was on a child of the item"
10900 );
10901 });
10902
10903 // Deactivating the window should also trigger autosave when a child of
10904 // the multibuffer item currently owns focus.
10905 item.update_in(cx, |item, window, cx| {
10906 item.is_dirty = true;
10907 window.focus(&item.child_focus_handles[0], cx);
10908 });
10909 cx.executor().run_until_parked();
10910 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10911
10912 cx.deactivate_window();
10913 item.read_with(cx, |item, _| {
10914 assert_eq!(
10915 item.save_count, 2,
10916 "Deactivating window should trigger autosave when focus was on a child"
10917 );
10918 });
10919 }
10920
10921 #[gpui::test]
10922 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10923 init_test(cx);
10924
10925 let fs = FakeFs::new(cx.executor());
10926
10927 let project = Project::test(fs, [], cx).await;
10928 let (workspace, cx) =
10929 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10930
10931 let item = cx.new(|cx| {
10932 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10933 });
10934 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10935 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10936 let toolbar_notify_count = Rc::new(RefCell::new(0));
10937
10938 workspace.update_in(cx, |workspace, window, cx| {
10939 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10940 let toolbar_notification_count = toolbar_notify_count.clone();
10941 cx.observe_in(&toolbar, window, move |_, _, _, _| {
10942 *toolbar_notification_count.borrow_mut() += 1
10943 })
10944 .detach();
10945 });
10946
10947 pane.read_with(cx, |pane, _| {
10948 assert!(!pane.can_navigate_backward());
10949 assert!(!pane.can_navigate_forward());
10950 });
10951
10952 item.update_in(cx, |item, _, cx| {
10953 item.set_state("one".to_string(), cx);
10954 });
10955
10956 // Toolbar must be notified to re-render the navigation buttons
10957 assert_eq!(*toolbar_notify_count.borrow(), 1);
10958
10959 pane.read_with(cx, |pane, _| {
10960 assert!(pane.can_navigate_backward());
10961 assert!(!pane.can_navigate_forward());
10962 });
10963
10964 workspace
10965 .update_in(cx, |workspace, window, cx| {
10966 workspace.go_back(pane.downgrade(), window, cx)
10967 })
10968 .await
10969 .unwrap();
10970
10971 assert_eq!(*toolbar_notify_count.borrow(), 2);
10972 pane.read_with(cx, |pane, _| {
10973 assert!(!pane.can_navigate_backward());
10974 assert!(pane.can_navigate_forward());
10975 });
10976 }
10977
10978 #[gpui::test]
10979 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
10980 init_test(cx);
10981 let fs = FakeFs::new(cx.executor());
10982 let project = Project::test(fs, [], cx).await;
10983 let (multi_workspace, cx) =
10984 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
10985 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
10986
10987 workspace.update_in(cx, |workspace, window, cx| {
10988 let first_item = cx.new(|cx| {
10989 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10990 });
10991 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
10992 workspace.split_pane(
10993 workspace.active_pane().clone(),
10994 SplitDirection::Right,
10995 window,
10996 cx,
10997 );
10998 workspace.split_pane(
10999 workspace.active_pane().clone(),
11000 SplitDirection::Right,
11001 window,
11002 cx,
11003 );
11004 });
11005
11006 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11007 let panes = workspace.center.panes();
11008 assert!(panes.len() >= 2);
11009 (
11010 panes.first().expect("at least one pane").entity_id(),
11011 panes.last().expect("at least one pane").entity_id(),
11012 )
11013 });
11014
11015 workspace.update_in(cx, |workspace, window, cx| {
11016 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11017 });
11018 workspace.update(cx, |workspace, _| {
11019 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11020 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11021 });
11022
11023 cx.dispatch_action(ActivateLastPane);
11024
11025 workspace.update(cx, |workspace, _| {
11026 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11027 });
11028 }
11029
11030 #[gpui::test]
11031 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11032 init_test(cx);
11033 let fs = FakeFs::new(cx.executor());
11034
11035 let project = Project::test(fs, [], cx).await;
11036 let (workspace, cx) =
11037 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11038
11039 let panel = workspace.update_in(cx, |workspace, window, cx| {
11040 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11041 workspace.add_panel(panel.clone(), window, cx);
11042
11043 workspace
11044 .right_dock()
11045 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11046
11047 panel
11048 });
11049
11050 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11051 pane.update_in(cx, |pane, window, cx| {
11052 let item = cx.new(TestItem::new);
11053 pane.add_item(Box::new(item), true, true, None, window, cx);
11054 });
11055
11056 // Transfer focus from center to panel
11057 workspace.update_in(cx, |workspace, window, cx| {
11058 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11059 });
11060
11061 workspace.update_in(cx, |workspace, window, cx| {
11062 assert!(workspace.right_dock().read(cx).is_open());
11063 assert!(!panel.is_zoomed(window, cx));
11064 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11065 });
11066
11067 // Transfer focus from panel to center
11068 workspace.update_in(cx, |workspace, window, cx| {
11069 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11070 });
11071
11072 workspace.update_in(cx, |workspace, window, cx| {
11073 assert!(workspace.right_dock().read(cx).is_open());
11074 assert!(!panel.is_zoomed(window, cx));
11075 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11076 });
11077
11078 // Close the dock
11079 workspace.update_in(cx, |workspace, window, cx| {
11080 workspace.toggle_dock(DockPosition::Right, window, cx);
11081 });
11082
11083 workspace.update_in(cx, |workspace, window, cx| {
11084 assert!(!workspace.right_dock().read(cx).is_open());
11085 assert!(!panel.is_zoomed(window, cx));
11086 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11087 });
11088
11089 // Open the dock
11090 workspace.update_in(cx, |workspace, window, cx| {
11091 workspace.toggle_dock(DockPosition::Right, window, cx);
11092 });
11093
11094 workspace.update_in(cx, |workspace, window, cx| {
11095 assert!(workspace.right_dock().read(cx).is_open());
11096 assert!(!panel.is_zoomed(window, cx));
11097 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11098 });
11099
11100 // Focus and zoom panel
11101 panel.update_in(cx, |panel, window, cx| {
11102 cx.focus_self(window);
11103 panel.set_zoomed(true, window, cx)
11104 });
11105
11106 workspace.update_in(cx, |workspace, window, cx| {
11107 assert!(workspace.right_dock().read(cx).is_open());
11108 assert!(panel.is_zoomed(window, cx));
11109 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11110 });
11111
11112 // Transfer focus to the center closes the dock
11113 workspace.update_in(cx, |workspace, window, cx| {
11114 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11115 });
11116
11117 workspace.update_in(cx, |workspace, window, cx| {
11118 assert!(!workspace.right_dock().read(cx).is_open());
11119 assert!(panel.is_zoomed(window, cx));
11120 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11121 });
11122
11123 // Transferring focus back to the panel keeps it zoomed
11124 workspace.update_in(cx, |workspace, window, cx| {
11125 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11126 });
11127
11128 workspace.update_in(cx, |workspace, window, cx| {
11129 assert!(workspace.right_dock().read(cx).is_open());
11130 assert!(panel.is_zoomed(window, cx));
11131 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11132 });
11133
11134 // Close the dock while it is zoomed
11135 workspace.update_in(cx, |workspace, window, cx| {
11136 workspace.toggle_dock(DockPosition::Right, window, cx)
11137 });
11138
11139 workspace.update_in(cx, |workspace, window, cx| {
11140 assert!(!workspace.right_dock().read(cx).is_open());
11141 assert!(panel.is_zoomed(window, cx));
11142 assert!(workspace.zoomed.is_none());
11143 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11144 });
11145
11146 // Opening the dock, when it's zoomed, retains focus
11147 workspace.update_in(cx, |workspace, window, cx| {
11148 workspace.toggle_dock(DockPosition::Right, window, cx)
11149 });
11150
11151 workspace.update_in(cx, |workspace, window, cx| {
11152 assert!(workspace.right_dock().read(cx).is_open());
11153 assert!(panel.is_zoomed(window, cx));
11154 assert!(workspace.zoomed.is_some());
11155 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11156 });
11157
11158 // Unzoom and close the panel, zoom the active pane.
11159 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11160 workspace.update_in(cx, |workspace, window, cx| {
11161 workspace.toggle_dock(DockPosition::Right, window, cx)
11162 });
11163 pane.update_in(cx, |pane, window, cx| {
11164 pane.toggle_zoom(&Default::default(), window, cx)
11165 });
11166
11167 // Opening a dock unzooms the pane.
11168 workspace.update_in(cx, |workspace, window, cx| {
11169 workspace.toggle_dock(DockPosition::Right, window, cx)
11170 });
11171 workspace.update_in(cx, |workspace, window, cx| {
11172 let pane = pane.read(cx);
11173 assert!(!pane.is_zoomed());
11174 assert!(!pane.focus_handle(cx).is_focused(window));
11175 assert!(workspace.right_dock().read(cx).is_open());
11176 assert!(workspace.zoomed.is_none());
11177 });
11178 }
11179
11180 #[gpui::test]
11181 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11182 init_test(cx);
11183 let fs = FakeFs::new(cx.executor());
11184
11185 let project = Project::test(fs, [], cx).await;
11186 let (workspace, cx) =
11187 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11188
11189 let panel = workspace.update_in(cx, |workspace, window, cx| {
11190 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11191 workspace.add_panel(panel.clone(), window, cx);
11192 panel
11193 });
11194
11195 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11196 pane.update_in(cx, |pane, window, cx| {
11197 let item = cx.new(TestItem::new);
11198 pane.add_item(Box::new(item), true, true, None, window, cx);
11199 });
11200
11201 // Enable close_panel_on_toggle
11202 cx.update_global(|store: &mut SettingsStore, cx| {
11203 store.update_user_settings(cx, |settings| {
11204 settings.workspace.close_panel_on_toggle = Some(true);
11205 });
11206 });
11207
11208 // Panel starts closed. Toggling should open and focus it.
11209 workspace.update_in(cx, |workspace, window, cx| {
11210 assert!(!workspace.right_dock().read(cx).is_open());
11211 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11212 });
11213
11214 workspace.update_in(cx, |workspace, window, cx| {
11215 assert!(
11216 workspace.right_dock().read(cx).is_open(),
11217 "Dock should be open after toggling from center"
11218 );
11219 assert!(
11220 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11221 "Panel should be focused after toggling from center"
11222 );
11223 });
11224
11225 // Panel is open and focused. Toggling should close the panel and
11226 // return focus to the center.
11227 workspace.update_in(cx, |workspace, window, cx| {
11228 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11229 });
11230
11231 workspace.update_in(cx, |workspace, window, cx| {
11232 assert!(
11233 !workspace.right_dock().read(cx).is_open(),
11234 "Dock should be closed after toggling from focused panel"
11235 );
11236 assert!(
11237 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11238 "Panel should not be focused after toggling from focused panel"
11239 );
11240 });
11241
11242 // Open the dock and focus something else so the panel is open but not
11243 // focused. Toggling should focus the panel (not close it).
11244 workspace.update_in(cx, |workspace, window, cx| {
11245 workspace
11246 .right_dock()
11247 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11248 window.focus(&pane.read(cx).focus_handle(cx), cx);
11249 });
11250
11251 workspace.update_in(cx, |workspace, window, cx| {
11252 assert!(workspace.right_dock().read(cx).is_open());
11253 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11254 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11255 });
11256
11257 workspace.update_in(cx, |workspace, window, cx| {
11258 assert!(
11259 workspace.right_dock().read(cx).is_open(),
11260 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11261 );
11262 assert!(
11263 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11264 "Panel should be focused after toggling an open-but-unfocused panel"
11265 );
11266 });
11267
11268 // Now disable the setting and verify the original behavior: toggling
11269 // from a focused panel moves focus to center but leaves the dock open.
11270 cx.update_global(|store: &mut SettingsStore, cx| {
11271 store.update_user_settings(cx, |settings| {
11272 settings.workspace.close_panel_on_toggle = Some(false);
11273 });
11274 });
11275
11276 workspace.update_in(cx, |workspace, window, cx| {
11277 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11278 });
11279
11280 workspace.update_in(cx, |workspace, window, cx| {
11281 assert!(
11282 workspace.right_dock().read(cx).is_open(),
11283 "Dock should remain open when setting is disabled"
11284 );
11285 assert!(
11286 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11287 "Panel should not be focused after toggling with setting disabled"
11288 );
11289 });
11290 }
11291
11292 #[gpui::test]
11293 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11294 init_test(cx);
11295 let fs = FakeFs::new(cx.executor());
11296
11297 let project = Project::test(fs, [], cx).await;
11298 let (workspace, cx) =
11299 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11300
11301 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11302 workspace.active_pane().clone()
11303 });
11304
11305 // Add an item to the pane so it can be zoomed
11306 workspace.update_in(cx, |workspace, window, cx| {
11307 let item = cx.new(TestItem::new);
11308 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11309 });
11310
11311 // Initially not zoomed
11312 workspace.update_in(cx, |workspace, _window, cx| {
11313 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11314 assert!(
11315 workspace.zoomed.is_none(),
11316 "Workspace should track no zoomed pane"
11317 );
11318 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11319 });
11320
11321 // Zoom In
11322 pane.update_in(cx, |pane, window, cx| {
11323 pane.zoom_in(&crate::ZoomIn, window, cx);
11324 });
11325
11326 workspace.update_in(cx, |workspace, window, cx| {
11327 assert!(
11328 pane.read(cx).is_zoomed(),
11329 "Pane should be zoomed after ZoomIn"
11330 );
11331 assert!(
11332 workspace.zoomed.is_some(),
11333 "Workspace should track the zoomed pane"
11334 );
11335 assert!(
11336 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11337 "ZoomIn should focus the pane"
11338 );
11339 });
11340
11341 // Zoom In again is a no-op
11342 pane.update_in(cx, |pane, window, cx| {
11343 pane.zoom_in(&crate::ZoomIn, window, cx);
11344 });
11345
11346 workspace.update_in(cx, |workspace, window, cx| {
11347 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11348 assert!(
11349 workspace.zoomed.is_some(),
11350 "Workspace still tracks zoomed pane"
11351 );
11352 assert!(
11353 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11354 "Pane remains focused after repeated ZoomIn"
11355 );
11356 });
11357
11358 // Zoom Out
11359 pane.update_in(cx, |pane, window, cx| {
11360 pane.zoom_out(&crate::ZoomOut, window, cx);
11361 });
11362
11363 workspace.update_in(cx, |workspace, _window, cx| {
11364 assert!(
11365 !pane.read(cx).is_zoomed(),
11366 "Pane should unzoom after ZoomOut"
11367 );
11368 assert!(
11369 workspace.zoomed.is_none(),
11370 "Workspace clears zoom tracking after ZoomOut"
11371 );
11372 });
11373
11374 // Zoom Out again is a no-op
11375 pane.update_in(cx, |pane, window, cx| {
11376 pane.zoom_out(&crate::ZoomOut, window, cx);
11377 });
11378
11379 workspace.update_in(cx, |workspace, _window, cx| {
11380 assert!(
11381 !pane.read(cx).is_zoomed(),
11382 "Second ZoomOut keeps pane unzoomed"
11383 );
11384 assert!(
11385 workspace.zoomed.is_none(),
11386 "Workspace remains without zoomed pane"
11387 );
11388 });
11389 }
11390
11391 #[gpui::test]
11392 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11393 init_test(cx);
11394 let fs = FakeFs::new(cx.executor());
11395
11396 let project = Project::test(fs, [], cx).await;
11397 let (workspace, cx) =
11398 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11399 workspace.update_in(cx, |workspace, window, cx| {
11400 // Open two docks
11401 let left_dock = workspace.dock_at_position(DockPosition::Left);
11402 let right_dock = workspace.dock_at_position(DockPosition::Right);
11403
11404 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11405 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11406
11407 assert!(left_dock.read(cx).is_open());
11408 assert!(right_dock.read(cx).is_open());
11409 });
11410
11411 workspace.update_in(cx, |workspace, window, cx| {
11412 // Toggle all docks - should close both
11413 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11414
11415 let left_dock = workspace.dock_at_position(DockPosition::Left);
11416 let right_dock = workspace.dock_at_position(DockPosition::Right);
11417 assert!(!left_dock.read(cx).is_open());
11418 assert!(!right_dock.read(cx).is_open());
11419 });
11420
11421 workspace.update_in(cx, |workspace, window, cx| {
11422 // Toggle again - should reopen both
11423 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11424
11425 let left_dock = workspace.dock_at_position(DockPosition::Left);
11426 let right_dock = workspace.dock_at_position(DockPosition::Right);
11427 assert!(left_dock.read(cx).is_open());
11428 assert!(right_dock.read(cx).is_open());
11429 });
11430 }
11431
11432 #[gpui::test]
11433 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11434 init_test(cx);
11435 let fs = FakeFs::new(cx.executor());
11436
11437 let project = Project::test(fs, [], cx).await;
11438 let (workspace, cx) =
11439 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11440 workspace.update_in(cx, |workspace, window, cx| {
11441 // Open two docks
11442 let left_dock = workspace.dock_at_position(DockPosition::Left);
11443 let right_dock = workspace.dock_at_position(DockPosition::Right);
11444
11445 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11446 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11447
11448 assert!(left_dock.read(cx).is_open());
11449 assert!(right_dock.read(cx).is_open());
11450 });
11451
11452 workspace.update_in(cx, |workspace, window, cx| {
11453 // Close them manually
11454 workspace.toggle_dock(DockPosition::Left, window, cx);
11455 workspace.toggle_dock(DockPosition::Right, window, cx);
11456
11457 let left_dock = workspace.dock_at_position(DockPosition::Left);
11458 let right_dock = workspace.dock_at_position(DockPosition::Right);
11459 assert!(!left_dock.read(cx).is_open());
11460 assert!(!right_dock.read(cx).is_open());
11461 });
11462
11463 workspace.update_in(cx, |workspace, window, cx| {
11464 // Toggle all docks - only last closed (right dock) should reopen
11465 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11466
11467 let left_dock = workspace.dock_at_position(DockPosition::Left);
11468 let right_dock = workspace.dock_at_position(DockPosition::Right);
11469 assert!(!left_dock.read(cx).is_open());
11470 assert!(right_dock.read(cx).is_open());
11471 });
11472 }
11473
11474 #[gpui::test]
11475 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11476 init_test(cx);
11477 let fs = FakeFs::new(cx.executor());
11478 let project = Project::test(fs, [], cx).await;
11479 let (multi_workspace, cx) =
11480 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11481 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11482
11483 // Open two docks (left and right) with one panel each
11484 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11485 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11486 workspace.add_panel(left_panel.clone(), window, cx);
11487
11488 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11489 workspace.add_panel(right_panel.clone(), window, cx);
11490
11491 workspace.toggle_dock(DockPosition::Left, window, cx);
11492 workspace.toggle_dock(DockPosition::Right, window, cx);
11493
11494 // Verify initial state
11495 assert!(
11496 workspace.left_dock().read(cx).is_open(),
11497 "Left dock should be open"
11498 );
11499 assert_eq!(
11500 workspace
11501 .left_dock()
11502 .read(cx)
11503 .visible_panel()
11504 .unwrap()
11505 .panel_id(),
11506 left_panel.panel_id(),
11507 "Left panel should be visible in left dock"
11508 );
11509 assert!(
11510 workspace.right_dock().read(cx).is_open(),
11511 "Right dock should be open"
11512 );
11513 assert_eq!(
11514 workspace
11515 .right_dock()
11516 .read(cx)
11517 .visible_panel()
11518 .unwrap()
11519 .panel_id(),
11520 right_panel.panel_id(),
11521 "Right panel should be visible in right dock"
11522 );
11523 assert!(
11524 !workspace.bottom_dock().read(cx).is_open(),
11525 "Bottom dock should be closed"
11526 );
11527
11528 (left_panel, right_panel)
11529 });
11530
11531 // Focus the left panel and move it to the next position (bottom dock)
11532 workspace.update_in(cx, |workspace, window, cx| {
11533 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11534 assert!(
11535 left_panel.read(cx).focus_handle(cx).is_focused(window),
11536 "Left panel should be focused"
11537 );
11538 });
11539
11540 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11541
11542 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11543 workspace.update(cx, |workspace, cx| {
11544 assert!(
11545 !workspace.left_dock().read(cx).is_open(),
11546 "Left dock should be closed"
11547 );
11548 assert!(
11549 workspace.bottom_dock().read(cx).is_open(),
11550 "Bottom dock should now be open"
11551 );
11552 assert_eq!(
11553 left_panel.read(cx).position,
11554 DockPosition::Bottom,
11555 "Left panel should now be in the bottom dock"
11556 );
11557 assert_eq!(
11558 workspace
11559 .bottom_dock()
11560 .read(cx)
11561 .visible_panel()
11562 .unwrap()
11563 .panel_id(),
11564 left_panel.panel_id(),
11565 "Left panel should be the visible panel in the bottom dock"
11566 );
11567 });
11568
11569 // Toggle all docks off
11570 workspace.update_in(cx, |workspace, window, cx| {
11571 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11572 assert!(
11573 !workspace.left_dock().read(cx).is_open(),
11574 "Left dock should be closed"
11575 );
11576 assert!(
11577 !workspace.right_dock().read(cx).is_open(),
11578 "Right dock should be closed"
11579 );
11580 assert!(
11581 !workspace.bottom_dock().read(cx).is_open(),
11582 "Bottom dock should be closed"
11583 );
11584 });
11585
11586 // Toggle all docks back on and verify positions are restored
11587 workspace.update_in(cx, |workspace, window, cx| {
11588 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11589 assert!(
11590 !workspace.left_dock().read(cx).is_open(),
11591 "Left dock should remain closed"
11592 );
11593 assert!(
11594 workspace.right_dock().read(cx).is_open(),
11595 "Right dock should remain open"
11596 );
11597 assert!(
11598 workspace.bottom_dock().read(cx).is_open(),
11599 "Bottom dock should remain open"
11600 );
11601 assert_eq!(
11602 left_panel.read(cx).position,
11603 DockPosition::Bottom,
11604 "Left panel should remain in the bottom dock"
11605 );
11606 assert_eq!(
11607 right_panel.read(cx).position,
11608 DockPosition::Right,
11609 "Right panel should remain in the right dock"
11610 );
11611 assert_eq!(
11612 workspace
11613 .bottom_dock()
11614 .read(cx)
11615 .visible_panel()
11616 .unwrap()
11617 .panel_id(),
11618 left_panel.panel_id(),
11619 "Left panel should be the visible panel in the right dock"
11620 );
11621 });
11622 }
11623
11624 #[gpui::test]
11625 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11626 init_test(cx);
11627
11628 let fs = FakeFs::new(cx.executor());
11629
11630 let project = Project::test(fs, None, cx).await;
11631 let (workspace, cx) =
11632 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11633
11634 // Let's arrange the panes like this:
11635 //
11636 // +-----------------------+
11637 // | top |
11638 // +------+--------+-------+
11639 // | left | center | right |
11640 // +------+--------+-------+
11641 // | bottom |
11642 // +-----------------------+
11643
11644 let top_item = cx.new(|cx| {
11645 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11646 });
11647 let bottom_item = cx.new(|cx| {
11648 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11649 });
11650 let left_item = cx.new(|cx| {
11651 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11652 });
11653 let right_item = cx.new(|cx| {
11654 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11655 });
11656 let center_item = cx.new(|cx| {
11657 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11658 });
11659
11660 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11661 let top_pane_id = workspace.active_pane().entity_id();
11662 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11663 workspace.split_pane(
11664 workspace.active_pane().clone(),
11665 SplitDirection::Down,
11666 window,
11667 cx,
11668 );
11669 top_pane_id
11670 });
11671 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11672 let bottom_pane_id = workspace.active_pane().entity_id();
11673 workspace.add_item_to_active_pane(
11674 Box::new(bottom_item.clone()),
11675 None,
11676 false,
11677 window,
11678 cx,
11679 );
11680 workspace.split_pane(
11681 workspace.active_pane().clone(),
11682 SplitDirection::Up,
11683 window,
11684 cx,
11685 );
11686 bottom_pane_id
11687 });
11688 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11689 let left_pane_id = workspace.active_pane().entity_id();
11690 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11691 workspace.split_pane(
11692 workspace.active_pane().clone(),
11693 SplitDirection::Right,
11694 window,
11695 cx,
11696 );
11697 left_pane_id
11698 });
11699 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11700 let right_pane_id = workspace.active_pane().entity_id();
11701 workspace.add_item_to_active_pane(
11702 Box::new(right_item.clone()),
11703 None,
11704 false,
11705 window,
11706 cx,
11707 );
11708 workspace.split_pane(
11709 workspace.active_pane().clone(),
11710 SplitDirection::Left,
11711 window,
11712 cx,
11713 );
11714 right_pane_id
11715 });
11716 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11717 let center_pane_id = workspace.active_pane().entity_id();
11718 workspace.add_item_to_active_pane(
11719 Box::new(center_item.clone()),
11720 None,
11721 false,
11722 window,
11723 cx,
11724 );
11725 center_pane_id
11726 });
11727 cx.executor().run_until_parked();
11728
11729 workspace.update_in(cx, |workspace, window, cx| {
11730 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11731
11732 // Join into next from center pane into right
11733 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11734 });
11735
11736 workspace.update_in(cx, |workspace, window, cx| {
11737 let active_pane = workspace.active_pane();
11738 assert_eq!(right_pane_id, active_pane.entity_id());
11739 assert_eq!(2, active_pane.read(cx).items_len());
11740 let item_ids_in_pane =
11741 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11742 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11743 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11744
11745 // Join into next from right pane into bottom
11746 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11747 });
11748
11749 workspace.update_in(cx, |workspace, window, cx| {
11750 let active_pane = workspace.active_pane();
11751 assert_eq!(bottom_pane_id, active_pane.entity_id());
11752 assert_eq!(3, active_pane.read(cx).items_len());
11753 let item_ids_in_pane =
11754 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11755 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11756 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11757 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11758
11759 // Join into next from bottom pane into left
11760 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11761 });
11762
11763 workspace.update_in(cx, |workspace, window, cx| {
11764 let active_pane = workspace.active_pane();
11765 assert_eq!(left_pane_id, active_pane.entity_id());
11766 assert_eq!(4, active_pane.read(cx).items_len());
11767 let item_ids_in_pane =
11768 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11769 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11770 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11771 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11772 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11773
11774 // Join into next from left pane into top
11775 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11776 });
11777
11778 workspace.update_in(cx, |workspace, window, cx| {
11779 let active_pane = workspace.active_pane();
11780 assert_eq!(top_pane_id, active_pane.entity_id());
11781 assert_eq!(5, active_pane.read(cx).items_len());
11782 let item_ids_in_pane =
11783 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11784 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11785 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11786 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11787 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11788 assert!(item_ids_in_pane.contains(&top_item.item_id()));
11789
11790 // Single pane left: no-op
11791 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11792 });
11793
11794 workspace.update(cx, |workspace, _cx| {
11795 let active_pane = workspace.active_pane();
11796 assert_eq!(top_pane_id, active_pane.entity_id());
11797 });
11798 }
11799
11800 fn add_an_item_to_active_pane(
11801 cx: &mut VisualTestContext,
11802 workspace: &Entity<Workspace>,
11803 item_id: u64,
11804 ) -> Entity<TestItem> {
11805 let item = cx.new(|cx| {
11806 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11807 item_id,
11808 "item{item_id}.txt",
11809 cx,
11810 )])
11811 });
11812 workspace.update_in(cx, |workspace, window, cx| {
11813 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11814 });
11815 item
11816 }
11817
11818 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11819 workspace.update_in(cx, |workspace, window, cx| {
11820 workspace.split_pane(
11821 workspace.active_pane().clone(),
11822 SplitDirection::Right,
11823 window,
11824 cx,
11825 )
11826 })
11827 }
11828
11829 #[gpui::test]
11830 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11831 init_test(cx);
11832 let fs = FakeFs::new(cx.executor());
11833 let project = Project::test(fs, None, cx).await;
11834 let (workspace, cx) =
11835 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11836
11837 add_an_item_to_active_pane(cx, &workspace, 1);
11838 split_pane(cx, &workspace);
11839 add_an_item_to_active_pane(cx, &workspace, 2);
11840 split_pane(cx, &workspace); // empty pane
11841 split_pane(cx, &workspace);
11842 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11843
11844 cx.executor().run_until_parked();
11845
11846 workspace.update(cx, |workspace, cx| {
11847 let num_panes = workspace.panes().len();
11848 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11849 let active_item = workspace
11850 .active_pane()
11851 .read(cx)
11852 .active_item()
11853 .expect("item is in focus");
11854
11855 assert_eq!(num_panes, 4);
11856 assert_eq!(num_items_in_current_pane, 1);
11857 assert_eq!(active_item.item_id(), last_item.item_id());
11858 });
11859
11860 workspace.update_in(cx, |workspace, window, cx| {
11861 workspace.join_all_panes(window, cx);
11862 });
11863
11864 workspace.update(cx, |workspace, cx| {
11865 let num_panes = workspace.panes().len();
11866 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11867 let active_item = workspace
11868 .active_pane()
11869 .read(cx)
11870 .active_item()
11871 .expect("item is in focus");
11872
11873 assert_eq!(num_panes, 1);
11874 assert_eq!(num_items_in_current_pane, 3);
11875 assert_eq!(active_item.item_id(), last_item.item_id());
11876 });
11877 }
11878 struct TestModal(FocusHandle);
11879
11880 impl TestModal {
11881 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11882 Self(cx.focus_handle())
11883 }
11884 }
11885
11886 impl EventEmitter<DismissEvent> for TestModal {}
11887
11888 impl Focusable for TestModal {
11889 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11890 self.0.clone()
11891 }
11892 }
11893
11894 impl ModalView for TestModal {}
11895
11896 impl Render for TestModal {
11897 fn render(
11898 &mut self,
11899 _window: &mut Window,
11900 _cx: &mut Context<TestModal>,
11901 ) -> impl IntoElement {
11902 div().track_focus(&self.0)
11903 }
11904 }
11905
11906 #[gpui::test]
11907 async fn test_panels(cx: &mut gpui::TestAppContext) {
11908 init_test(cx);
11909 let fs = FakeFs::new(cx.executor());
11910
11911 let project = Project::test(fs, [], cx).await;
11912 let (multi_workspace, cx) =
11913 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11914 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11915
11916 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11917 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11918 workspace.add_panel(panel_1.clone(), window, cx);
11919 workspace.toggle_dock(DockPosition::Left, window, cx);
11920 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11921 workspace.add_panel(panel_2.clone(), window, cx);
11922 workspace.toggle_dock(DockPosition::Right, window, cx);
11923
11924 let left_dock = workspace.left_dock();
11925 assert_eq!(
11926 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11927 panel_1.panel_id()
11928 );
11929 assert_eq!(
11930 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11931 panel_1.size(window, cx)
11932 );
11933
11934 left_dock.update(cx, |left_dock, cx| {
11935 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11936 });
11937 assert_eq!(
11938 workspace
11939 .right_dock()
11940 .read(cx)
11941 .visible_panel()
11942 .unwrap()
11943 .panel_id(),
11944 panel_2.panel_id(),
11945 );
11946
11947 (panel_1, panel_2)
11948 });
11949
11950 // Move panel_1 to the right
11951 panel_1.update_in(cx, |panel_1, window, cx| {
11952 panel_1.set_position(DockPosition::Right, window, cx)
11953 });
11954
11955 workspace.update_in(cx, |workspace, window, cx| {
11956 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11957 // Since it was the only panel on the left, the left dock should now be closed.
11958 assert!(!workspace.left_dock().read(cx).is_open());
11959 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11960 let right_dock = workspace.right_dock();
11961 assert_eq!(
11962 right_dock.read(cx).visible_panel().unwrap().panel_id(),
11963 panel_1.panel_id()
11964 );
11965 assert_eq!(
11966 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11967 px(1337.)
11968 );
11969
11970 // Now we move panel_2 to the left
11971 panel_2.set_position(DockPosition::Left, window, cx);
11972 });
11973
11974 workspace.update(cx, |workspace, cx| {
11975 // Since panel_2 was not visible on the right, we don't open the left dock.
11976 assert!(!workspace.left_dock().read(cx).is_open());
11977 // And the right dock is unaffected in its displaying of panel_1
11978 assert!(workspace.right_dock().read(cx).is_open());
11979 assert_eq!(
11980 workspace
11981 .right_dock()
11982 .read(cx)
11983 .visible_panel()
11984 .unwrap()
11985 .panel_id(),
11986 panel_1.panel_id(),
11987 );
11988 });
11989
11990 // Move panel_1 back to the left
11991 panel_1.update_in(cx, |panel_1, window, cx| {
11992 panel_1.set_position(DockPosition::Left, window, cx)
11993 });
11994
11995 workspace.update_in(cx, |workspace, window, cx| {
11996 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11997 let left_dock = workspace.left_dock();
11998 assert!(left_dock.read(cx).is_open());
11999 assert_eq!(
12000 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12001 panel_1.panel_id()
12002 );
12003 assert_eq!(
12004 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
12005 px(1337.)
12006 );
12007 // And the right dock should be closed as it no longer has any panels.
12008 assert!(!workspace.right_dock().read(cx).is_open());
12009
12010 // Now we move panel_1 to the bottom
12011 panel_1.set_position(DockPosition::Bottom, window, cx);
12012 });
12013
12014 workspace.update_in(cx, |workspace, window, cx| {
12015 // Since panel_1 was visible on the left, we close the left dock.
12016 assert!(!workspace.left_dock().read(cx).is_open());
12017 // The bottom dock is sized based on the panel's default size,
12018 // since the panel orientation changed from vertical to horizontal.
12019 let bottom_dock = workspace.bottom_dock();
12020 assert_eq!(
12021 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
12022 panel_1.size(window, cx),
12023 );
12024 // Close bottom dock and move panel_1 back to the left.
12025 bottom_dock.update(cx, |bottom_dock, cx| {
12026 bottom_dock.set_open(false, window, cx)
12027 });
12028 panel_1.set_position(DockPosition::Left, window, cx);
12029 });
12030
12031 // Emit activated event on panel 1
12032 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12033
12034 // Now the left dock is open and panel_1 is active and focused.
12035 workspace.update_in(cx, |workspace, window, cx| {
12036 let left_dock = workspace.left_dock();
12037 assert!(left_dock.read(cx).is_open());
12038 assert_eq!(
12039 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12040 panel_1.panel_id(),
12041 );
12042 assert!(panel_1.focus_handle(cx).is_focused(window));
12043 });
12044
12045 // Emit closed event on panel 2, which is not active
12046 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12047
12048 // Wo don't close the left dock, because panel_2 wasn't the active panel
12049 workspace.update(cx, |workspace, cx| {
12050 let left_dock = workspace.left_dock();
12051 assert!(left_dock.read(cx).is_open());
12052 assert_eq!(
12053 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12054 panel_1.panel_id(),
12055 );
12056 });
12057
12058 // Emitting a ZoomIn event shows the panel as zoomed.
12059 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12060 workspace.read_with(cx, |workspace, _| {
12061 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12062 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12063 });
12064
12065 // Move panel to another dock while it is zoomed
12066 panel_1.update_in(cx, |panel, window, cx| {
12067 panel.set_position(DockPosition::Right, window, cx)
12068 });
12069 workspace.read_with(cx, |workspace, _| {
12070 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12071
12072 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12073 });
12074
12075 // This is a helper for getting a:
12076 // - valid focus on an element,
12077 // - that isn't a part of the panes and panels system of the Workspace,
12078 // - and doesn't trigger the 'on_focus_lost' API.
12079 let focus_other_view = {
12080 let workspace = workspace.clone();
12081 move |cx: &mut VisualTestContext| {
12082 workspace.update_in(cx, |workspace, window, cx| {
12083 if workspace.active_modal::<TestModal>(cx).is_some() {
12084 workspace.toggle_modal(window, cx, TestModal::new);
12085 workspace.toggle_modal(window, cx, TestModal::new);
12086 } else {
12087 workspace.toggle_modal(window, cx, TestModal::new);
12088 }
12089 })
12090 }
12091 };
12092
12093 // If focus is transferred to another view that's not a panel or another pane, we still show
12094 // the panel as zoomed.
12095 focus_other_view(cx);
12096 workspace.read_with(cx, |workspace, _| {
12097 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12098 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12099 });
12100
12101 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12102 workspace.update_in(cx, |_workspace, window, cx| {
12103 cx.focus_self(window);
12104 });
12105 workspace.read_with(cx, |workspace, _| {
12106 assert_eq!(workspace.zoomed, None);
12107 assert_eq!(workspace.zoomed_position, None);
12108 });
12109
12110 // If focus is transferred again to another view that's not a panel or a pane, we won't
12111 // show the panel as zoomed because it wasn't zoomed before.
12112 focus_other_view(cx);
12113 workspace.read_with(cx, |workspace, _| {
12114 assert_eq!(workspace.zoomed, None);
12115 assert_eq!(workspace.zoomed_position, None);
12116 });
12117
12118 // When the panel is activated, it is zoomed again.
12119 cx.dispatch_action(ToggleRightDock);
12120 workspace.read_with(cx, |workspace, _| {
12121 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12122 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12123 });
12124
12125 // Emitting a ZoomOut event unzooms the panel.
12126 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12127 workspace.read_with(cx, |workspace, _| {
12128 assert_eq!(workspace.zoomed, None);
12129 assert_eq!(workspace.zoomed_position, None);
12130 });
12131
12132 // Emit closed event on panel 1, which is active
12133 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12134
12135 // Now the left dock is closed, because panel_1 was the active panel
12136 workspace.update(cx, |workspace, cx| {
12137 let right_dock = workspace.right_dock();
12138 assert!(!right_dock.read(cx).is_open());
12139 });
12140 }
12141
12142 #[gpui::test]
12143 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12144 init_test(cx);
12145
12146 let fs = FakeFs::new(cx.background_executor.clone());
12147 let project = Project::test(fs, [], cx).await;
12148 let (workspace, cx) =
12149 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12150 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12151
12152 let dirty_regular_buffer = cx.new(|cx| {
12153 TestItem::new(cx)
12154 .with_dirty(true)
12155 .with_label("1.txt")
12156 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12157 });
12158 let dirty_regular_buffer_2 = cx.new(|cx| {
12159 TestItem::new(cx)
12160 .with_dirty(true)
12161 .with_label("2.txt")
12162 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12163 });
12164 let dirty_multi_buffer_with_both = cx.new(|cx| {
12165 TestItem::new(cx)
12166 .with_dirty(true)
12167 .with_buffer_kind(ItemBufferKind::Multibuffer)
12168 .with_label("Fake Project Search")
12169 .with_project_items(&[
12170 dirty_regular_buffer.read(cx).project_items[0].clone(),
12171 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12172 ])
12173 });
12174 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12175 workspace.update_in(cx, |workspace, window, cx| {
12176 workspace.add_item(
12177 pane.clone(),
12178 Box::new(dirty_regular_buffer.clone()),
12179 None,
12180 false,
12181 false,
12182 window,
12183 cx,
12184 );
12185 workspace.add_item(
12186 pane.clone(),
12187 Box::new(dirty_regular_buffer_2.clone()),
12188 None,
12189 false,
12190 false,
12191 window,
12192 cx,
12193 );
12194 workspace.add_item(
12195 pane.clone(),
12196 Box::new(dirty_multi_buffer_with_both.clone()),
12197 None,
12198 false,
12199 false,
12200 window,
12201 cx,
12202 );
12203 });
12204
12205 pane.update_in(cx, |pane, window, cx| {
12206 pane.activate_item(2, true, true, window, cx);
12207 assert_eq!(
12208 pane.active_item().unwrap().item_id(),
12209 multi_buffer_with_both_files_id,
12210 "Should select the multi buffer in the pane"
12211 );
12212 });
12213 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12214 pane.close_other_items(
12215 &CloseOtherItems {
12216 save_intent: Some(SaveIntent::Save),
12217 close_pinned: true,
12218 },
12219 None,
12220 window,
12221 cx,
12222 )
12223 });
12224 cx.background_executor.run_until_parked();
12225 assert!(!cx.has_pending_prompt());
12226 close_all_but_multi_buffer_task
12227 .await
12228 .expect("Closing all buffers but the multi buffer failed");
12229 pane.update(cx, |pane, cx| {
12230 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12231 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12232 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12233 assert_eq!(pane.items_len(), 1);
12234 assert_eq!(
12235 pane.active_item().unwrap().item_id(),
12236 multi_buffer_with_both_files_id,
12237 "Should have only the multi buffer left in the pane"
12238 );
12239 assert!(
12240 dirty_multi_buffer_with_both.read(cx).is_dirty,
12241 "The multi buffer containing the unsaved buffer should still be dirty"
12242 );
12243 });
12244
12245 dirty_regular_buffer.update(cx, |buffer, cx| {
12246 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12247 });
12248
12249 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12250 pane.close_active_item(
12251 &CloseActiveItem {
12252 save_intent: Some(SaveIntent::Close),
12253 close_pinned: false,
12254 },
12255 window,
12256 cx,
12257 )
12258 });
12259 cx.background_executor.run_until_parked();
12260 assert!(
12261 cx.has_pending_prompt(),
12262 "Dirty multi buffer should prompt a save dialog"
12263 );
12264 cx.simulate_prompt_answer("Save");
12265 cx.background_executor.run_until_parked();
12266 close_multi_buffer_task
12267 .await
12268 .expect("Closing the multi buffer failed");
12269 pane.update(cx, |pane, cx| {
12270 assert_eq!(
12271 dirty_multi_buffer_with_both.read(cx).save_count,
12272 1,
12273 "Multi buffer item should get be saved"
12274 );
12275 // Test impl does not save inner items, so we do not assert them
12276 assert_eq!(
12277 pane.items_len(),
12278 0,
12279 "No more items should be left in the pane"
12280 );
12281 assert!(pane.active_item().is_none());
12282 });
12283 }
12284
12285 #[gpui::test]
12286 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
12287 cx: &mut TestAppContext,
12288 ) {
12289 init_test(cx);
12290
12291 let fs = FakeFs::new(cx.background_executor.clone());
12292 let project = Project::test(fs, [], cx).await;
12293 let (workspace, cx) =
12294 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12295 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12296
12297 let dirty_regular_buffer = cx.new(|cx| {
12298 TestItem::new(cx)
12299 .with_dirty(true)
12300 .with_label("1.txt")
12301 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12302 });
12303 let dirty_regular_buffer_2 = cx.new(|cx| {
12304 TestItem::new(cx)
12305 .with_dirty(true)
12306 .with_label("2.txt")
12307 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12308 });
12309 let clear_regular_buffer = cx.new(|cx| {
12310 TestItem::new(cx)
12311 .with_label("3.txt")
12312 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12313 });
12314
12315 let dirty_multi_buffer_with_both = cx.new(|cx| {
12316 TestItem::new(cx)
12317 .with_dirty(true)
12318 .with_buffer_kind(ItemBufferKind::Multibuffer)
12319 .with_label("Fake Project Search")
12320 .with_project_items(&[
12321 dirty_regular_buffer.read(cx).project_items[0].clone(),
12322 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12323 clear_regular_buffer.read(cx).project_items[0].clone(),
12324 ])
12325 });
12326 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12327 workspace.update_in(cx, |workspace, window, cx| {
12328 workspace.add_item(
12329 pane.clone(),
12330 Box::new(dirty_regular_buffer.clone()),
12331 None,
12332 false,
12333 false,
12334 window,
12335 cx,
12336 );
12337 workspace.add_item(
12338 pane.clone(),
12339 Box::new(dirty_multi_buffer_with_both.clone()),
12340 None,
12341 false,
12342 false,
12343 window,
12344 cx,
12345 );
12346 });
12347
12348 pane.update_in(cx, |pane, window, cx| {
12349 pane.activate_item(1, true, true, window, cx);
12350 assert_eq!(
12351 pane.active_item().unwrap().item_id(),
12352 multi_buffer_with_both_files_id,
12353 "Should select the multi buffer in the pane"
12354 );
12355 });
12356 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12357 pane.close_active_item(
12358 &CloseActiveItem {
12359 save_intent: None,
12360 close_pinned: false,
12361 },
12362 window,
12363 cx,
12364 )
12365 });
12366 cx.background_executor.run_until_parked();
12367 assert!(
12368 cx.has_pending_prompt(),
12369 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
12370 );
12371 }
12372
12373 /// Tests that when `close_on_file_delete` is enabled, files are automatically
12374 /// closed when they are deleted from disk.
12375 #[gpui::test]
12376 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
12377 init_test(cx);
12378
12379 // Enable the close_on_disk_deletion setting
12380 cx.update_global(|store: &mut SettingsStore, cx| {
12381 store.update_user_settings(cx, |settings| {
12382 settings.workspace.close_on_file_delete = Some(true);
12383 });
12384 });
12385
12386 let fs = FakeFs::new(cx.background_executor.clone());
12387 let project = Project::test(fs, [], cx).await;
12388 let (workspace, cx) =
12389 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12390 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12391
12392 // Create a test item that simulates a file
12393 let item = cx.new(|cx| {
12394 TestItem::new(cx)
12395 .with_label("test.txt")
12396 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12397 });
12398
12399 // Add item to workspace
12400 workspace.update_in(cx, |workspace, window, cx| {
12401 workspace.add_item(
12402 pane.clone(),
12403 Box::new(item.clone()),
12404 None,
12405 false,
12406 false,
12407 window,
12408 cx,
12409 );
12410 });
12411
12412 // Verify the item is in the pane
12413 pane.read_with(cx, |pane, _| {
12414 assert_eq!(pane.items().count(), 1);
12415 });
12416
12417 // Simulate file deletion by setting the item's deleted state
12418 item.update(cx, |item, _| {
12419 item.set_has_deleted_file(true);
12420 });
12421
12422 // Emit UpdateTab event to trigger the close behavior
12423 cx.run_until_parked();
12424 item.update(cx, |_, cx| {
12425 cx.emit(ItemEvent::UpdateTab);
12426 });
12427
12428 // Allow the close operation to complete
12429 cx.run_until_parked();
12430
12431 // Verify the item was automatically closed
12432 pane.read_with(cx, |pane, _| {
12433 assert_eq!(
12434 pane.items().count(),
12435 0,
12436 "Item should be automatically closed when file is deleted"
12437 );
12438 });
12439 }
12440
12441 /// Tests that when `close_on_file_delete` is disabled (default), files remain
12442 /// open with a strikethrough when they are deleted from disk.
12443 #[gpui::test]
12444 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12445 init_test(cx);
12446
12447 // Ensure close_on_disk_deletion is disabled (default)
12448 cx.update_global(|store: &mut SettingsStore, cx| {
12449 store.update_user_settings(cx, |settings| {
12450 settings.workspace.close_on_file_delete = Some(false);
12451 });
12452 });
12453
12454 let fs = FakeFs::new(cx.background_executor.clone());
12455 let project = Project::test(fs, [], cx).await;
12456 let (workspace, cx) =
12457 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12458 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12459
12460 // Create a test item that simulates a file
12461 let item = cx.new(|cx| {
12462 TestItem::new(cx)
12463 .with_label("test.txt")
12464 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12465 });
12466
12467 // Add item to workspace
12468 workspace.update_in(cx, |workspace, window, cx| {
12469 workspace.add_item(
12470 pane.clone(),
12471 Box::new(item.clone()),
12472 None,
12473 false,
12474 false,
12475 window,
12476 cx,
12477 );
12478 });
12479
12480 // Verify the item is in the pane
12481 pane.read_with(cx, |pane, _| {
12482 assert_eq!(pane.items().count(), 1);
12483 });
12484
12485 // Simulate file deletion
12486 item.update(cx, |item, _| {
12487 item.set_has_deleted_file(true);
12488 });
12489
12490 // Emit UpdateTab event
12491 cx.run_until_parked();
12492 item.update(cx, |_, cx| {
12493 cx.emit(ItemEvent::UpdateTab);
12494 });
12495
12496 // Allow any potential close operation to complete
12497 cx.run_until_parked();
12498
12499 // Verify the item remains open (with strikethrough)
12500 pane.read_with(cx, |pane, _| {
12501 assert_eq!(
12502 pane.items().count(),
12503 1,
12504 "Item should remain open when close_on_disk_deletion is disabled"
12505 );
12506 });
12507
12508 // Verify the item shows as deleted
12509 item.read_with(cx, |item, _| {
12510 assert!(
12511 item.has_deleted_file,
12512 "Item should be marked as having deleted file"
12513 );
12514 });
12515 }
12516
12517 /// Tests that dirty files are not automatically closed when deleted from disk,
12518 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12519 /// unsaved changes without being prompted.
12520 #[gpui::test]
12521 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12522 init_test(cx);
12523
12524 // Enable the close_on_file_delete setting
12525 cx.update_global(|store: &mut SettingsStore, cx| {
12526 store.update_user_settings(cx, |settings| {
12527 settings.workspace.close_on_file_delete = Some(true);
12528 });
12529 });
12530
12531 let fs = FakeFs::new(cx.background_executor.clone());
12532 let project = Project::test(fs, [], cx).await;
12533 let (workspace, cx) =
12534 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12535 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12536
12537 // Create a dirty test item
12538 let item = cx.new(|cx| {
12539 TestItem::new(cx)
12540 .with_dirty(true)
12541 .with_label("test.txt")
12542 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12543 });
12544
12545 // Add item to workspace
12546 workspace.update_in(cx, |workspace, window, cx| {
12547 workspace.add_item(
12548 pane.clone(),
12549 Box::new(item.clone()),
12550 None,
12551 false,
12552 false,
12553 window,
12554 cx,
12555 );
12556 });
12557
12558 // Simulate file deletion
12559 item.update(cx, |item, _| {
12560 item.set_has_deleted_file(true);
12561 });
12562
12563 // Emit UpdateTab event to trigger the close behavior
12564 cx.run_until_parked();
12565 item.update(cx, |_, cx| {
12566 cx.emit(ItemEvent::UpdateTab);
12567 });
12568
12569 // Allow any potential close operation to complete
12570 cx.run_until_parked();
12571
12572 // Verify the item remains open (dirty files are not auto-closed)
12573 pane.read_with(cx, |pane, _| {
12574 assert_eq!(
12575 pane.items().count(),
12576 1,
12577 "Dirty items should not be automatically closed even when file is deleted"
12578 );
12579 });
12580
12581 // Verify the item is marked as deleted and still dirty
12582 item.read_with(cx, |item, _| {
12583 assert!(
12584 item.has_deleted_file,
12585 "Item should be marked as having deleted file"
12586 );
12587 assert!(item.is_dirty, "Item should still be dirty");
12588 });
12589 }
12590
12591 /// Tests that navigation history is cleaned up when files are auto-closed
12592 /// due to deletion from disk.
12593 #[gpui::test]
12594 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12595 init_test(cx);
12596
12597 // Enable the close_on_file_delete setting
12598 cx.update_global(|store: &mut SettingsStore, cx| {
12599 store.update_user_settings(cx, |settings| {
12600 settings.workspace.close_on_file_delete = Some(true);
12601 });
12602 });
12603
12604 let fs = FakeFs::new(cx.background_executor.clone());
12605 let project = Project::test(fs, [], cx).await;
12606 let (workspace, cx) =
12607 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12608 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12609
12610 // Create test items
12611 let item1 = cx.new(|cx| {
12612 TestItem::new(cx)
12613 .with_label("test1.txt")
12614 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12615 });
12616 let item1_id = item1.item_id();
12617
12618 let item2 = cx.new(|cx| {
12619 TestItem::new(cx)
12620 .with_label("test2.txt")
12621 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12622 });
12623
12624 // Add items to workspace
12625 workspace.update_in(cx, |workspace, window, cx| {
12626 workspace.add_item(
12627 pane.clone(),
12628 Box::new(item1.clone()),
12629 None,
12630 false,
12631 false,
12632 window,
12633 cx,
12634 );
12635 workspace.add_item(
12636 pane.clone(),
12637 Box::new(item2.clone()),
12638 None,
12639 false,
12640 false,
12641 window,
12642 cx,
12643 );
12644 });
12645
12646 // Activate item1 to ensure it gets navigation entries
12647 pane.update_in(cx, |pane, window, cx| {
12648 pane.activate_item(0, true, true, window, cx);
12649 });
12650
12651 // Switch to item2 and back to create navigation history
12652 pane.update_in(cx, |pane, window, cx| {
12653 pane.activate_item(1, true, true, window, cx);
12654 });
12655 cx.run_until_parked();
12656
12657 pane.update_in(cx, |pane, window, cx| {
12658 pane.activate_item(0, true, true, window, cx);
12659 });
12660 cx.run_until_parked();
12661
12662 // Simulate file deletion for item1
12663 item1.update(cx, |item, _| {
12664 item.set_has_deleted_file(true);
12665 });
12666
12667 // Emit UpdateTab event to trigger the close behavior
12668 item1.update(cx, |_, cx| {
12669 cx.emit(ItemEvent::UpdateTab);
12670 });
12671 cx.run_until_parked();
12672
12673 // Verify item1 was closed
12674 pane.read_with(cx, |pane, _| {
12675 assert_eq!(
12676 pane.items().count(),
12677 1,
12678 "Should have 1 item remaining after auto-close"
12679 );
12680 });
12681
12682 // Check navigation history after close
12683 let has_item = pane.read_with(cx, |pane, cx| {
12684 let mut has_item = false;
12685 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12686 if entry.item.id() == item1_id {
12687 has_item = true;
12688 }
12689 });
12690 has_item
12691 });
12692
12693 assert!(
12694 !has_item,
12695 "Navigation history should not contain closed item entries"
12696 );
12697 }
12698
12699 #[gpui::test]
12700 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12701 cx: &mut TestAppContext,
12702 ) {
12703 init_test(cx);
12704
12705 let fs = FakeFs::new(cx.background_executor.clone());
12706 let project = Project::test(fs, [], cx).await;
12707 let (workspace, cx) =
12708 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12709 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12710
12711 let dirty_regular_buffer = cx.new(|cx| {
12712 TestItem::new(cx)
12713 .with_dirty(true)
12714 .with_label("1.txt")
12715 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12716 });
12717 let dirty_regular_buffer_2 = cx.new(|cx| {
12718 TestItem::new(cx)
12719 .with_dirty(true)
12720 .with_label("2.txt")
12721 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12722 });
12723 let clear_regular_buffer = cx.new(|cx| {
12724 TestItem::new(cx)
12725 .with_label("3.txt")
12726 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12727 });
12728
12729 let dirty_multi_buffer = cx.new(|cx| {
12730 TestItem::new(cx)
12731 .with_dirty(true)
12732 .with_buffer_kind(ItemBufferKind::Multibuffer)
12733 .with_label("Fake Project Search")
12734 .with_project_items(&[
12735 dirty_regular_buffer.read(cx).project_items[0].clone(),
12736 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12737 clear_regular_buffer.read(cx).project_items[0].clone(),
12738 ])
12739 });
12740 workspace.update_in(cx, |workspace, window, cx| {
12741 workspace.add_item(
12742 pane.clone(),
12743 Box::new(dirty_regular_buffer.clone()),
12744 None,
12745 false,
12746 false,
12747 window,
12748 cx,
12749 );
12750 workspace.add_item(
12751 pane.clone(),
12752 Box::new(dirty_regular_buffer_2.clone()),
12753 None,
12754 false,
12755 false,
12756 window,
12757 cx,
12758 );
12759 workspace.add_item(
12760 pane.clone(),
12761 Box::new(dirty_multi_buffer.clone()),
12762 None,
12763 false,
12764 false,
12765 window,
12766 cx,
12767 );
12768 });
12769
12770 pane.update_in(cx, |pane, window, cx| {
12771 pane.activate_item(2, true, true, window, cx);
12772 assert_eq!(
12773 pane.active_item().unwrap().item_id(),
12774 dirty_multi_buffer.item_id(),
12775 "Should select the multi buffer in the pane"
12776 );
12777 });
12778 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12779 pane.close_active_item(
12780 &CloseActiveItem {
12781 save_intent: None,
12782 close_pinned: false,
12783 },
12784 window,
12785 cx,
12786 )
12787 });
12788 cx.background_executor.run_until_parked();
12789 assert!(
12790 !cx.has_pending_prompt(),
12791 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12792 );
12793 close_multi_buffer_task
12794 .await
12795 .expect("Closing multi buffer failed");
12796 pane.update(cx, |pane, cx| {
12797 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12798 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12799 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12800 assert_eq!(
12801 pane.items()
12802 .map(|item| item.item_id())
12803 .sorted()
12804 .collect::<Vec<_>>(),
12805 vec![
12806 dirty_regular_buffer.item_id(),
12807 dirty_regular_buffer_2.item_id(),
12808 ],
12809 "Should have no multi buffer left in the pane"
12810 );
12811 assert!(dirty_regular_buffer.read(cx).is_dirty);
12812 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12813 });
12814 }
12815
12816 #[gpui::test]
12817 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12818 init_test(cx);
12819 let fs = FakeFs::new(cx.executor());
12820 let project = Project::test(fs, [], cx).await;
12821 let (multi_workspace, cx) =
12822 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12823 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12824
12825 // Add a new panel to the right dock, opening the dock and setting the
12826 // focus to the new panel.
12827 let panel = workspace.update_in(cx, |workspace, window, cx| {
12828 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12829 workspace.add_panel(panel.clone(), window, cx);
12830
12831 workspace
12832 .right_dock()
12833 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12834
12835 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12836
12837 panel
12838 });
12839
12840 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12841 // panel to the next valid position which, in this case, is the left
12842 // dock.
12843 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12844 workspace.update(cx, |workspace, cx| {
12845 assert!(workspace.left_dock().read(cx).is_open());
12846 assert_eq!(panel.read(cx).position, DockPosition::Left);
12847 });
12848
12849 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12850 // panel to the next valid position which, in this case, is the bottom
12851 // dock.
12852 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12853 workspace.update(cx, |workspace, cx| {
12854 assert!(workspace.bottom_dock().read(cx).is_open());
12855 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12856 });
12857
12858 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12859 // around moving the panel to its initial position, the right dock.
12860 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12861 workspace.update(cx, |workspace, cx| {
12862 assert!(workspace.right_dock().read(cx).is_open());
12863 assert_eq!(panel.read(cx).position, DockPosition::Right);
12864 });
12865
12866 // Remove focus from the panel, ensuring that, if the panel is not
12867 // focused, the `MoveFocusedPanelToNextPosition` action does not update
12868 // the panel's position, so the panel is still in the right dock.
12869 workspace.update_in(cx, |workspace, window, cx| {
12870 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12871 });
12872
12873 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12874 workspace.update(cx, |workspace, cx| {
12875 assert!(workspace.right_dock().read(cx).is_open());
12876 assert_eq!(panel.read(cx).position, DockPosition::Right);
12877 });
12878 }
12879
12880 #[gpui::test]
12881 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12882 init_test(cx);
12883
12884 let fs = FakeFs::new(cx.executor());
12885 let project = Project::test(fs, [], cx).await;
12886 let (workspace, cx) =
12887 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12888
12889 let item_1 = cx.new(|cx| {
12890 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12891 });
12892 workspace.update_in(cx, |workspace, window, cx| {
12893 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12894 workspace.move_item_to_pane_in_direction(
12895 &MoveItemToPaneInDirection {
12896 direction: SplitDirection::Right,
12897 focus: true,
12898 clone: false,
12899 },
12900 window,
12901 cx,
12902 );
12903 workspace.move_item_to_pane_at_index(
12904 &MoveItemToPane {
12905 destination: 3,
12906 focus: true,
12907 clone: false,
12908 },
12909 window,
12910 cx,
12911 );
12912
12913 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12914 assert_eq!(
12915 pane_items_paths(&workspace.active_pane, cx),
12916 vec!["first.txt".to_string()],
12917 "Single item was not moved anywhere"
12918 );
12919 });
12920
12921 let item_2 = cx.new(|cx| {
12922 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12923 });
12924 workspace.update_in(cx, |workspace, window, cx| {
12925 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12926 assert_eq!(
12927 pane_items_paths(&workspace.panes[0], cx),
12928 vec!["first.txt".to_string(), "second.txt".to_string()],
12929 );
12930 workspace.move_item_to_pane_in_direction(
12931 &MoveItemToPaneInDirection {
12932 direction: SplitDirection::Right,
12933 focus: true,
12934 clone: false,
12935 },
12936 window,
12937 cx,
12938 );
12939
12940 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12941 assert_eq!(
12942 pane_items_paths(&workspace.panes[0], cx),
12943 vec!["first.txt".to_string()],
12944 "After moving, one item should be left in the original pane"
12945 );
12946 assert_eq!(
12947 pane_items_paths(&workspace.panes[1], cx),
12948 vec!["second.txt".to_string()],
12949 "New item should have been moved to the new pane"
12950 );
12951 });
12952
12953 let item_3 = cx.new(|cx| {
12954 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12955 });
12956 workspace.update_in(cx, |workspace, window, cx| {
12957 let original_pane = workspace.panes[0].clone();
12958 workspace.set_active_pane(&original_pane, window, cx);
12959 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12960 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12961 assert_eq!(
12962 pane_items_paths(&workspace.active_pane, cx),
12963 vec!["first.txt".to_string(), "third.txt".to_string()],
12964 "New pane should be ready to move one item out"
12965 );
12966
12967 workspace.move_item_to_pane_at_index(
12968 &MoveItemToPane {
12969 destination: 3,
12970 focus: true,
12971 clone: false,
12972 },
12973 window,
12974 cx,
12975 );
12976 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12977 assert_eq!(
12978 pane_items_paths(&workspace.active_pane, cx),
12979 vec!["first.txt".to_string()],
12980 "After moving, one item should be left in the original pane"
12981 );
12982 assert_eq!(
12983 pane_items_paths(&workspace.panes[1], cx),
12984 vec!["second.txt".to_string()],
12985 "Previously created pane should be unchanged"
12986 );
12987 assert_eq!(
12988 pane_items_paths(&workspace.panes[2], cx),
12989 vec!["third.txt".to_string()],
12990 "New item should have been moved to the new pane"
12991 );
12992 });
12993 }
12994
12995 #[gpui::test]
12996 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12997 init_test(cx);
12998
12999 let fs = FakeFs::new(cx.executor());
13000 let project = Project::test(fs, [], cx).await;
13001 let (workspace, cx) =
13002 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13003
13004 let item_1 = cx.new(|cx| {
13005 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13006 });
13007 workspace.update_in(cx, |workspace, window, cx| {
13008 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13009 workspace.move_item_to_pane_in_direction(
13010 &MoveItemToPaneInDirection {
13011 direction: SplitDirection::Right,
13012 focus: true,
13013 clone: true,
13014 },
13015 window,
13016 cx,
13017 );
13018 });
13019 cx.run_until_parked();
13020 workspace.update_in(cx, |workspace, window, cx| {
13021 workspace.move_item_to_pane_at_index(
13022 &MoveItemToPane {
13023 destination: 3,
13024 focus: true,
13025 clone: true,
13026 },
13027 window,
13028 cx,
13029 );
13030 });
13031 cx.run_until_parked();
13032
13033 workspace.update(cx, |workspace, cx| {
13034 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13035 for pane in workspace.panes() {
13036 assert_eq!(
13037 pane_items_paths(pane, cx),
13038 vec!["first.txt".to_string()],
13039 "Single item exists in all panes"
13040 );
13041 }
13042 });
13043
13044 // verify that the active pane has been updated after waiting for the
13045 // pane focus event to fire and resolve
13046 workspace.read_with(cx, |workspace, _app| {
13047 assert_eq!(
13048 workspace.active_pane(),
13049 &workspace.panes[2],
13050 "The third pane should be the active one: {:?}",
13051 workspace.panes
13052 );
13053 })
13054 }
13055
13056 #[gpui::test]
13057 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13058 init_test(cx);
13059
13060 let fs = FakeFs::new(cx.executor());
13061 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13062
13063 let project = Project::test(fs, ["root".as_ref()], cx).await;
13064 let (workspace, cx) =
13065 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13066
13067 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13068 // Add item to pane A with project path
13069 let item_a = cx.new(|cx| {
13070 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13071 });
13072 workspace.update_in(cx, |workspace, window, cx| {
13073 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13074 });
13075
13076 // Split to create pane B
13077 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13078 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13079 });
13080
13081 // Add item with SAME project path to pane B, and pin it
13082 let item_b = cx.new(|cx| {
13083 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13084 });
13085 pane_b.update_in(cx, |pane, window, cx| {
13086 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13087 pane.set_pinned_count(1);
13088 });
13089
13090 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13091 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13092
13093 // close_pinned: false should only close the unpinned copy
13094 workspace.update_in(cx, |workspace, window, cx| {
13095 workspace.close_item_in_all_panes(
13096 &CloseItemInAllPanes {
13097 save_intent: Some(SaveIntent::Close),
13098 close_pinned: false,
13099 },
13100 window,
13101 cx,
13102 )
13103 });
13104 cx.executor().run_until_parked();
13105
13106 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13107 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13108 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13109 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13110
13111 // Split again, seeing as closing the previous item also closed its
13112 // pane, so only pane remains, which does not allow us to properly test
13113 // that both items close when `close_pinned: true`.
13114 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13115 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13116 });
13117
13118 // Add an item with the same project path to pane C so that
13119 // close_item_in_all_panes can determine what to close across all panes
13120 // (it reads the active item from the active pane, and split_pane
13121 // creates an empty pane).
13122 let item_c = cx.new(|cx| {
13123 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13124 });
13125 pane_c.update_in(cx, |pane, window, cx| {
13126 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13127 });
13128
13129 // close_pinned: true should close the pinned copy too
13130 workspace.update_in(cx, |workspace, window, cx| {
13131 let panes_count = workspace.panes().len();
13132 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13133
13134 workspace.close_item_in_all_panes(
13135 &CloseItemInAllPanes {
13136 save_intent: Some(SaveIntent::Close),
13137 close_pinned: true,
13138 },
13139 window,
13140 cx,
13141 )
13142 });
13143 cx.executor().run_until_parked();
13144
13145 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13146 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13147 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13148 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13149 }
13150
13151 mod register_project_item_tests {
13152
13153 use super::*;
13154
13155 // View
13156 struct TestPngItemView {
13157 focus_handle: FocusHandle,
13158 }
13159 // Model
13160 struct TestPngItem {}
13161
13162 impl project::ProjectItem for TestPngItem {
13163 fn try_open(
13164 _project: &Entity<Project>,
13165 path: &ProjectPath,
13166 cx: &mut App,
13167 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13168 if path.path.extension().unwrap() == "png" {
13169 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13170 } else {
13171 None
13172 }
13173 }
13174
13175 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13176 None
13177 }
13178
13179 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13180 None
13181 }
13182
13183 fn is_dirty(&self) -> bool {
13184 false
13185 }
13186 }
13187
13188 impl Item for TestPngItemView {
13189 type Event = ();
13190 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13191 "".into()
13192 }
13193 }
13194 impl EventEmitter<()> for TestPngItemView {}
13195 impl Focusable for TestPngItemView {
13196 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13197 self.focus_handle.clone()
13198 }
13199 }
13200
13201 impl Render for TestPngItemView {
13202 fn render(
13203 &mut self,
13204 _window: &mut Window,
13205 _cx: &mut Context<Self>,
13206 ) -> impl IntoElement {
13207 Empty
13208 }
13209 }
13210
13211 impl ProjectItem for TestPngItemView {
13212 type Item = TestPngItem;
13213
13214 fn for_project_item(
13215 _project: Entity<Project>,
13216 _pane: Option<&Pane>,
13217 _item: Entity<Self::Item>,
13218 _: &mut Window,
13219 cx: &mut Context<Self>,
13220 ) -> Self
13221 where
13222 Self: Sized,
13223 {
13224 Self {
13225 focus_handle: cx.focus_handle(),
13226 }
13227 }
13228 }
13229
13230 // View
13231 struct TestIpynbItemView {
13232 focus_handle: FocusHandle,
13233 }
13234 // Model
13235 struct TestIpynbItem {}
13236
13237 impl project::ProjectItem for TestIpynbItem {
13238 fn try_open(
13239 _project: &Entity<Project>,
13240 path: &ProjectPath,
13241 cx: &mut App,
13242 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13243 if path.path.extension().unwrap() == "ipynb" {
13244 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13245 } else {
13246 None
13247 }
13248 }
13249
13250 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13251 None
13252 }
13253
13254 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13255 None
13256 }
13257
13258 fn is_dirty(&self) -> bool {
13259 false
13260 }
13261 }
13262
13263 impl Item for TestIpynbItemView {
13264 type Event = ();
13265 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13266 "".into()
13267 }
13268 }
13269 impl EventEmitter<()> for TestIpynbItemView {}
13270 impl Focusable for TestIpynbItemView {
13271 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13272 self.focus_handle.clone()
13273 }
13274 }
13275
13276 impl Render for TestIpynbItemView {
13277 fn render(
13278 &mut self,
13279 _window: &mut Window,
13280 _cx: &mut Context<Self>,
13281 ) -> impl IntoElement {
13282 Empty
13283 }
13284 }
13285
13286 impl ProjectItem for TestIpynbItemView {
13287 type Item = TestIpynbItem;
13288
13289 fn for_project_item(
13290 _project: Entity<Project>,
13291 _pane: Option<&Pane>,
13292 _item: Entity<Self::Item>,
13293 _: &mut Window,
13294 cx: &mut Context<Self>,
13295 ) -> Self
13296 where
13297 Self: Sized,
13298 {
13299 Self {
13300 focus_handle: cx.focus_handle(),
13301 }
13302 }
13303 }
13304
13305 struct TestAlternatePngItemView {
13306 focus_handle: FocusHandle,
13307 }
13308
13309 impl Item for TestAlternatePngItemView {
13310 type Event = ();
13311 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13312 "".into()
13313 }
13314 }
13315
13316 impl EventEmitter<()> for TestAlternatePngItemView {}
13317 impl Focusable for TestAlternatePngItemView {
13318 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13319 self.focus_handle.clone()
13320 }
13321 }
13322
13323 impl Render for TestAlternatePngItemView {
13324 fn render(
13325 &mut self,
13326 _window: &mut Window,
13327 _cx: &mut Context<Self>,
13328 ) -> impl IntoElement {
13329 Empty
13330 }
13331 }
13332
13333 impl ProjectItem for TestAlternatePngItemView {
13334 type Item = TestPngItem;
13335
13336 fn for_project_item(
13337 _project: Entity<Project>,
13338 _pane: Option<&Pane>,
13339 _item: Entity<Self::Item>,
13340 _: &mut Window,
13341 cx: &mut Context<Self>,
13342 ) -> Self
13343 where
13344 Self: Sized,
13345 {
13346 Self {
13347 focus_handle: cx.focus_handle(),
13348 }
13349 }
13350 }
13351
13352 #[gpui::test]
13353 async fn test_register_project_item(cx: &mut TestAppContext) {
13354 init_test(cx);
13355
13356 cx.update(|cx| {
13357 register_project_item::<TestPngItemView>(cx);
13358 register_project_item::<TestIpynbItemView>(cx);
13359 });
13360
13361 let fs = FakeFs::new(cx.executor());
13362 fs.insert_tree(
13363 "/root1",
13364 json!({
13365 "one.png": "BINARYDATAHERE",
13366 "two.ipynb": "{ totally a notebook }",
13367 "three.txt": "editing text, sure why not?"
13368 }),
13369 )
13370 .await;
13371
13372 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13373 let (workspace, cx) =
13374 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13375
13376 let worktree_id = project.update(cx, |project, cx| {
13377 project.worktrees(cx).next().unwrap().read(cx).id()
13378 });
13379
13380 let handle = workspace
13381 .update_in(cx, |workspace, window, cx| {
13382 let project_path = (worktree_id, rel_path("one.png"));
13383 workspace.open_path(project_path, None, true, window, cx)
13384 })
13385 .await
13386 .unwrap();
13387
13388 // Now we can check if the handle we got back errored or not
13389 assert_eq!(
13390 handle.to_any_view().entity_type(),
13391 TypeId::of::<TestPngItemView>()
13392 );
13393
13394 let handle = workspace
13395 .update_in(cx, |workspace, window, cx| {
13396 let project_path = (worktree_id, rel_path("two.ipynb"));
13397 workspace.open_path(project_path, None, true, window, cx)
13398 })
13399 .await
13400 .unwrap();
13401
13402 assert_eq!(
13403 handle.to_any_view().entity_type(),
13404 TypeId::of::<TestIpynbItemView>()
13405 );
13406
13407 let handle = workspace
13408 .update_in(cx, |workspace, window, cx| {
13409 let project_path = (worktree_id, rel_path("three.txt"));
13410 workspace.open_path(project_path, None, true, window, cx)
13411 })
13412 .await;
13413 assert!(handle.is_err());
13414 }
13415
13416 #[gpui::test]
13417 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
13418 init_test(cx);
13419
13420 cx.update(|cx| {
13421 register_project_item::<TestPngItemView>(cx);
13422 register_project_item::<TestAlternatePngItemView>(cx);
13423 });
13424
13425 let fs = FakeFs::new(cx.executor());
13426 fs.insert_tree(
13427 "/root1",
13428 json!({
13429 "one.png": "BINARYDATAHERE",
13430 "two.ipynb": "{ totally a notebook }",
13431 "three.txt": "editing text, sure why not?"
13432 }),
13433 )
13434 .await;
13435 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13436 let (workspace, cx) =
13437 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13438 let worktree_id = project.update(cx, |project, cx| {
13439 project.worktrees(cx).next().unwrap().read(cx).id()
13440 });
13441
13442 let handle = workspace
13443 .update_in(cx, |workspace, window, cx| {
13444 let project_path = (worktree_id, rel_path("one.png"));
13445 workspace.open_path(project_path, None, true, window, cx)
13446 })
13447 .await
13448 .unwrap();
13449
13450 // This _must_ be the second item registered
13451 assert_eq!(
13452 handle.to_any_view().entity_type(),
13453 TypeId::of::<TestAlternatePngItemView>()
13454 );
13455
13456 let handle = workspace
13457 .update_in(cx, |workspace, window, cx| {
13458 let project_path = (worktree_id, rel_path("three.txt"));
13459 workspace.open_path(project_path, None, true, window, cx)
13460 })
13461 .await;
13462 assert!(handle.is_err());
13463 }
13464 }
13465
13466 #[gpui::test]
13467 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13468 init_test(cx);
13469
13470 let fs = FakeFs::new(cx.executor());
13471 let project = Project::test(fs, [], cx).await;
13472 let (workspace, _cx) =
13473 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13474
13475 // Test with status bar shown (default)
13476 workspace.read_with(cx, |workspace, cx| {
13477 let visible = workspace.status_bar_visible(cx);
13478 assert!(visible, "Status bar should be visible by default");
13479 });
13480
13481 // Test with status bar hidden
13482 cx.update_global(|store: &mut SettingsStore, cx| {
13483 store.update_user_settings(cx, |settings| {
13484 settings.status_bar.get_or_insert_default().show = Some(false);
13485 });
13486 });
13487
13488 workspace.read_with(cx, |workspace, cx| {
13489 let visible = workspace.status_bar_visible(cx);
13490 assert!(!visible, "Status bar should be hidden when show is false");
13491 });
13492
13493 // Test with status bar shown explicitly
13494 cx.update_global(|store: &mut SettingsStore, cx| {
13495 store.update_user_settings(cx, |settings| {
13496 settings.status_bar.get_or_insert_default().show = Some(true);
13497 });
13498 });
13499
13500 workspace.read_with(cx, |workspace, cx| {
13501 let visible = workspace.status_bar_visible(cx);
13502 assert!(visible, "Status bar should be visible when show is true");
13503 });
13504 }
13505
13506 #[gpui::test]
13507 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13508 init_test(cx);
13509
13510 let fs = FakeFs::new(cx.executor());
13511 let project = Project::test(fs, [], cx).await;
13512 let (multi_workspace, cx) =
13513 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13514 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13515 let panel = workspace.update_in(cx, |workspace, window, cx| {
13516 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13517 workspace.add_panel(panel.clone(), window, cx);
13518
13519 workspace
13520 .right_dock()
13521 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13522
13523 panel
13524 });
13525
13526 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13527 let item_a = cx.new(TestItem::new);
13528 let item_b = cx.new(TestItem::new);
13529 let item_a_id = item_a.entity_id();
13530 let item_b_id = item_b.entity_id();
13531
13532 pane.update_in(cx, |pane, window, cx| {
13533 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13534 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13535 });
13536
13537 pane.read_with(cx, |pane, _| {
13538 assert_eq!(pane.items_len(), 2);
13539 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13540 });
13541
13542 workspace.update_in(cx, |workspace, window, cx| {
13543 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13544 });
13545
13546 workspace.update_in(cx, |_, window, cx| {
13547 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13548 });
13549
13550 // Assert that the `pane::CloseActiveItem` action is handled at the
13551 // workspace level when one of the dock panels is focused and, in that
13552 // case, the center pane's active item is closed but the focus is not
13553 // moved.
13554 cx.dispatch_action(pane::CloseActiveItem::default());
13555 cx.run_until_parked();
13556
13557 pane.read_with(cx, |pane, _| {
13558 assert_eq!(pane.items_len(), 1);
13559 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13560 });
13561
13562 workspace.update_in(cx, |workspace, window, cx| {
13563 assert!(workspace.right_dock().read(cx).is_open());
13564 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13565 });
13566 }
13567
13568 #[gpui::test]
13569 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13570 init_test(cx);
13571 let fs = FakeFs::new(cx.executor());
13572
13573 let project_a = Project::test(fs.clone(), [], cx).await;
13574 let project_b = Project::test(fs, [], cx).await;
13575
13576 let multi_workspace_handle =
13577 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13578 cx.run_until_parked();
13579
13580 let workspace_a = multi_workspace_handle
13581 .read_with(cx, |mw, _| mw.workspace().clone())
13582 .unwrap();
13583
13584 let _workspace_b = multi_workspace_handle
13585 .update(cx, |mw, window, cx| {
13586 mw.test_add_workspace(project_b, window, cx)
13587 })
13588 .unwrap();
13589
13590 // Switch to workspace A
13591 multi_workspace_handle
13592 .update(cx, |mw, window, cx| {
13593 mw.activate_index(0, window, cx);
13594 })
13595 .unwrap();
13596
13597 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13598
13599 // Add a panel to workspace A's right dock and open the dock
13600 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13601 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13602 workspace.add_panel(panel.clone(), window, cx);
13603 workspace
13604 .right_dock()
13605 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13606 panel
13607 });
13608
13609 // Focus the panel through the workspace (matching existing test pattern)
13610 workspace_a.update_in(cx, |workspace, window, cx| {
13611 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13612 });
13613
13614 // Zoom the panel
13615 panel.update_in(cx, |panel, window, cx| {
13616 panel.set_zoomed(true, window, cx);
13617 });
13618
13619 // Verify the panel is zoomed and the dock is open
13620 workspace_a.update_in(cx, |workspace, window, cx| {
13621 assert!(
13622 workspace.right_dock().read(cx).is_open(),
13623 "dock should be open before switch"
13624 );
13625 assert!(
13626 panel.is_zoomed(window, cx),
13627 "panel should be zoomed before switch"
13628 );
13629 assert!(
13630 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13631 "panel should be focused before switch"
13632 );
13633 });
13634
13635 // Switch to workspace B
13636 multi_workspace_handle
13637 .update(cx, |mw, window, cx| {
13638 mw.activate_index(1, window, cx);
13639 })
13640 .unwrap();
13641 cx.run_until_parked();
13642
13643 // Switch back to workspace A
13644 multi_workspace_handle
13645 .update(cx, |mw, window, cx| {
13646 mw.activate_index(0, window, cx);
13647 })
13648 .unwrap();
13649 cx.run_until_parked();
13650
13651 // Verify the panel is still zoomed and the dock is still open
13652 workspace_a.update_in(cx, |workspace, window, cx| {
13653 assert!(
13654 workspace.right_dock().read(cx).is_open(),
13655 "dock should still be open after switching back"
13656 );
13657 assert!(
13658 panel.is_zoomed(window, cx),
13659 "panel should still be zoomed after switching back"
13660 );
13661 });
13662 }
13663
13664 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13665 pane.read(cx)
13666 .items()
13667 .flat_map(|item| {
13668 item.project_paths(cx)
13669 .into_iter()
13670 .map(|path| path.path.display(PathStyle::local()).into_owned())
13671 })
13672 .collect()
13673 }
13674
13675 pub fn init_test(cx: &mut TestAppContext) {
13676 cx.update(|cx| {
13677 let settings_store = SettingsStore::test(cx);
13678 cx.set_global(settings_store);
13679 cx.set_global(db::AppDatabase::test_new());
13680 theme::init(theme::LoadThemes::JustBase, cx);
13681 });
13682 }
13683
13684 #[gpui::test]
13685 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
13686 use settings::{ThemeName, ThemeSelection};
13687 use theme::SystemAppearance;
13688 use zed_actions::theme::ToggleMode;
13689
13690 init_test(cx);
13691
13692 let fs = FakeFs::new(cx.executor());
13693 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
13694
13695 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
13696 .await;
13697
13698 // Build a test project and workspace view so the test can invoke
13699 // the workspace action handler the same way the UI would.
13700 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
13701 let (workspace, cx) =
13702 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13703
13704 // Seed the settings file with a plain static light theme so the
13705 // first toggle always starts from a known persisted state.
13706 workspace.update_in(cx, |_workspace, _window, cx| {
13707 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
13708 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
13709 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
13710 });
13711 });
13712 cx.executor().advance_clock(Duration::from_millis(200));
13713 cx.run_until_parked();
13714
13715 // Confirm the initial persisted settings contain the static theme
13716 // we just wrote before any toggling happens.
13717 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13718 assert!(settings_text.contains(r#""theme": "One Light""#));
13719
13720 // Toggle once. This should migrate the persisted theme settings
13721 // into light/dark slots and enable system mode.
13722 workspace.update_in(cx, |workspace, window, cx| {
13723 workspace.toggle_theme_mode(&ToggleMode, window, cx);
13724 });
13725 cx.executor().advance_clock(Duration::from_millis(200));
13726 cx.run_until_parked();
13727
13728 // 1. Static -> Dynamic
13729 // this assertion checks theme changed from static to dynamic.
13730 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13731 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
13732 assert_eq!(
13733 parsed["theme"],
13734 serde_json::json!({
13735 "mode": "system",
13736 "light": "One Light",
13737 "dark": "One Dark"
13738 })
13739 );
13740
13741 // 2. Toggle again, suppose it will change the mode to light
13742 workspace.update_in(cx, |workspace, window, cx| {
13743 workspace.toggle_theme_mode(&ToggleMode, window, cx);
13744 });
13745 cx.executor().advance_clock(Duration::from_millis(200));
13746 cx.run_until_parked();
13747
13748 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13749 assert!(settings_text.contains(r#""mode": "light""#));
13750 }
13751
13752 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13753 let item = TestProjectItem::new(id, path, cx);
13754 item.update(cx, |item, _| {
13755 item.is_dirty = true;
13756 });
13757 item
13758 }
13759
13760 #[gpui::test]
13761 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13762 cx: &mut gpui::TestAppContext,
13763 ) {
13764 init_test(cx);
13765 let fs = FakeFs::new(cx.executor());
13766
13767 let project = Project::test(fs, [], cx).await;
13768 let (workspace, cx) =
13769 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13770
13771 let panel = workspace.update_in(cx, |workspace, window, cx| {
13772 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13773 workspace.add_panel(panel.clone(), window, cx);
13774 workspace
13775 .right_dock()
13776 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13777 panel
13778 });
13779
13780 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13781 pane.update_in(cx, |pane, window, cx| {
13782 let item = cx.new(TestItem::new);
13783 pane.add_item(Box::new(item), true, true, None, window, cx);
13784 });
13785
13786 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13787 // mirrors the real-world flow and avoids side effects from directly
13788 // focusing the panel while the center pane is active.
13789 workspace.update_in(cx, |workspace, window, cx| {
13790 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13791 });
13792
13793 panel.update_in(cx, |panel, window, cx| {
13794 panel.set_zoomed(true, window, cx);
13795 });
13796
13797 workspace.update_in(cx, |workspace, window, cx| {
13798 assert!(workspace.right_dock().read(cx).is_open());
13799 assert!(panel.is_zoomed(window, cx));
13800 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13801 });
13802
13803 // Simulate a spurious pane::Event::Focus on the center pane while the
13804 // panel still has focus. This mirrors what happens during macOS window
13805 // activation: the center pane fires a focus event even though actual
13806 // focus remains on the dock panel.
13807 pane.update_in(cx, |_, _, cx| {
13808 cx.emit(pane::Event::Focus);
13809 });
13810
13811 // The dock must remain open because the panel had focus at the time the
13812 // event was processed. Before the fix, dock_to_preserve was None for
13813 // panels that don't implement pane(), causing the dock to close.
13814 workspace.update_in(cx, |workspace, window, cx| {
13815 assert!(
13816 workspace.right_dock().read(cx).is_open(),
13817 "Dock should stay open when its zoomed panel (without pane()) still has focus"
13818 );
13819 assert!(panel.is_zoomed(window, cx));
13820 });
13821 }
13822}