1pub mod dock;
2pub mod history_manager;
3pub mod invalid_item_view;
4pub mod item;
5mod modal_layer;
6mod multi_workspace;
7pub mod notifications;
8pub mod pane;
9pub mod pane_group;
10pub mod path_list {
11 pub use util::path_list::{PathList, SerializedPathList};
12}
13mod persistence;
14pub mod searchable;
15mod security_modal;
16pub mod shared_screen;
17use db::smol::future::yield_now;
18pub use shared_screen::SharedScreen;
19mod status_bar;
20pub mod tasks;
21mod theme_preview;
22mod toast_layer;
23mod toolbar;
24pub mod welcome;
25mod workspace_settings;
26
27pub use crate::notifications::NotificationFrame;
28pub use dock::Panel;
29pub use multi_workspace::{
30 CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace,
31 MultiWorkspaceEvent, Sidebar, 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, deferred, hsla, linear_color_stop, linear_gradient, point,
59 relative, size, transparent_black,
60};
61pub use history_manager::*;
62pub use item::{
63 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
64 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
65};
66use itertools::Itertools;
67use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
68pub use modal_layer::*;
69use node_runtime::NodeRuntime;
70use notifications::{
71 DetachAndPromptErr, Notifications, dismiss_app_notification,
72 simple_message_notification::MessageNotification,
73};
74pub use pane::*;
75pub use pane_group::{
76 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
77 SplitDirection,
78};
79use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
80pub use persistence::{
81 WorkspaceDb, delete_unloaded_items,
82 model::{
83 DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
84 SessionWorkspace,
85 },
86 read_serialized_multi_workspaces, resolve_worktree_workspaces,
87};
88use postage::stream::Stream;
89use project::{
90 DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
91 WorktreeSettings,
92 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
93 project_settings::ProjectSettings,
94 toolchain_store::ToolchainStoreEvent,
95 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
96};
97use remote::{
98 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
99 remote_client::ConnectionIdentifier,
100};
101use schemars::JsonSchema;
102use serde::Deserialize;
103use session::AppSession;
104use settings::{
105 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
106};
107
108use sqlez::{
109 bindable::{Bind, Column, StaticColumnCount},
110 statement::Statement,
111};
112use status_bar::StatusBar;
113pub use status_bar::StatusItemView;
114use std::{
115 any::TypeId,
116 borrow::Cow,
117 cell::RefCell,
118 cmp,
119 collections::VecDeque,
120 env,
121 hash::Hash,
122 path::{Path, PathBuf},
123 process::ExitStatus,
124 rc::Rc,
125 sync::{
126 Arc, LazyLock, Weak,
127 atomic::{AtomicBool, AtomicUsize},
128 },
129 time::Duration,
130};
131use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
132use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
133pub use toolbar::{
134 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
135};
136pub use ui;
137use ui::{Window, prelude::*};
138use util::{
139 ResultExt, TryFutureExt,
140 paths::{PathStyle, SanitizedPath},
141 rel_path::RelPath,
142 serde::default_true,
143};
144use uuid::Uuid;
145pub use workspace_settings::{
146 AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
147 WorkspaceSettings,
148};
149use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
150
151use crate::{item::ItemBufferKind, notifications::NotificationId};
152use crate::{
153 persistence::{
154 SerializedAxis,
155 model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
156 },
157 security_modal::SecurityModal,
158};
159
160pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
161
162static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
163 env::var("ZED_WINDOW_SIZE")
164 .ok()
165 .as_deref()
166 .and_then(parse_pixel_size_env_var)
167});
168
169static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
170 env::var("ZED_WINDOW_POSITION")
171 .ok()
172 .as_deref()
173 .and_then(parse_pixel_position_env_var)
174});
175
176pub trait TerminalProvider {
177 fn spawn(
178 &self,
179 task: SpawnInTerminal,
180 window: &mut Window,
181 cx: &mut App,
182 ) -> Task<Option<Result<ExitStatus>>>;
183}
184
185pub trait DebuggerProvider {
186 // `active_buffer` is used to resolve build task's name against language-specific tasks.
187 fn start_session(
188 &self,
189 definition: DebugScenario,
190 task_context: SharedTaskContext,
191 active_buffer: Option<Entity<Buffer>>,
192 worktree_id: Option<WorktreeId>,
193 window: &mut Window,
194 cx: &mut App,
195 );
196
197 fn spawn_task_or_modal(
198 &self,
199 workspace: &mut Workspace,
200 action: &Spawn,
201 window: &mut Window,
202 cx: &mut Context<Workspace>,
203 );
204
205 fn task_scheduled(&self, cx: &mut App);
206 fn debug_scenario_scheduled(&self, cx: &mut App);
207 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
208
209 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
210}
211
212/// Opens a file or directory.
213#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
214#[action(namespace = workspace)]
215pub struct Open {
216 /// When true, opens in a new window. When false, adds to the current
217 /// window as a new workspace (multi-workspace).
218 #[serde(default = "Open::default_create_new_window")]
219 pub create_new_window: bool,
220}
221
222impl Open {
223 pub const DEFAULT: Self = Self {
224 create_new_window: true,
225 };
226
227 /// Used by `#[serde(default)]` on the `create_new_window` field so that
228 /// the serde default and `Open::DEFAULT` stay in sync.
229 fn default_create_new_window() -> bool {
230 Self::DEFAULT.create_new_window
231 }
232}
233
234impl Default for Open {
235 fn default() -> Self {
236 Self::DEFAULT
237 }
238}
239
240actions!(
241 workspace,
242 [
243 /// Activates the next pane in the workspace.
244 ActivateNextPane,
245 /// Activates the previous pane in the workspace.
246 ActivatePreviousPane,
247 /// Activates the last pane in the workspace.
248 ActivateLastPane,
249 /// Switches to the next window.
250 ActivateNextWindow,
251 /// Switches to the previous window.
252 ActivatePreviousWindow,
253 /// Adds a folder to the current project.
254 AddFolderToProject,
255 /// Clears all notifications.
256 ClearAllNotifications,
257 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
258 ClearNavigationHistory,
259 /// Closes the active dock.
260 CloseActiveDock,
261 /// Closes all docks.
262 CloseAllDocks,
263 /// Toggles all docks.
264 ToggleAllDocks,
265 /// Closes the current window.
266 CloseWindow,
267 /// Closes the current project.
268 CloseProject,
269 /// Opens the feedback dialog.
270 Feedback,
271 /// Follows the next collaborator in the session.
272 FollowNextCollaborator,
273 /// Moves the focused panel to the next position.
274 MoveFocusedPanelToNextPosition,
275 /// Creates a new file.
276 NewFile,
277 /// Creates a new file in a vertical split.
278 NewFileSplitVertical,
279 /// Creates a new file in a horizontal split.
280 NewFileSplitHorizontal,
281 /// Opens a new search.
282 NewSearch,
283 /// Opens a new window.
284 NewWindow,
285 /// Opens multiple files.
286 OpenFiles,
287 /// Opens the current location in terminal.
288 OpenInTerminal,
289 /// Opens the component preview.
290 OpenComponentPreview,
291 /// Reloads the active item.
292 ReloadActiveItem,
293 /// Resets the active dock to its default size.
294 ResetActiveDockSize,
295 /// Resets all open docks to their default sizes.
296 ResetOpenDocksSize,
297 /// Reloads the application
298 Reload,
299 /// Saves the current file with a new name.
300 SaveAs,
301 /// Saves without formatting.
302 SaveWithoutFormat,
303 /// Shuts down all debug adapters.
304 ShutdownDebugAdapters,
305 /// Suppresses the current notification.
306 SuppressNotification,
307 /// Toggles the bottom dock.
308 ToggleBottomDock,
309 /// Toggles centered layout mode.
310 ToggleCenteredLayout,
311 /// Toggles edit prediction feature globally for all files.
312 ToggleEditPrediction,
313 /// Toggles the left dock.
314 ToggleLeftDock,
315 /// Toggles the right dock.
316 ToggleRightDock,
317 /// Toggles zoom on the active pane.
318 ToggleZoom,
319 /// Toggles read-only mode for the active item (if supported by that item).
320 ToggleReadOnlyFile,
321 /// Zooms in on the active pane.
322 ZoomIn,
323 /// Zooms out of the active pane.
324 ZoomOut,
325 /// If any worktrees are in restricted mode, shows a modal with possible actions.
326 /// If the modal is shown already, closes it without trusting any worktree.
327 ToggleWorktreeSecurity,
328 /// Clears all trusted worktrees, placing them in restricted mode on next open.
329 /// Requires restart to take effect on already opened projects.
330 ClearTrustedWorktrees,
331 /// Stops following a collaborator.
332 Unfollow,
333 /// Restores the banner.
334 RestoreBanner,
335 /// Toggles expansion of the selected item.
336 ToggleExpandItem,
337 ]
338);
339
340/// Activates a specific pane by its index.
341#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
342#[action(namespace = workspace)]
343pub struct ActivatePane(pub usize);
344
345/// Moves an item to a specific pane by index.
346#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
347#[action(namespace = workspace)]
348#[serde(deny_unknown_fields)]
349pub struct MoveItemToPane {
350 #[serde(default = "default_1")]
351 pub destination: usize,
352 #[serde(default = "default_true")]
353 pub focus: bool,
354 #[serde(default)]
355 pub clone: bool,
356}
357
358fn default_1() -> usize {
359 1
360}
361
362/// Moves an item to a pane in the specified direction.
363#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
364#[action(namespace = workspace)]
365#[serde(deny_unknown_fields)]
366pub struct MoveItemToPaneInDirection {
367 #[serde(default = "default_right")]
368 pub direction: SplitDirection,
369 #[serde(default = "default_true")]
370 pub focus: bool,
371 #[serde(default)]
372 pub clone: bool,
373}
374
375/// Creates a new file in a split of the desired direction.
376#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
377#[action(namespace = workspace)]
378#[serde(deny_unknown_fields)]
379pub struct NewFileSplit(pub SplitDirection);
380
381fn default_right() -> SplitDirection {
382 SplitDirection::Right
383}
384
385/// Saves all open files in the workspace.
386#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
387#[action(namespace = workspace)]
388#[serde(deny_unknown_fields)]
389pub struct SaveAll {
390 #[serde(default)]
391 pub save_intent: Option<SaveIntent>,
392}
393
394/// Saves the current file with the specified options.
395#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
396#[action(namespace = workspace)]
397#[serde(deny_unknown_fields)]
398pub struct Save {
399 #[serde(default)]
400 pub save_intent: Option<SaveIntent>,
401}
402
403/// Moves Focus to the central panes in the workspace.
404#[derive(Clone, Debug, PartialEq, Eq, Action)]
405#[action(namespace = workspace)]
406pub struct FocusCenterPane;
407
408/// Closes all items and panes in the workspace.
409#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
410#[action(namespace = workspace)]
411#[serde(deny_unknown_fields)]
412pub struct CloseAllItemsAndPanes {
413 #[serde(default)]
414 pub save_intent: Option<SaveIntent>,
415}
416
417/// Closes all inactive tabs and panes in the workspace.
418#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
419#[action(namespace = workspace)]
420#[serde(deny_unknown_fields)]
421pub struct CloseInactiveTabsAndPanes {
422 #[serde(default)]
423 pub save_intent: Option<SaveIntent>,
424}
425
426/// Closes the active item across all panes.
427#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
428#[action(namespace = workspace)]
429#[serde(deny_unknown_fields)]
430pub struct CloseItemInAllPanes {
431 #[serde(default)]
432 pub save_intent: Option<SaveIntent>,
433 #[serde(default)]
434 pub close_pinned: bool,
435}
436
437/// Sends a sequence of keystrokes to the active element.
438#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
439#[action(namespace = workspace)]
440pub struct SendKeystrokes(pub String);
441
442actions!(
443 project_symbols,
444 [
445 /// Toggles the project symbols search.
446 #[action(name = "Toggle")]
447 ToggleProjectSymbols
448 ]
449);
450
451/// Toggles the file finder interface.
452#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
453#[action(namespace = file_finder, name = "Toggle")]
454#[serde(deny_unknown_fields)]
455pub struct ToggleFileFinder {
456 #[serde(default)]
457 pub separate_history: bool,
458}
459
460/// Opens a new terminal in the center.
461#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
462#[action(namespace = workspace)]
463#[serde(deny_unknown_fields)]
464pub struct NewCenterTerminal {
465 /// If true, creates a local terminal even in remote projects.
466 #[serde(default)]
467 pub local: bool,
468}
469
470/// Opens a new terminal.
471#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
472#[action(namespace = workspace)]
473#[serde(deny_unknown_fields)]
474pub struct NewTerminal {
475 /// If true, creates a local terminal even in remote projects.
476 #[serde(default)]
477 pub local: bool,
478}
479
480/// Increases size of a currently focused dock by a given amount of pixels.
481#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
482#[action(namespace = workspace)]
483#[serde(deny_unknown_fields)]
484pub struct IncreaseActiveDockSize {
485 /// For 0px parameter, uses UI font size value.
486 #[serde(default)]
487 pub px: u32,
488}
489
490/// Decreases size of a currently focused dock by a given amount of pixels.
491#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
492#[action(namespace = workspace)]
493#[serde(deny_unknown_fields)]
494pub struct DecreaseActiveDockSize {
495 /// For 0px parameter, uses UI font size value.
496 #[serde(default)]
497 pub px: u32,
498}
499
500/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
501#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
502#[action(namespace = workspace)]
503#[serde(deny_unknown_fields)]
504pub struct IncreaseOpenDocksSize {
505 /// For 0px parameter, uses UI font size value.
506 #[serde(default)]
507 pub px: u32,
508}
509
510/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
511#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
512#[action(namespace = workspace)]
513#[serde(deny_unknown_fields)]
514pub struct DecreaseOpenDocksSize {
515 /// For 0px parameter, uses UI font size value.
516 #[serde(default)]
517 pub px: u32,
518}
519
520actions!(
521 workspace,
522 [
523 /// Activates the pane to the left.
524 ActivatePaneLeft,
525 /// Activates the pane to the right.
526 ActivatePaneRight,
527 /// Activates the pane above.
528 ActivatePaneUp,
529 /// Activates the pane below.
530 ActivatePaneDown,
531 /// Swaps the current pane with the one to the left.
532 SwapPaneLeft,
533 /// Swaps the current pane with the one to the right.
534 SwapPaneRight,
535 /// Swaps the current pane with the one above.
536 SwapPaneUp,
537 /// Swaps the current pane with the one below.
538 SwapPaneDown,
539 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
540 SwapPaneAdjacent,
541 /// Move the current pane to be at the far left.
542 MovePaneLeft,
543 /// Move the current pane to be at the far right.
544 MovePaneRight,
545 /// Move the current pane to be at the very top.
546 MovePaneUp,
547 /// Move the current pane to be at the very bottom.
548 MovePaneDown,
549 ]
550);
551
552#[derive(PartialEq, Eq, Debug)]
553pub enum CloseIntent {
554 /// Quit the program entirely.
555 Quit,
556 /// Close a window.
557 CloseWindow,
558 /// Replace the workspace in an existing window.
559 ReplaceWindow,
560}
561
562#[derive(Clone)]
563pub struct Toast {
564 id: NotificationId,
565 msg: Cow<'static, str>,
566 autohide: bool,
567 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
568}
569
570impl Toast {
571 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
572 Toast {
573 id,
574 msg: msg.into(),
575 on_click: None,
576 autohide: false,
577 }
578 }
579
580 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
581 where
582 M: Into<Cow<'static, str>>,
583 F: Fn(&mut Window, &mut App) + 'static,
584 {
585 self.on_click = Some((message.into(), Arc::new(on_click)));
586 self
587 }
588
589 pub fn autohide(mut self) -> Self {
590 self.autohide = true;
591 self
592 }
593}
594
595impl PartialEq for Toast {
596 fn eq(&self, other: &Self) -> bool {
597 self.id == other.id
598 && self.msg == other.msg
599 && self.on_click.is_some() == other.on_click.is_some()
600 }
601}
602
603/// Opens a new terminal with the specified working directory.
604#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
605#[action(namespace = workspace)]
606#[serde(deny_unknown_fields)]
607pub struct OpenTerminal {
608 pub working_directory: PathBuf,
609 /// If true, creates a local terminal even in remote projects.
610 #[serde(default)]
611 pub local: bool,
612}
613
614#[derive(
615 Clone,
616 Copy,
617 Debug,
618 Default,
619 Hash,
620 PartialEq,
621 Eq,
622 PartialOrd,
623 Ord,
624 serde::Serialize,
625 serde::Deserialize,
626)]
627pub struct WorkspaceId(i64);
628
629impl WorkspaceId {
630 pub fn from_i64(value: i64) -> Self {
631 Self(value)
632 }
633}
634
635impl StaticColumnCount for WorkspaceId {}
636impl Bind for WorkspaceId {
637 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
638 self.0.bind(statement, start_index)
639 }
640}
641impl Column for WorkspaceId {
642 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
643 i64::column(statement, start_index)
644 .map(|(i, next_index)| (Self(i), next_index))
645 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
646 }
647}
648impl From<WorkspaceId> for i64 {
649 fn from(val: WorkspaceId) -> Self {
650 val.0
651 }
652}
653
654fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
655 if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
656 workspace_window
657 .update(cx, |multi_workspace, window, cx| {
658 let workspace = multi_workspace.workspace().clone();
659 workspace.update(cx, |workspace, cx| {
660 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
661 });
662 })
663 .ok();
664 } else {
665 let task = Workspace::new_local(Vec::new(), app_state.clone(), None, None, None, true, cx);
666 cx.spawn(async move |cx| {
667 let OpenResult { window, .. } = task.await?;
668 window.update(cx, |multi_workspace, window, cx| {
669 window.activate_window();
670 let workspace = multi_workspace.workspace().clone();
671 workspace.update(cx, |workspace, cx| {
672 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
673 });
674 })?;
675 anyhow::Ok(())
676 })
677 .detach_and_log_err(cx);
678 }
679}
680
681pub fn prompt_for_open_path_and_open(
682 workspace: &mut Workspace,
683 app_state: Arc<AppState>,
684 options: PathPromptOptions,
685 create_new_window: bool,
686 window: &mut Window,
687 cx: &mut Context<Workspace>,
688) {
689 let paths = workspace.prompt_for_open_path(
690 options,
691 DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
692 window,
693 cx,
694 );
695 let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
696 cx.spawn_in(window, async move |this, cx| {
697 let Some(paths) = paths.await.log_err().flatten() else {
698 return;
699 };
700 if !create_new_window {
701 if let Some(handle) = multi_workspace_handle {
702 if let Some(task) = handle
703 .update(cx, |multi_workspace, window, cx| {
704 multi_workspace.open_project(paths, window, cx)
705 })
706 .log_err()
707 {
708 task.await.log_err();
709 }
710 return;
711 }
712 }
713 if let Some(task) = this
714 .update_in(cx, |this, window, cx| {
715 this.open_workspace_for_paths(false, paths, window, cx)
716 })
717 .log_err()
718 {
719 task.await.log_err();
720 }
721 })
722 .detach();
723}
724
725pub fn init(app_state: Arc<AppState>, cx: &mut App) {
726 component::init();
727 theme_preview::init(cx);
728 toast_layer::init(cx);
729 history_manager::init(app_state.fs.clone(), cx);
730
731 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
732 .on_action(|_: &Reload, cx| reload(cx))
733 .on_action({
734 let app_state = Arc::downgrade(&app_state);
735 move |_: &Open, cx: &mut App| {
736 if let Some(app_state) = app_state.upgrade() {
737 prompt_and_open_paths(
738 app_state,
739 PathPromptOptions {
740 files: true,
741 directories: true,
742 multiple: true,
743 prompt: None,
744 },
745 cx,
746 );
747 }
748 }
749 })
750 .on_action({
751 let app_state = Arc::downgrade(&app_state);
752 move |_: &OpenFiles, cx: &mut App| {
753 let directories = cx.can_select_mixed_files_and_dirs();
754 if let Some(app_state) = app_state.upgrade() {
755 prompt_and_open_paths(
756 app_state,
757 PathPromptOptions {
758 files: true,
759 directories,
760 multiple: true,
761 prompt: None,
762 },
763 cx,
764 );
765 }
766 }
767 });
768}
769
770type BuildProjectItemFn =
771 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
772
773type BuildProjectItemForPathFn =
774 fn(
775 &Entity<Project>,
776 &ProjectPath,
777 &mut Window,
778 &mut App,
779 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
780
781#[derive(Clone, Default)]
782struct ProjectItemRegistry {
783 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
784 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
785}
786
787impl ProjectItemRegistry {
788 fn register<T: ProjectItem>(&mut self) {
789 self.build_project_item_fns_by_type.insert(
790 TypeId::of::<T::Item>(),
791 |item, project, pane, window, cx| {
792 let item = item.downcast().unwrap();
793 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
794 as Box<dyn ItemHandle>
795 },
796 );
797 self.build_project_item_for_path_fns
798 .push(|project, project_path, window, cx| {
799 let project_path = project_path.clone();
800 let is_file = project
801 .read(cx)
802 .entry_for_path(&project_path, cx)
803 .is_some_and(|entry| entry.is_file());
804 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
805 let is_local = project.read(cx).is_local();
806 let project_item =
807 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
808 let project = project.clone();
809 Some(window.spawn(cx, async move |cx| {
810 match project_item.await.with_context(|| {
811 format!(
812 "opening project path {:?}",
813 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
814 )
815 }) {
816 Ok(project_item) => {
817 let project_item = project_item;
818 let project_entry_id: Option<ProjectEntryId> =
819 project_item.read_with(cx, project::ProjectItem::entry_id);
820 let build_workspace_item = Box::new(
821 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
822 Box::new(cx.new(|cx| {
823 T::for_project_item(
824 project,
825 Some(pane),
826 project_item,
827 window,
828 cx,
829 )
830 })) as Box<dyn ItemHandle>
831 },
832 ) as Box<_>;
833 Ok((project_entry_id, build_workspace_item))
834 }
835 Err(e) => {
836 log::warn!("Failed to open a project item: {e:#}");
837 if e.error_code() == ErrorCode::Internal {
838 if let Some(abs_path) =
839 entry_abs_path.as_deref().filter(|_| is_file)
840 {
841 if let Some(broken_project_item_view) =
842 cx.update(|window, cx| {
843 T::for_broken_project_item(
844 abs_path, is_local, &e, window, cx,
845 )
846 })?
847 {
848 let build_workspace_item = Box::new(
849 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
850 cx.new(|_| broken_project_item_view).boxed_clone()
851 },
852 )
853 as Box<_>;
854 return Ok((None, build_workspace_item));
855 }
856 }
857 }
858 Err(e)
859 }
860 }
861 }))
862 });
863 }
864
865 fn open_path(
866 &self,
867 project: &Entity<Project>,
868 path: &ProjectPath,
869 window: &mut Window,
870 cx: &mut App,
871 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
872 let Some(open_project_item) = self
873 .build_project_item_for_path_fns
874 .iter()
875 .rev()
876 .find_map(|open_project_item| open_project_item(project, path, window, cx))
877 else {
878 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
879 };
880 open_project_item
881 }
882
883 fn build_item<T: project::ProjectItem>(
884 &self,
885 item: Entity<T>,
886 project: Entity<Project>,
887 pane: Option<&Pane>,
888 window: &mut Window,
889 cx: &mut App,
890 ) -> Option<Box<dyn ItemHandle>> {
891 let build = self
892 .build_project_item_fns_by_type
893 .get(&TypeId::of::<T>())?;
894 Some(build(item.into_any(), project, pane, window, cx))
895 }
896}
897
898type WorkspaceItemBuilder =
899 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
900
901impl Global for ProjectItemRegistry {}
902
903/// Registers a [ProjectItem] for the app. When opening a file, all the registered
904/// items will get a chance to open the file, starting from the project item that
905/// was added last.
906pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
907 cx.default_global::<ProjectItemRegistry>().register::<I>();
908}
909
910#[derive(Default)]
911pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
912
913struct FollowableViewDescriptor {
914 from_state_proto: fn(
915 Entity<Workspace>,
916 ViewId,
917 &mut Option<proto::view::Variant>,
918 &mut Window,
919 &mut App,
920 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
921 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
922}
923
924impl Global for FollowableViewRegistry {}
925
926impl FollowableViewRegistry {
927 pub fn register<I: FollowableItem>(cx: &mut App) {
928 cx.default_global::<Self>().0.insert(
929 TypeId::of::<I>(),
930 FollowableViewDescriptor {
931 from_state_proto: |workspace, id, state, window, cx| {
932 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
933 cx.foreground_executor()
934 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
935 })
936 },
937 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
938 },
939 );
940 }
941
942 pub fn from_state_proto(
943 workspace: Entity<Workspace>,
944 view_id: ViewId,
945 mut state: Option<proto::view::Variant>,
946 window: &mut Window,
947 cx: &mut App,
948 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
949 cx.update_default_global(|this: &mut Self, cx| {
950 this.0.values().find_map(|descriptor| {
951 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
952 })
953 })
954 }
955
956 pub fn to_followable_view(
957 view: impl Into<AnyView>,
958 cx: &App,
959 ) -> Option<Box<dyn FollowableItemHandle>> {
960 let this = cx.try_global::<Self>()?;
961 let view = view.into();
962 let descriptor = this.0.get(&view.entity_type())?;
963 Some((descriptor.to_followable_view)(&view))
964 }
965}
966
967#[derive(Copy, Clone)]
968struct SerializableItemDescriptor {
969 deserialize: fn(
970 Entity<Project>,
971 WeakEntity<Workspace>,
972 WorkspaceId,
973 ItemId,
974 &mut Window,
975 &mut Context<Pane>,
976 ) -> Task<Result<Box<dyn ItemHandle>>>,
977 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
978 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
979}
980
981#[derive(Default)]
982struct SerializableItemRegistry {
983 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
984 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
985}
986
987impl Global for SerializableItemRegistry {}
988
989impl SerializableItemRegistry {
990 fn deserialize(
991 item_kind: &str,
992 project: Entity<Project>,
993 workspace: WeakEntity<Workspace>,
994 workspace_id: WorkspaceId,
995 item_item: ItemId,
996 window: &mut Window,
997 cx: &mut Context<Pane>,
998 ) -> Task<Result<Box<dyn ItemHandle>>> {
999 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1000 return Task::ready(Err(anyhow!(
1001 "cannot deserialize {}, descriptor not found",
1002 item_kind
1003 )));
1004 };
1005
1006 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
1007 }
1008
1009 fn cleanup(
1010 item_kind: &str,
1011 workspace_id: WorkspaceId,
1012 loaded_items: Vec<ItemId>,
1013 window: &mut Window,
1014 cx: &mut App,
1015 ) -> Task<Result<()>> {
1016 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1017 return Task::ready(Err(anyhow!(
1018 "cannot cleanup {}, descriptor not found",
1019 item_kind
1020 )));
1021 };
1022
1023 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
1024 }
1025
1026 fn view_to_serializable_item_handle(
1027 view: AnyView,
1028 cx: &App,
1029 ) -> Option<Box<dyn SerializableItemHandle>> {
1030 let this = cx.try_global::<Self>()?;
1031 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
1032 Some((descriptor.view_to_serializable_item)(view))
1033 }
1034
1035 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
1036 let this = cx.try_global::<Self>()?;
1037 this.descriptors_by_kind.get(item_kind).copied()
1038 }
1039}
1040
1041pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
1042 let serialized_item_kind = I::serialized_item_kind();
1043
1044 let registry = cx.default_global::<SerializableItemRegistry>();
1045 let descriptor = SerializableItemDescriptor {
1046 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
1047 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
1048 cx.foreground_executor()
1049 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
1050 },
1051 cleanup: |workspace_id, loaded_items, window, cx| {
1052 I::cleanup(workspace_id, loaded_items, window, cx)
1053 },
1054 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
1055 };
1056 registry
1057 .descriptors_by_kind
1058 .insert(Arc::from(serialized_item_kind), descriptor);
1059 registry
1060 .descriptors_by_type
1061 .insert(TypeId::of::<I>(), descriptor);
1062}
1063
1064pub struct AppState {
1065 pub languages: Arc<LanguageRegistry>,
1066 pub client: Arc<Client>,
1067 pub user_store: Entity<UserStore>,
1068 pub workspace_store: Entity<WorkspaceStore>,
1069 pub fs: Arc<dyn fs::Fs>,
1070 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1071 pub node_runtime: NodeRuntime,
1072 pub session: Entity<AppSession>,
1073}
1074
1075struct GlobalAppState(Weak<AppState>);
1076
1077impl Global for GlobalAppState {}
1078
1079pub struct WorkspaceStore {
1080 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1081 client: Arc<Client>,
1082 _subscriptions: Vec<client::Subscription>,
1083}
1084
1085#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1086pub enum CollaboratorId {
1087 PeerId(PeerId),
1088 Agent,
1089}
1090
1091impl From<PeerId> for CollaboratorId {
1092 fn from(peer_id: PeerId) -> Self {
1093 CollaboratorId::PeerId(peer_id)
1094 }
1095}
1096
1097impl From<&PeerId> for CollaboratorId {
1098 fn from(peer_id: &PeerId) -> Self {
1099 CollaboratorId::PeerId(*peer_id)
1100 }
1101}
1102
1103#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1104struct Follower {
1105 project_id: Option<u64>,
1106 peer_id: PeerId,
1107}
1108
1109impl AppState {
1110 #[track_caller]
1111 pub fn global(cx: &App) -> Weak<Self> {
1112 cx.global::<GlobalAppState>().0.clone()
1113 }
1114 pub fn try_global(cx: &App) -> Option<Weak<Self>> {
1115 cx.try_global::<GlobalAppState>()
1116 .map(|state| state.0.clone())
1117 }
1118 pub fn set_global(state: Weak<AppState>, cx: &mut App) {
1119 cx.set_global(GlobalAppState(state));
1120 }
1121
1122 #[cfg(any(test, feature = "test-support"))]
1123 pub fn test(cx: &mut App) -> Arc<Self> {
1124 use fs::Fs;
1125 use node_runtime::NodeRuntime;
1126 use session::Session;
1127 use settings::SettingsStore;
1128
1129 if !cx.has_global::<SettingsStore>() {
1130 let settings_store = SettingsStore::test(cx);
1131 cx.set_global(settings_store);
1132 }
1133
1134 let fs = fs::FakeFs::new(cx.background_executor().clone());
1135 <dyn Fs>::set_global(fs.clone(), cx);
1136 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1137 let clock = Arc::new(clock::FakeSystemClock::new());
1138 let http_client = http_client::FakeHttpClient::with_404_response();
1139 let client = Client::new(clock, http_client, cx);
1140 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1141 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1142 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1143
1144 theme::init(theme::LoadThemes::JustBase, cx);
1145 client::init(&client, cx);
1146
1147 Arc::new(Self {
1148 client,
1149 fs,
1150 languages,
1151 user_store,
1152 workspace_store,
1153 node_runtime: NodeRuntime::unavailable(),
1154 build_window_options: |_, _| Default::default(),
1155 session,
1156 })
1157 }
1158}
1159
1160struct DelayedDebouncedEditAction {
1161 task: Option<Task<()>>,
1162 cancel_channel: Option<oneshot::Sender<()>>,
1163}
1164
1165impl DelayedDebouncedEditAction {
1166 fn new() -> DelayedDebouncedEditAction {
1167 DelayedDebouncedEditAction {
1168 task: None,
1169 cancel_channel: None,
1170 }
1171 }
1172
1173 fn fire_new<F>(
1174 &mut self,
1175 delay: Duration,
1176 window: &mut Window,
1177 cx: &mut Context<Workspace>,
1178 func: F,
1179 ) where
1180 F: 'static
1181 + Send
1182 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1183 {
1184 if let Some(channel) = self.cancel_channel.take() {
1185 _ = channel.send(());
1186 }
1187
1188 let (sender, mut receiver) = oneshot::channel::<()>();
1189 self.cancel_channel = Some(sender);
1190
1191 let previous_task = self.task.take();
1192 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1193 let mut timer = cx.background_executor().timer(delay).fuse();
1194 if let Some(previous_task) = previous_task {
1195 previous_task.await;
1196 }
1197
1198 futures::select_biased! {
1199 _ = receiver => return,
1200 _ = timer => {}
1201 }
1202
1203 if let Some(result) = workspace
1204 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1205 .log_err()
1206 {
1207 result.await.log_err();
1208 }
1209 }));
1210 }
1211}
1212
1213pub enum Event {
1214 PaneAdded(Entity<Pane>),
1215 PaneRemoved,
1216 ItemAdded {
1217 item: Box<dyn ItemHandle>,
1218 },
1219 ActiveItemChanged,
1220 ItemRemoved {
1221 item_id: EntityId,
1222 },
1223 UserSavedItem {
1224 pane: WeakEntity<Pane>,
1225 item: Box<dyn WeakItemHandle>,
1226 save_intent: SaveIntent,
1227 },
1228 ContactRequestedJoin(u64),
1229 WorkspaceCreated(WeakEntity<Workspace>),
1230 OpenBundledFile {
1231 text: Cow<'static, str>,
1232 title: &'static str,
1233 language: &'static str,
1234 },
1235 ZoomChanged,
1236 ModalOpened,
1237 Activate,
1238 PanelAdded(AnyView),
1239}
1240
1241#[derive(Debug, Clone)]
1242pub enum OpenVisible {
1243 All,
1244 None,
1245 OnlyFiles,
1246 OnlyDirectories,
1247}
1248
1249enum WorkspaceLocation {
1250 // Valid local paths or SSH project to serialize
1251 Location(SerializedWorkspaceLocation, PathList),
1252 // No valid location found hence clear session id
1253 DetachFromSession,
1254 // No valid location found to serialize
1255 None,
1256}
1257
1258type PromptForNewPath = Box<
1259 dyn Fn(
1260 &mut Workspace,
1261 DirectoryLister,
1262 Option<String>,
1263 &mut Window,
1264 &mut Context<Workspace>,
1265 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1266>;
1267
1268type PromptForOpenPath = Box<
1269 dyn Fn(
1270 &mut Workspace,
1271 DirectoryLister,
1272 &mut Window,
1273 &mut Context<Workspace>,
1274 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1275>;
1276
1277#[derive(Default)]
1278struct DispatchingKeystrokes {
1279 dispatched: HashSet<Vec<Keystroke>>,
1280 queue: VecDeque<Keystroke>,
1281 task: Option<Shared<Task<()>>>,
1282}
1283
1284/// Collects everything project-related for a certain window opened.
1285/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1286///
1287/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1288/// The `Workspace` owns everybody's state and serves as a default, "global context",
1289/// that can be used to register a global action to be triggered from any place in the window.
1290pub struct Workspace {
1291 weak_self: WeakEntity<Self>,
1292 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1293 zoomed: Option<AnyWeakView>,
1294 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1295 zoomed_position: Option<DockPosition>,
1296 center: PaneGroup,
1297 left_dock: Entity<Dock>,
1298 bottom_dock: Entity<Dock>,
1299 right_dock: Entity<Dock>,
1300 panes: Vec<Entity<Pane>>,
1301 active_worktree_override: Option<WorktreeId>,
1302 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1303 active_pane: Entity<Pane>,
1304 last_active_center_pane: Option<WeakEntity<Pane>>,
1305 last_active_view_id: Option<proto::ViewId>,
1306 status_bar: Entity<StatusBar>,
1307 pub(crate) modal_layer: Entity<ModalLayer>,
1308 toast_layer: Entity<ToastLayer>,
1309 titlebar_item: Option<AnyView>,
1310 notifications: Notifications,
1311 suppressed_notifications: HashSet<NotificationId>,
1312 project: Entity<Project>,
1313 follower_states: HashMap<CollaboratorId, FollowerState>,
1314 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1315 window_edited: bool,
1316 last_window_title: Option<String>,
1317 dirty_items: HashMap<EntityId, Subscription>,
1318 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1319 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1320 database_id: Option<WorkspaceId>,
1321 app_state: Arc<AppState>,
1322 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1323 _subscriptions: Vec<Subscription>,
1324 _apply_leader_updates: Task<Result<()>>,
1325 _observe_current_user: Task<Result<()>>,
1326 _schedule_serialize_workspace: Option<Task<()>>,
1327 _serialize_workspace_task: Option<Task<()>>,
1328 _schedule_serialize_ssh_paths: Option<Task<()>>,
1329 pane_history_timestamp: Arc<AtomicUsize>,
1330 bounds: Bounds<Pixels>,
1331 pub centered_layout: bool,
1332 bounds_save_task_queued: Option<Task<()>>,
1333 on_prompt_for_new_path: Option<PromptForNewPath>,
1334 on_prompt_for_open_path: Option<PromptForOpenPath>,
1335 terminal_provider: Option<Box<dyn TerminalProvider>>,
1336 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1337 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1338 _items_serializer: Task<Result<()>>,
1339 session_id: Option<String>,
1340 scheduled_tasks: Vec<Task<()>>,
1341 last_open_dock_positions: Vec<DockPosition>,
1342 removing: bool,
1343 _panels_task: Option<Task<Result<()>>>,
1344 sidebar_focus_handle: Option<FocusHandle>,
1345}
1346
1347impl EventEmitter<Event> for Workspace {}
1348
1349#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1350pub struct ViewId {
1351 pub creator: CollaboratorId,
1352 pub id: u64,
1353}
1354
1355pub struct FollowerState {
1356 center_pane: Entity<Pane>,
1357 dock_pane: Option<Entity<Pane>>,
1358 active_view_id: Option<ViewId>,
1359 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1360}
1361
1362struct FollowerView {
1363 view: Box<dyn FollowableItemHandle>,
1364 location: Option<proto::PanelId>,
1365}
1366
1367impl Workspace {
1368 pub fn new(
1369 workspace_id: Option<WorkspaceId>,
1370 project: Entity<Project>,
1371 app_state: Arc<AppState>,
1372 window: &mut Window,
1373 cx: &mut Context<Self>,
1374 ) -> Self {
1375 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1376 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1377 if let TrustedWorktreesEvent::Trusted(..) = e {
1378 // Do not persist auto trusted worktrees
1379 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1380 worktrees_store.update(cx, |worktrees_store, cx| {
1381 worktrees_store.schedule_serialization(
1382 cx,
1383 |new_trusted_worktrees, cx| {
1384 let timeout =
1385 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1386 let db = WorkspaceDb::global(cx);
1387 cx.background_spawn(async move {
1388 timeout.await;
1389 db.save_trusted_worktrees(new_trusted_worktrees)
1390 .await
1391 .log_err();
1392 })
1393 },
1394 )
1395 });
1396 }
1397 }
1398 })
1399 .detach();
1400
1401 cx.observe_global::<SettingsStore>(|_, cx| {
1402 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1403 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1404 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1405 trusted_worktrees.auto_trust_all(cx);
1406 })
1407 }
1408 }
1409 })
1410 .detach();
1411 }
1412
1413 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1414 match event {
1415 project::Event::RemoteIdChanged(_) => {
1416 this.update_window_title(window, cx);
1417 }
1418
1419 project::Event::CollaboratorLeft(peer_id) => {
1420 this.collaborator_left(*peer_id, window, cx);
1421 }
1422
1423 &project::Event::WorktreeRemoved(_) => {
1424 this.update_window_title(window, cx);
1425 this.serialize_workspace(window, cx);
1426 this.update_history(cx);
1427 }
1428
1429 &project::Event::WorktreeAdded(id) => {
1430 this.update_window_title(window, cx);
1431 if this
1432 .project()
1433 .read(cx)
1434 .worktree_for_id(id, cx)
1435 .is_some_and(|wt| wt.read(cx).is_visible())
1436 {
1437 this.serialize_workspace(window, cx);
1438 this.update_history(cx);
1439 }
1440 }
1441 project::Event::WorktreeUpdatedEntries(..) => {
1442 this.update_window_title(window, cx);
1443 this.serialize_workspace(window, cx);
1444 }
1445
1446 project::Event::DisconnectedFromHost => {
1447 this.update_window_edited(window, cx);
1448 let leaders_to_unfollow =
1449 this.follower_states.keys().copied().collect::<Vec<_>>();
1450 for leader_id in leaders_to_unfollow {
1451 this.unfollow(leader_id, window, cx);
1452 }
1453 }
1454
1455 project::Event::DisconnectedFromRemote {
1456 server_not_running: _,
1457 } => {
1458 this.update_window_edited(window, cx);
1459 }
1460
1461 project::Event::Closed => {
1462 window.remove_window();
1463 }
1464
1465 project::Event::DeletedEntry(_, entry_id) => {
1466 for pane in this.panes.iter() {
1467 pane.update(cx, |pane, cx| {
1468 pane.handle_deleted_project_item(*entry_id, window, cx)
1469 });
1470 }
1471 }
1472
1473 project::Event::Toast {
1474 notification_id,
1475 message,
1476 link,
1477 } => this.show_notification(
1478 NotificationId::named(notification_id.clone()),
1479 cx,
1480 |cx| {
1481 let mut notification = MessageNotification::new(message.clone(), cx);
1482 if let Some(link) = link {
1483 notification = notification
1484 .more_info_message(link.label)
1485 .more_info_url(link.url);
1486 }
1487
1488 cx.new(|_| notification)
1489 },
1490 ),
1491
1492 project::Event::HideToast { notification_id } => {
1493 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1494 }
1495
1496 project::Event::LanguageServerPrompt(request) => {
1497 struct LanguageServerPrompt;
1498
1499 this.show_notification(
1500 NotificationId::composite::<LanguageServerPrompt>(request.id),
1501 cx,
1502 |cx| {
1503 cx.new(|cx| {
1504 notifications::LanguageServerPrompt::new(request.clone(), cx)
1505 })
1506 },
1507 );
1508 }
1509
1510 project::Event::AgentLocationChanged => {
1511 this.handle_agent_location_changed(window, cx)
1512 }
1513
1514 _ => {}
1515 }
1516 cx.notify()
1517 })
1518 .detach();
1519
1520 cx.subscribe_in(
1521 &project.read(cx).breakpoint_store(),
1522 window,
1523 |workspace, _, event, window, cx| match event {
1524 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1525 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1526 workspace.serialize_workspace(window, cx);
1527 }
1528 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1529 },
1530 )
1531 .detach();
1532 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1533 cx.subscribe_in(
1534 &toolchain_store,
1535 window,
1536 |workspace, _, event, window, cx| match event {
1537 ToolchainStoreEvent::CustomToolchainsModified => {
1538 workspace.serialize_workspace(window, cx);
1539 }
1540 _ => {}
1541 },
1542 )
1543 .detach();
1544 }
1545
1546 cx.on_focus_lost(window, |this, window, cx| {
1547 let focus_handle = this.focus_handle(cx);
1548 window.focus(&focus_handle, cx);
1549 })
1550 .detach();
1551
1552 let weak_handle = cx.entity().downgrade();
1553 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1554
1555 let center_pane = cx.new(|cx| {
1556 let mut center_pane = Pane::new(
1557 weak_handle.clone(),
1558 project.clone(),
1559 pane_history_timestamp.clone(),
1560 None,
1561 NewFile.boxed_clone(),
1562 true,
1563 window,
1564 cx,
1565 );
1566 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1567 center_pane.set_should_display_welcome_page(true);
1568 center_pane
1569 });
1570 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1571 .detach();
1572
1573 window.focus(¢er_pane.focus_handle(cx), cx);
1574
1575 cx.emit(Event::PaneAdded(center_pane.clone()));
1576
1577 let any_window_handle = window.window_handle();
1578 app_state.workspace_store.update(cx, |store, _| {
1579 store
1580 .workspaces
1581 .insert((any_window_handle, weak_handle.clone()));
1582 });
1583
1584 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1585 let mut connection_status = app_state.client.status();
1586 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1587 current_user.next().await;
1588 connection_status.next().await;
1589 let mut stream =
1590 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1591
1592 while stream.recv().await.is_some() {
1593 this.update(cx, |_, cx| cx.notify())?;
1594 }
1595 anyhow::Ok(())
1596 });
1597
1598 // All leader updates are enqueued and then processed in a single task, so
1599 // that each asynchronous operation can be run in order.
1600 let (leader_updates_tx, mut leader_updates_rx) =
1601 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1602 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1603 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1604 Self::process_leader_update(&this, leader_id, update, cx)
1605 .await
1606 .log_err();
1607 }
1608
1609 Ok(())
1610 });
1611
1612 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1613 let modal_layer = cx.new(|_| ModalLayer::new());
1614 let toast_layer = cx.new(|_| ToastLayer::new());
1615 cx.subscribe(
1616 &modal_layer,
1617 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1618 cx.emit(Event::ModalOpened);
1619 },
1620 )
1621 .detach();
1622
1623 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1624 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1625 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1626 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1627 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1628 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1629 let status_bar = cx.new(|cx| {
1630 let mut status_bar = StatusBar::new(¢er_pane.clone(), window, cx);
1631 status_bar.add_left_item(left_dock_buttons, window, cx);
1632 status_bar.add_right_item(right_dock_buttons, window, cx);
1633 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1634 status_bar
1635 });
1636
1637 let session_id = app_state.session.read(cx).id().to_owned();
1638
1639 let mut active_call = None;
1640 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1641 let subscriptions =
1642 vec![
1643 call.0
1644 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1645 ];
1646 active_call = Some((call, subscriptions));
1647 }
1648
1649 let (serializable_items_tx, serializable_items_rx) =
1650 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1651 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1652 Self::serialize_items(&this, serializable_items_rx, cx).await
1653 });
1654
1655 let subscriptions = vec![
1656 cx.observe_window_activation(window, Self::on_window_activation_changed),
1657 cx.observe_window_bounds(window, move |this, window, cx| {
1658 if this.bounds_save_task_queued.is_some() {
1659 return;
1660 }
1661 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1662 cx.background_executor()
1663 .timer(Duration::from_millis(100))
1664 .await;
1665 this.update_in(cx, |this, window, cx| {
1666 this.save_window_bounds(window, cx).detach();
1667 this.bounds_save_task_queued.take();
1668 })
1669 .ok();
1670 }));
1671 cx.notify();
1672 }),
1673 cx.observe_window_appearance(window, |_, window, cx| {
1674 let window_appearance = window.appearance();
1675
1676 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1677
1678 GlobalTheme::reload_theme(cx);
1679 GlobalTheme::reload_icon_theme(cx);
1680 }),
1681 cx.on_release({
1682 let weak_handle = weak_handle.clone();
1683 move |this, cx| {
1684 this.app_state.workspace_store.update(cx, move |store, _| {
1685 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1686 })
1687 }
1688 }),
1689 ];
1690
1691 cx.defer_in(window, move |this, window, cx| {
1692 this.update_window_title(window, cx);
1693 this.show_initial_notifications(cx);
1694 });
1695
1696 let mut center = PaneGroup::new(center_pane.clone());
1697 center.set_is_center(true);
1698 center.mark_positions(cx);
1699
1700 Workspace {
1701 weak_self: weak_handle.clone(),
1702 zoomed: None,
1703 zoomed_position: None,
1704 previous_dock_drag_coordinates: None,
1705 center,
1706 panes: vec![center_pane.clone()],
1707 panes_by_item: Default::default(),
1708 active_pane: center_pane.clone(),
1709 last_active_center_pane: Some(center_pane.downgrade()),
1710 last_active_view_id: None,
1711 status_bar,
1712 modal_layer,
1713 toast_layer,
1714 titlebar_item: None,
1715 active_worktree_override: None,
1716 notifications: Notifications::default(),
1717 suppressed_notifications: HashSet::default(),
1718 left_dock,
1719 bottom_dock,
1720 right_dock,
1721 _panels_task: None,
1722 project: project.clone(),
1723 follower_states: Default::default(),
1724 last_leaders_by_pane: Default::default(),
1725 dispatching_keystrokes: Default::default(),
1726 window_edited: false,
1727 last_window_title: None,
1728 dirty_items: Default::default(),
1729 active_call,
1730 database_id: workspace_id,
1731 app_state,
1732 _observe_current_user,
1733 _apply_leader_updates,
1734 _schedule_serialize_workspace: None,
1735 _serialize_workspace_task: None,
1736 _schedule_serialize_ssh_paths: None,
1737 leader_updates_tx,
1738 _subscriptions: subscriptions,
1739 pane_history_timestamp,
1740 workspace_actions: Default::default(),
1741 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1742 bounds: Default::default(),
1743 centered_layout: false,
1744 bounds_save_task_queued: None,
1745 on_prompt_for_new_path: None,
1746 on_prompt_for_open_path: None,
1747 terminal_provider: None,
1748 debugger_provider: None,
1749 serializable_items_tx,
1750 _items_serializer,
1751 session_id: Some(session_id),
1752
1753 scheduled_tasks: Vec::new(),
1754 last_open_dock_positions: Vec::new(),
1755 removing: false,
1756 sidebar_focus_handle: None,
1757 }
1758 }
1759
1760 pub fn new_local(
1761 abs_paths: Vec<PathBuf>,
1762 app_state: Arc<AppState>,
1763 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1764 env: Option<HashMap<String, String>>,
1765 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1766 activate: bool,
1767 cx: &mut App,
1768 ) -> Task<anyhow::Result<OpenResult>> {
1769 let project_handle = Project::local(
1770 app_state.client.clone(),
1771 app_state.node_runtime.clone(),
1772 app_state.user_store.clone(),
1773 app_state.languages.clone(),
1774 app_state.fs.clone(),
1775 env,
1776 Default::default(),
1777 cx,
1778 );
1779
1780 let db = WorkspaceDb::global(cx);
1781 let kvp = db::kvp::KeyValueStore::global(cx);
1782 cx.spawn(async move |cx| {
1783 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1784 for path in abs_paths.into_iter() {
1785 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1786 paths_to_open.push(canonical)
1787 } else {
1788 paths_to_open.push(path)
1789 }
1790 }
1791
1792 let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
1793
1794 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1795 paths_to_open = paths.ordered_paths().cloned().collect();
1796 if !paths.is_lexicographically_ordered() {
1797 project_handle.update(cx, |project, cx| {
1798 project.set_worktrees_reordered(true, cx);
1799 });
1800 }
1801 }
1802
1803 // Get project paths for all of the abs_paths
1804 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1805 Vec::with_capacity(paths_to_open.len());
1806
1807 for path in paths_to_open.into_iter() {
1808 if let Some((_, project_entry)) = cx
1809 .update(|cx| {
1810 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1811 })
1812 .await
1813 .log_err()
1814 {
1815 project_paths.push((path, Some(project_entry)));
1816 } else {
1817 project_paths.push((path, None));
1818 }
1819 }
1820
1821 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1822 serialized_workspace.id
1823 } else {
1824 db.next_id().await.unwrap_or_else(|_| Default::default())
1825 };
1826
1827 let toolchains = db.toolchains(workspace_id).await?;
1828
1829 for (toolchain, worktree_path, path) in toolchains {
1830 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1831 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1832 this.find_worktree(&worktree_path, cx)
1833 .and_then(|(worktree, rel_path)| {
1834 if rel_path.is_empty() {
1835 Some(worktree.read(cx).id())
1836 } else {
1837 None
1838 }
1839 })
1840 }) else {
1841 // We did not find a worktree with a given path, but that's whatever.
1842 continue;
1843 };
1844 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1845 continue;
1846 }
1847
1848 project_handle
1849 .update(cx, |this, cx| {
1850 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1851 })
1852 .await;
1853 }
1854 if let Some(workspace) = serialized_workspace.as_ref() {
1855 project_handle.update(cx, |this, cx| {
1856 for (scope, toolchains) in &workspace.user_toolchains {
1857 for toolchain in toolchains {
1858 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1859 }
1860 }
1861 });
1862 }
1863
1864 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1865 if let Some(window) = requesting_window {
1866 let centered_layout = serialized_workspace
1867 .as_ref()
1868 .map(|w| w.centered_layout)
1869 .unwrap_or(false);
1870
1871 let workspace = window.update(cx, |multi_workspace, window, cx| {
1872 let workspace = cx.new(|cx| {
1873 let mut workspace = Workspace::new(
1874 Some(workspace_id),
1875 project_handle.clone(),
1876 app_state.clone(),
1877 window,
1878 cx,
1879 );
1880
1881 workspace.centered_layout = centered_layout;
1882
1883 // Call init callback to add items before window renders
1884 if let Some(init) = init {
1885 init(&mut workspace, window, cx);
1886 }
1887
1888 workspace
1889 });
1890 if activate {
1891 multi_workspace.activate(workspace.clone(), cx);
1892 } else {
1893 multi_workspace.add_workspace(workspace.clone(), cx);
1894 }
1895 workspace
1896 })?;
1897 (window, workspace)
1898 } else {
1899 let window_bounds_override = window_bounds_env_override();
1900
1901 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1902 (Some(WindowBounds::Windowed(bounds)), None)
1903 } else if let Some(workspace) = serialized_workspace.as_ref()
1904 && let Some(display) = workspace.display
1905 && let Some(bounds) = workspace.window_bounds.as_ref()
1906 {
1907 // Reopening an existing workspace - restore its saved bounds
1908 (Some(bounds.0), Some(display))
1909 } else if let Some((display, bounds)) =
1910 persistence::read_default_window_bounds(&kvp)
1911 {
1912 // New or empty workspace - use the last known window bounds
1913 (Some(bounds), Some(display))
1914 } else {
1915 // New window - let GPUI's default_bounds() handle cascading
1916 (None, None)
1917 };
1918
1919 // Use the serialized workspace to construct the new window
1920 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1921 options.window_bounds = window_bounds;
1922 let centered_layout = serialized_workspace
1923 .as_ref()
1924 .map(|w| w.centered_layout)
1925 .unwrap_or(false);
1926 let window = cx.open_window(options, {
1927 let app_state = app_state.clone();
1928 let project_handle = project_handle.clone();
1929 move |window, cx| {
1930 let workspace = cx.new(|cx| {
1931 let mut workspace = Workspace::new(
1932 Some(workspace_id),
1933 project_handle,
1934 app_state,
1935 window,
1936 cx,
1937 );
1938 workspace.centered_layout = centered_layout;
1939
1940 // Call init callback to add items before window renders
1941 if let Some(init) = init {
1942 init(&mut workspace, window, cx);
1943 }
1944
1945 workspace
1946 });
1947 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1948 }
1949 })?;
1950 let workspace =
1951 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
1952 multi_workspace.workspace().clone()
1953 })?;
1954 (window, workspace)
1955 };
1956
1957 notify_if_database_failed(window, cx);
1958 // Check if this is an empty workspace (no paths to open)
1959 // An empty workspace is one where project_paths is empty
1960 let is_empty_workspace = project_paths.is_empty();
1961 // Check if serialized workspace has paths before it's moved
1962 let serialized_workspace_has_paths = serialized_workspace
1963 .as_ref()
1964 .map(|ws| !ws.paths.is_empty())
1965 .unwrap_or(false);
1966
1967 let opened_items = window
1968 .update(cx, |_, window, cx| {
1969 workspace.update(cx, |_workspace: &mut Workspace, cx| {
1970 open_items(serialized_workspace, project_paths, window, cx)
1971 })
1972 })?
1973 .await
1974 .unwrap_or_default();
1975
1976 // Restore default dock state for empty workspaces
1977 // Only restore if:
1978 // 1. This is an empty workspace (no paths), AND
1979 // 2. The serialized workspace either doesn't exist or has no paths
1980 if is_empty_workspace && !serialized_workspace_has_paths {
1981 if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
1982 window
1983 .update(cx, |_, window, cx| {
1984 workspace.update(cx, |workspace, cx| {
1985 for (dock, serialized_dock) in [
1986 (&workspace.right_dock, &default_docks.right),
1987 (&workspace.left_dock, &default_docks.left),
1988 (&workspace.bottom_dock, &default_docks.bottom),
1989 ] {
1990 dock.update(cx, |dock, cx| {
1991 dock.serialized_dock = Some(serialized_dock.clone());
1992 dock.restore_state(window, cx);
1993 });
1994 }
1995 cx.notify();
1996 });
1997 })
1998 .log_err();
1999 }
2000 }
2001
2002 window
2003 .update(cx, |_, _window, cx| {
2004 workspace.update(cx, |this: &mut Workspace, cx| {
2005 this.update_history(cx);
2006 });
2007 })
2008 .log_err();
2009 Ok(OpenResult {
2010 window,
2011 workspace,
2012 opened_items,
2013 })
2014 })
2015 }
2016
2017 pub fn weak_handle(&self) -> WeakEntity<Self> {
2018 self.weak_self.clone()
2019 }
2020
2021 pub fn left_dock(&self) -> &Entity<Dock> {
2022 &self.left_dock
2023 }
2024
2025 pub fn bottom_dock(&self) -> &Entity<Dock> {
2026 &self.bottom_dock
2027 }
2028
2029 pub fn set_bottom_dock_layout(
2030 &mut self,
2031 layout: BottomDockLayout,
2032 window: &mut Window,
2033 cx: &mut Context<Self>,
2034 ) {
2035 let fs = self.project().read(cx).fs();
2036 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2037 content.workspace.bottom_dock_layout = Some(layout);
2038 });
2039
2040 cx.notify();
2041 self.serialize_workspace(window, cx);
2042 }
2043
2044 pub fn right_dock(&self) -> &Entity<Dock> {
2045 &self.right_dock
2046 }
2047
2048 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2049 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2050 }
2051
2052 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2053 let left_dock = self.left_dock.read(cx);
2054 let left_visible = left_dock.is_open();
2055 let left_active_panel = left_dock
2056 .active_panel()
2057 .map(|panel| panel.persistent_name().to_string());
2058 // `zoomed_position` is kept in sync with individual panel zoom state
2059 // by the dock code in `Dock::new` and `Dock::add_panel`.
2060 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2061
2062 let right_dock = self.right_dock.read(cx);
2063 let right_visible = right_dock.is_open();
2064 let right_active_panel = right_dock
2065 .active_panel()
2066 .map(|panel| panel.persistent_name().to_string());
2067 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2068
2069 let bottom_dock = self.bottom_dock.read(cx);
2070 let bottom_visible = bottom_dock.is_open();
2071 let bottom_active_panel = bottom_dock
2072 .active_panel()
2073 .map(|panel| panel.persistent_name().to_string());
2074 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2075
2076 DockStructure {
2077 left: DockData {
2078 visible: left_visible,
2079 active_panel: left_active_panel,
2080 zoom: left_dock_zoom,
2081 },
2082 right: DockData {
2083 visible: right_visible,
2084 active_panel: right_active_panel,
2085 zoom: right_dock_zoom,
2086 },
2087 bottom: DockData {
2088 visible: bottom_visible,
2089 active_panel: bottom_active_panel,
2090 zoom: bottom_dock_zoom,
2091 },
2092 }
2093 }
2094
2095 pub fn set_dock_structure(
2096 &self,
2097 docks: DockStructure,
2098 window: &mut Window,
2099 cx: &mut Context<Self>,
2100 ) {
2101 for (dock, data) in [
2102 (&self.left_dock, docks.left),
2103 (&self.bottom_dock, docks.bottom),
2104 (&self.right_dock, docks.right),
2105 ] {
2106 dock.update(cx, |dock, cx| {
2107 dock.serialized_dock = Some(data);
2108 dock.restore_state(window, cx);
2109 });
2110 }
2111 }
2112
2113 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2114 self.items(cx)
2115 .filter_map(|item| {
2116 let project_path = item.project_path(cx)?;
2117 self.project.read(cx).absolute_path(&project_path, cx)
2118 })
2119 .collect()
2120 }
2121
2122 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2123 match position {
2124 DockPosition::Left => &self.left_dock,
2125 DockPosition::Bottom => &self.bottom_dock,
2126 DockPosition::Right => &self.right_dock,
2127 }
2128 }
2129
2130 pub fn is_edited(&self) -> bool {
2131 self.window_edited
2132 }
2133
2134 pub fn add_panel<T: Panel>(
2135 &mut self,
2136 panel: Entity<T>,
2137 window: &mut Window,
2138 cx: &mut Context<Self>,
2139 ) {
2140 let focus_handle = panel.panel_focus_handle(cx);
2141 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2142 .detach();
2143
2144 let dock_position = panel.position(window, cx);
2145 let dock = self.dock_at_position(dock_position);
2146 let any_panel = panel.to_any();
2147
2148 dock.update(cx, |dock, cx| {
2149 dock.add_panel(panel, self.weak_self.clone(), window, cx)
2150 });
2151
2152 cx.emit(Event::PanelAdded(any_panel));
2153 }
2154
2155 pub fn remove_panel<T: Panel>(
2156 &mut self,
2157 panel: &Entity<T>,
2158 window: &mut Window,
2159 cx: &mut Context<Self>,
2160 ) {
2161 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2162 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2163 }
2164 }
2165
2166 pub fn status_bar(&self) -> &Entity<StatusBar> {
2167 &self.status_bar
2168 }
2169
2170 pub fn set_workspace_sidebar_open(
2171 &mut self,
2172 open: bool,
2173 has_notifications: bool,
2174 show_toggle: bool,
2175 cx: &mut App,
2176 ) {
2177 self.status_bar.update(cx, |status_bar, cx| {
2178 status_bar.set_workspace_sidebar_open(open, cx);
2179 status_bar.set_sidebar_has_notifications(has_notifications, cx);
2180 status_bar.set_show_sidebar_toggle(show_toggle, cx);
2181 });
2182 }
2183
2184 pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
2185 self.sidebar_focus_handle = handle;
2186 }
2187
2188 pub fn status_bar_visible(&self, cx: &App) -> bool {
2189 StatusBarSettings::get_global(cx).show
2190 }
2191
2192 pub fn app_state(&self) -> &Arc<AppState> {
2193 &self.app_state
2194 }
2195
2196 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2197 self._panels_task = Some(task);
2198 }
2199
2200 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2201 self._panels_task.take()
2202 }
2203
2204 pub fn user_store(&self) -> &Entity<UserStore> {
2205 &self.app_state.user_store
2206 }
2207
2208 pub fn project(&self) -> &Entity<Project> {
2209 &self.project
2210 }
2211
2212 pub fn path_style(&self, cx: &App) -> PathStyle {
2213 self.project.read(cx).path_style(cx)
2214 }
2215
2216 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2217 let mut history: HashMap<EntityId, usize> = HashMap::default();
2218
2219 for pane_handle in &self.panes {
2220 let pane = pane_handle.read(cx);
2221
2222 for entry in pane.activation_history() {
2223 history.insert(
2224 entry.entity_id,
2225 history
2226 .get(&entry.entity_id)
2227 .cloned()
2228 .unwrap_or(0)
2229 .max(entry.timestamp),
2230 );
2231 }
2232 }
2233
2234 history
2235 }
2236
2237 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2238 let mut recent_item: Option<Entity<T>> = None;
2239 let mut recent_timestamp = 0;
2240 for pane_handle in &self.panes {
2241 let pane = pane_handle.read(cx);
2242 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2243 pane.items().map(|item| (item.item_id(), item)).collect();
2244 for entry in pane.activation_history() {
2245 if entry.timestamp > recent_timestamp
2246 && let Some(&item) = item_map.get(&entry.entity_id)
2247 && let Some(typed_item) = item.act_as::<T>(cx)
2248 {
2249 recent_timestamp = entry.timestamp;
2250 recent_item = Some(typed_item);
2251 }
2252 }
2253 }
2254 recent_item
2255 }
2256
2257 pub fn recent_navigation_history_iter(
2258 &self,
2259 cx: &App,
2260 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2261 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2262 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2263
2264 for pane in &self.panes {
2265 let pane = pane.read(cx);
2266
2267 pane.nav_history()
2268 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2269 if let Some(fs_path) = &fs_path {
2270 abs_paths_opened
2271 .entry(fs_path.clone())
2272 .or_default()
2273 .insert(project_path.clone());
2274 }
2275 let timestamp = entry.timestamp;
2276 match history.entry(project_path) {
2277 hash_map::Entry::Occupied(mut entry) => {
2278 let (_, old_timestamp) = entry.get();
2279 if ×tamp > old_timestamp {
2280 entry.insert((fs_path, timestamp));
2281 }
2282 }
2283 hash_map::Entry::Vacant(entry) => {
2284 entry.insert((fs_path, timestamp));
2285 }
2286 }
2287 });
2288
2289 if let Some(item) = pane.active_item()
2290 && let Some(project_path) = item.project_path(cx)
2291 {
2292 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2293
2294 if let Some(fs_path) = &fs_path {
2295 abs_paths_opened
2296 .entry(fs_path.clone())
2297 .or_default()
2298 .insert(project_path.clone());
2299 }
2300
2301 history.insert(project_path, (fs_path, std::usize::MAX));
2302 }
2303 }
2304
2305 history
2306 .into_iter()
2307 .sorted_by_key(|(_, (_, order))| *order)
2308 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2309 .rev()
2310 .filter(move |(history_path, abs_path)| {
2311 let latest_project_path_opened = abs_path
2312 .as_ref()
2313 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2314 .and_then(|project_paths| {
2315 project_paths
2316 .iter()
2317 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2318 });
2319
2320 latest_project_path_opened.is_none_or(|path| path == history_path)
2321 })
2322 }
2323
2324 pub fn recent_navigation_history(
2325 &self,
2326 limit: Option<usize>,
2327 cx: &App,
2328 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2329 self.recent_navigation_history_iter(cx)
2330 .take(limit.unwrap_or(usize::MAX))
2331 .collect()
2332 }
2333
2334 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2335 for pane in &self.panes {
2336 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2337 }
2338 }
2339
2340 fn navigate_history(
2341 &mut self,
2342 pane: WeakEntity<Pane>,
2343 mode: NavigationMode,
2344 window: &mut Window,
2345 cx: &mut Context<Workspace>,
2346 ) -> Task<Result<()>> {
2347 self.navigate_history_impl(
2348 pane,
2349 mode,
2350 window,
2351 &mut |history, cx| history.pop(mode, cx),
2352 cx,
2353 )
2354 }
2355
2356 fn navigate_tag_history(
2357 &mut self,
2358 pane: WeakEntity<Pane>,
2359 mode: TagNavigationMode,
2360 window: &mut Window,
2361 cx: &mut Context<Workspace>,
2362 ) -> Task<Result<()>> {
2363 self.navigate_history_impl(
2364 pane,
2365 NavigationMode::Normal,
2366 window,
2367 &mut |history, _cx| history.pop_tag(mode),
2368 cx,
2369 )
2370 }
2371
2372 fn navigate_history_impl(
2373 &mut self,
2374 pane: WeakEntity<Pane>,
2375 mode: NavigationMode,
2376 window: &mut Window,
2377 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2378 cx: &mut Context<Workspace>,
2379 ) -> Task<Result<()>> {
2380 let to_load = if let Some(pane) = pane.upgrade() {
2381 pane.update(cx, |pane, cx| {
2382 window.focus(&pane.focus_handle(cx), cx);
2383 loop {
2384 // Retrieve the weak item handle from the history.
2385 let entry = cb(pane.nav_history_mut(), cx)?;
2386
2387 // If the item is still present in this pane, then activate it.
2388 if let Some(index) = entry
2389 .item
2390 .upgrade()
2391 .and_then(|v| pane.index_for_item(v.as_ref()))
2392 {
2393 let prev_active_item_index = pane.active_item_index();
2394 pane.nav_history_mut().set_mode(mode);
2395 pane.activate_item(index, true, true, window, cx);
2396 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2397
2398 let mut navigated = prev_active_item_index != pane.active_item_index();
2399 if let Some(data) = entry.data {
2400 navigated |= pane.active_item()?.navigate(data, window, cx);
2401 }
2402
2403 if navigated {
2404 break None;
2405 }
2406 } else {
2407 // If the item is no longer present in this pane, then retrieve its
2408 // path info in order to reopen it.
2409 break pane
2410 .nav_history()
2411 .path_for_item(entry.item.id())
2412 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2413 }
2414 }
2415 })
2416 } else {
2417 None
2418 };
2419
2420 if let Some((project_path, abs_path, entry)) = to_load {
2421 // If the item was no longer present, then load it again from its previous path, first try the local path
2422 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2423
2424 cx.spawn_in(window, async move |workspace, cx| {
2425 let open_by_project_path = open_by_project_path.await;
2426 let mut navigated = false;
2427 match open_by_project_path
2428 .with_context(|| format!("Navigating to {project_path:?}"))
2429 {
2430 Ok((project_entry_id, build_item)) => {
2431 let prev_active_item_id = pane.update(cx, |pane, _| {
2432 pane.nav_history_mut().set_mode(mode);
2433 pane.active_item().map(|p| p.item_id())
2434 })?;
2435
2436 pane.update_in(cx, |pane, window, cx| {
2437 let item = pane.open_item(
2438 project_entry_id,
2439 project_path,
2440 true,
2441 entry.is_preview,
2442 true,
2443 None,
2444 window, cx,
2445 build_item,
2446 );
2447 navigated |= Some(item.item_id()) != prev_active_item_id;
2448 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2449 if let Some(data) = entry.data {
2450 navigated |= item.navigate(data, window, cx);
2451 }
2452 })?;
2453 }
2454 Err(open_by_project_path_e) => {
2455 // Fall back to opening by abs path, in case an external file was opened and closed,
2456 // and its worktree is now dropped
2457 if let Some(abs_path) = abs_path {
2458 let prev_active_item_id = pane.update(cx, |pane, _| {
2459 pane.nav_history_mut().set_mode(mode);
2460 pane.active_item().map(|p| p.item_id())
2461 })?;
2462 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2463 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2464 })?;
2465 match open_by_abs_path
2466 .await
2467 .with_context(|| format!("Navigating to {abs_path:?}"))
2468 {
2469 Ok(item) => {
2470 pane.update_in(cx, |pane, window, cx| {
2471 navigated |= Some(item.item_id()) != prev_active_item_id;
2472 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2473 if let Some(data) = entry.data {
2474 navigated |= item.navigate(data, window, cx);
2475 }
2476 })?;
2477 }
2478 Err(open_by_abs_path_e) => {
2479 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2480 }
2481 }
2482 }
2483 }
2484 }
2485
2486 if !navigated {
2487 workspace
2488 .update_in(cx, |workspace, window, cx| {
2489 Self::navigate_history(workspace, pane, mode, window, cx)
2490 })?
2491 .await?;
2492 }
2493
2494 Ok(())
2495 })
2496 } else {
2497 Task::ready(Ok(()))
2498 }
2499 }
2500
2501 pub fn go_back(
2502 &mut self,
2503 pane: WeakEntity<Pane>,
2504 window: &mut Window,
2505 cx: &mut Context<Workspace>,
2506 ) -> Task<Result<()>> {
2507 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2508 }
2509
2510 pub fn go_forward(
2511 &mut self,
2512 pane: WeakEntity<Pane>,
2513 window: &mut Window,
2514 cx: &mut Context<Workspace>,
2515 ) -> Task<Result<()>> {
2516 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2517 }
2518
2519 pub fn reopen_closed_item(
2520 &mut self,
2521 window: &mut Window,
2522 cx: &mut Context<Workspace>,
2523 ) -> Task<Result<()>> {
2524 self.navigate_history(
2525 self.active_pane().downgrade(),
2526 NavigationMode::ReopeningClosedItem,
2527 window,
2528 cx,
2529 )
2530 }
2531
2532 pub fn client(&self) -> &Arc<Client> {
2533 &self.app_state.client
2534 }
2535
2536 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2537 self.titlebar_item = Some(item);
2538 cx.notify();
2539 }
2540
2541 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2542 self.on_prompt_for_new_path = Some(prompt)
2543 }
2544
2545 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2546 self.on_prompt_for_open_path = Some(prompt)
2547 }
2548
2549 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2550 self.terminal_provider = Some(Box::new(provider));
2551 }
2552
2553 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2554 self.debugger_provider = Some(Arc::new(provider));
2555 }
2556
2557 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2558 self.debugger_provider.clone()
2559 }
2560
2561 pub fn prompt_for_open_path(
2562 &mut self,
2563 path_prompt_options: PathPromptOptions,
2564 lister: DirectoryLister,
2565 window: &mut Window,
2566 cx: &mut Context<Self>,
2567 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2568 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2569 let prompt = self.on_prompt_for_open_path.take().unwrap();
2570 let rx = prompt(self, lister, window, cx);
2571 self.on_prompt_for_open_path = Some(prompt);
2572 rx
2573 } else {
2574 let (tx, rx) = oneshot::channel();
2575 let abs_path = cx.prompt_for_paths(path_prompt_options);
2576
2577 cx.spawn_in(window, async move |workspace, cx| {
2578 let Ok(result) = abs_path.await else {
2579 return Ok(());
2580 };
2581
2582 match result {
2583 Ok(result) => {
2584 tx.send(result).ok();
2585 }
2586 Err(err) => {
2587 let rx = workspace.update_in(cx, |workspace, window, cx| {
2588 workspace.show_portal_error(err.to_string(), cx);
2589 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2590 let rx = prompt(workspace, lister, window, cx);
2591 workspace.on_prompt_for_open_path = Some(prompt);
2592 rx
2593 })?;
2594 if let Ok(path) = rx.await {
2595 tx.send(path).ok();
2596 }
2597 }
2598 };
2599 anyhow::Ok(())
2600 })
2601 .detach();
2602
2603 rx
2604 }
2605 }
2606
2607 pub fn prompt_for_new_path(
2608 &mut self,
2609 lister: DirectoryLister,
2610 suggested_name: Option<String>,
2611 window: &mut Window,
2612 cx: &mut Context<Self>,
2613 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2614 if self.project.read(cx).is_via_collab()
2615 || self.project.read(cx).is_via_remote_server()
2616 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2617 {
2618 let prompt = self.on_prompt_for_new_path.take().unwrap();
2619 let rx = prompt(self, lister, suggested_name, window, cx);
2620 self.on_prompt_for_new_path = Some(prompt);
2621 return rx;
2622 }
2623
2624 let (tx, rx) = oneshot::channel();
2625 cx.spawn_in(window, async move |workspace, cx| {
2626 let abs_path = workspace.update(cx, |workspace, cx| {
2627 let relative_to = workspace
2628 .most_recent_active_path(cx)
2629 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2630 .or_else(|| {
2631 let project = workspace.project.read(cx);
2632 project.visible_worktrees(cx).find_map(|worktree| {
2633 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2634 })
2635 })
2636 .or_else(std::env::home_dir)
2637 .unwrap_or_else(|| PathBuf::from(""));
2638 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2639 })?;
2640 let abs_path = match abs_path.await? {
2641 Ok(path) => path,
2642 Err(err) => {
2643 let rx = workspace.update_in(cx, |workspace, window, cx| {
2644 workspace.show_portal_error(err.to_string(), cx);
2645
2646 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2647 let rx = prompt(workspace, lister, suggested_name, window, cx);
2648 workspace.on_prompt_for_new_path = Some(prompt);
2649 rx
2650 })?;
2651 if let Ok(path) = rx.await {
2652 tx.send(path).ok();
2653 }
2654 return anyhow::Ok(());
2655 }
2656 };
2657
2658 tx.send(abs_path.map(|path| vec![path])).ok();
2659 anyhow::Ok(())
2660 })
2661 .detach();
2662
2663 rx
2664 }
2665
2666 pub fn titlebar_item(&self) -> Option<AnyView> {
2667 self.titlebar_item.clone()
2668 }
2669
2670 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2671 /// When set, git-related operations should use this worktree instead of deriving
2672 /// the active worktree from the focused file.
2673 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2674 self.active_worktree_override
2675 }
2676
2677 pub fn set_active_worktree_override(
2678 &mut self,
2679 worktree_id: Option<WorktreeId>,
2680 cx: &mut Context<Self>,
2681 ) {
2682 self.active_worktree_override = worktree_id;
2683 cx.notify();
2684 }
2685
2686 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2687 self.active_worktree_override = None;
2688 cx.notify();
2689 }
2690
2691 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2692 ///
2693 /// If the given workspace has a local project, then it will be passed
2694 /// to the callback. Otherwise, a new empty window will be created.
2695 pub fn with_local_workspace<T, F>(
2696 &mut self,
2697 window: &mut Window,
2698 cx: &mut Context<Self>,
2699 callback: F,
2700 ) -> Task<Result<T>>
2701 where
2702 T: 'static,
2703 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2704 {
2705 if self.project.read(cx).is_local() {
2706 Task::ready(Ok(callback(self, window, cx)))
2707 } else {
2708 let env = self.project.read(cx).cli_environment(cx);
2709 let task = Self::new_local(
2710 Vec::new(),
2711 self.app_state.clone(),
2712 None,
2713 env,
2714 None,
2715 true,
2716 cx,
2717 );
2718 cx.spawn_in(window, async move |_vh, cx| {
2719 let OpenResult {
2720 window: multi_workspace_window,
2721 ..
2722 } = task.await?;
2723 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2724 let workspace = multi_workspace.workspace().clone();
2725 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2726 })
2727 })
2728 }
2729 }
2730
2731 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2732 ///
2733 /// If the given workspace has a local project, then it will be passed
2734 /// to the callback. Otherwise, a new empty window will be created.
2735 pub fn with_local_or_wsl_workspace<T, F>(
2736 &mut self,
2737 window: &mut Window,
2738 cx: &mut Context<Self>,
2739 callback: F,
2740 ) -> Task<Result<T>>
2741 where
2742 T: 'static,
2743 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2744 {
2745 let project = self.project.read(cx);
2746 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
2747 Task::ready(Ok(callback(self, window, cx)))
2748 } else {
2749 let env = self.project.read(cx).cli_environment(cx);
2750 let task = Self::new_local(
2751 Vec::new(),
2752 self.app_state.clone(),
2753 None,
2754 env,
2755 None,
2756 true,
2757 cx,
2758 );
2759 cx.spawn_in(window, async move |_vh, cx| {
2760 let OpenResult {
2761 window: multi_workspace_window,
2762 ..
2763 } = task.await?;
2764 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2765 let workspace = multi_workspace.workspace().clone();
2766 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2767 })
2768 })
2769 }
2770 }
2771
2772 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2773 self.project.read(cx).worktrees(cx)
2774 }
2775
2776 pub fn visible_worktrees<'a>(
2777 &self,
2778 cx: &'a App,
2779 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2780 self.project.read(cx).visible_worktrees(cx)
2781 }
2782
2783 #[cfg(any(test, feature = "test-support"))]
2784 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
2785 let futures = self
2786 .worktrees(cx)
2787 .filter_map(|worktree| worktree.read(cx).as_local())
2788 .map(|worktree| worktree.scan_complete())
2789 .collect::<Vec<_>>();
2790 async move {
2791 for future in futures {
2792 future.await;
2793 }
2794 }
2795 }
2796
2797 pub fn close_global(cx: &mut App) {
2798 cx.defer(|cx| {
2799 cx.windows().iter().find(|window| {
2800 window
2801 .update(cx, |_, window, _| {
2802 if window.is_window_active() {
2803 //This can only get called when the window's project connection has been lost
2804 //so we don't need to prompt the user for anything and instead just close the window
2805 window.remove_window();
2806 true
2807 } else {
2808 false
2809 }
2810 })
2811 .unwrap_or(false)
2812 });
2813 });
2814 }
2815
2816 pub fn move_focused_panel_to_next_position(
2817 &mut self,
2818 _: &MoveFocusedPanelToNextPosition,
2819 window: &mut Window,
2820 cx: &mut Context<Self>,
2821 ) {
2822 let docks = self.all_docks();
2823 let active_dock = docks
2824 .into_iter()
2825 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
2826
2827 if let Some(dock) = active_dock {
2828 dock.update(cx, |dock, cx| {
2829 let active_panel = dock
2830 .active_panel()
2831 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
2832
2833 if let Some(panel) = active_panel {
2834 panel.move_to_next_position(window, cx);
2835 }
2836 })
2837 }
2838 }
2839
2840 pub fn prepare_to_close(
2841 &mut self,
2842 close_intent: CloseIntent,
2843 window: &mut Window,
2844 cx: &mut Context<Self>,
2845 ) -> Task<Result<bool>> {
2846 let active_call = self.active_global_call();
2847
2848 cx.spawn_in(window, async move |this, cx| {
2849 this.update(cx, |this, _| {
2850 if close_intent == CloseIntent::CloseWindow {
2851 this.removing = true;
2852 }
2853 })?;
2854
2855 let workspace_count = cx.update(|_window, cx| {
2856 cx.windows()
2857 .iter()
2858 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
2859 .count()
2860 })?;
2861
2862 #[cfg(target_os = "macos")]
2863 let save_last_workspace = false;
2864
2865 // On Linux and Windows, closing the last window should restore the last workspace.
2866 #[cfg(not(target_os = "macos"))]
2867 let save_last_workspace = {
2868 let remaining_workspaces = cx.update(|_window, cx| {
2869 cx.windows()
2870 .iter()
2871 .filter_map(|window| window.downcast::<MultiWorkspace>())
2872 .filter_map(|multi_workspace| {
2873 multi_workspace
2874 .update(cx, |multi_workspace, _, cx| {
2875 multi_workspace.workspace().read(cx).removing
2876 })
2877 .ok()
2878 })
2879 .filter(|removing| !removing)
2880 .count()
2881 })?;
2882
2883 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
2884 };
2885
2886 if let Some(active_call) = active_call
2887 && workspace_count == 1
2888 && cx
2889 .update(|_window, cx| active_call.0.is_in_room(cx))
2890 .unwrap_or(false)
2891 {
2892 if close_intent == CloseIntent::CloseWindow {
2893 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
2894 let answer = cx.update(|window, cx| {
2895 window.prompt(
2896 PromptLevel::Warning,
2897 "Do you want to leave the current call?",
2898 None,
2899 &["Close window and hang up", "Cancel"],
2900 cx,
2901 )
2902 })?;
2903
2904 if answer.await.log_err() == Some(1) {
2905 return anyhow::Ok(false);
2906 } else {
2907 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
2908 task.await.log_err();
2909 }
2910 }
2911 }
2912 if close_intent == CloseIntent::ReplaceWindow {
2913 _ = cx.update(|_window, cx| {
2914 let multi_workspace = cx
2915 .windows()
2916 .iter()
2917 .filter_map(|window| window.downcast::<MultiWorkspace>())
2918 .next()
2919 .unwrap();
2920 let project = multi_workspace
2921 .read(cx)?
2922 .workspace()
2923 .read(cx)
2924 .project
2925 .clone();
2926 if project.read(cx).is_shared() {
2927 active_call.0.unshare_project(project, cx)?;
2928 }
2929 Ok::<_, anyhow::Error>(())
2930 });
2931 }
2932 }
2933
2934 let save_result = this
2935 .update_in(cx, |this, window, cx| {
2936 this.save_all_internal(SaveIntent::Close, window, cx)
2937 })?
2938 .await;
2939
2940 // If we're not quitting, but closing, we remove the workspace from
2941 // the current session.
2942 if close_intent != CloseIntent::Quit
2943 && !save_last_workspace
2944 && save_result.as_ref().is_ok_and(|&res| res)
2945 {
2946 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
2947 .await;
2948 }
2949
2950 save_result
2951 })
2952 }
2953
2954 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
2955 self.save_all_internal(
2956 action.save_intent.unwrap_or(SaveIntent::SaveAll),
2957 window,
2958 cx,
2959 )
2960 .detach_and_log_err(cx);
2961 }
2962
2963 fn send_keystrokes(
2964 &mut self,
2965 action: &SendKeystrokes,
2966 window: &mut Window,
2967 cx: &mut Context<Self>,
2968 ) {
2969 let keystrokes: Vec<Keystroke> = action
2970 .0
2971 .split(' ')
2972 .flat_map(|k| Keystroke::parse(k).log_err())
2973 .map(|k| {
2974 cx.keyboard_mapper()
2975 .map_key_equivalent(k, false)
2976 .inner()
2977 .clone()
2978 })
2979 .collect();
2980 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
2981 }
2982
2983 pub fn send_keystrokes_impl(
2984 &mut self,
2985 keystrokes: Vec<Keystroke>,
2986 window: &mut Window,
2987 cx: &mut Context<Self>,
2988 ) -> Shared<Task<()>> {
2989 let mut state = self.dispatching_keystrokes.borrow_mut();
2990 if !state.dispatched.insert(keystrokes.clone()) {
2991 cx.propagate();
2992 return state.task.clone().unwrap();
2993 }
2994
2995 state.queue.extend(keystrokes);
2996
2997 let keystrokes = self.dispatching_keystrokes.clone();
2998 if state.task.is_none() {
2999 state.task = Some(
3000 window
3001 .spawn(cx, async move |cx| {
3002 // limit to 100 keystrokes to avoid infinite recursion.
3003 for _ in 0..100 {
3004 let keystroke = {
3005 let mut state = keystrokes.borrow_mut();
3006 let Some(keystroke) = state.queue.pop_front() else {
3007 state.dispatched.clear();
3008 state.task.take();
3009 return;
3010 };
3011 keystroke
3012 };
3013 cx.update(|window, cx| {
3014 let focused = window.focused(cx);
3015 window.dispatch_keystroke(keystroke.clone(), cx);
3016 if window.focused(cx) != focused {
3017 // dispatch_keystroke may cause the focus to change.
3018 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
3019 // And we need that to happen before the next keystroke to keep vim mode happy...
3020 // (Note that the tests always do this implicitly, so you must manually test with something like:
3021 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
3022 // )
3023 window.draw(cx).clear();
3024 }
3025 })
3026 .ok();
3027
3028 // Yield between synthetic keystrokes so deferred focus and
3029 // other effects can settle before dispatching the next key.
3030 yield_now().await;
3031 }
3032
3033 *keystrokes.borrow_mut() = Default::default();
3034 log::error!("over 100 keystrokes passed to send_keystrokes");
3035 })
3036 .shared(),
3037 );
3038 }
3039 state.task.clone().unwrap()
3040 }
3041
3042 fn save_all_internal(
3043 &mut self,
3044 mut save_intent: SaveIntent,
3045 window: &mut Window,
3046 cx: &mut Context<Self>,
3047 ) -> Task<Result<bool>> {
3048 if self.project.read(cx).is_disconnected(cx) {
3049 return Task::ready(Ok(true));
3050 }
3051 let dirty_items = self
3052 .panes
3053 .iter()
3054 .flat_map(|pane| {
3055 pane.read(cx).items().filter_map(|item| {
3056 if item.is_dirty(cx) {
3057 item.tab_content_text(0, cx);
3058 Some((pane.downgrade(), item.boxed_clone()))
3059 } else {
3060 None
3061 }
3062 })
3063 })
3064 .collect::<Vec<_>>();
3065
3066 let project = self.project.clone();
3067 cx.spawn_in(window, async move |workspace, cx| {
3068 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3069 let (serialize_tasks, remaining_dirty_items) =
3070 workspace.update_in(cx, |workspace, window, cx| {
3071 let mut remaining_dirty_items = Vec::new();
3072 let mut serialize_tasks = Vec::new();
3073 for (pane, item) in dirty_items {
3074 if let Some(task) = item
3075 .to_serializable_item_handle(cx)
3076 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3077 {
3078 serialize_tasks.push(task);
3079 } else {
3080 remaining_dirty_items.push((pane, item));
3081 }
3082 }
3083 (serialize_tasks, remaining_dirty_items)
3084 })?;
3085
3086 futures::future::try_join_all(serialize_tasks).await?;
3087
3088 if !remaining_dirty_items.is_empty() {
3089 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3090 }
3091
3092 if remaining_dirty_items.len() > 1 {
3093 let answer = workspace.update_in(cx, |_, window, cx| {
3094 let detail = Pane::file_names_for_prompt(
3095 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3096 cx,
3097 );
3098 window.prompt(
3099 PromptLevel::Warning,
3100 "Do you want to save all changes in the following files?",
3101 Some(&detail),
3102 &["Save all", "Discard all", "Cancel"],
3103 cx,
3104 )
3105 })?;
3106 match answer.await.log_err() {
3107 Some(0) => save_intent = SaveIntent::SaveAll,
3108 Some(1) => save_intent = SaveIntent::Skip,
3109 Some(2) => return Ok(false),
3110 _ => {}
3111 }
3112 }
3113
3114 remaining_dirty_items
3115 } else {
3116 dirty_items
3117 };
3118
3119 for (pane, item) in dirty_items {
3120 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3121 (
3122 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3123 item.project_entry_ids(cx),
3124 )
3125 })?;
3126 if (singleton || !project_entry_ids.is_empty())
3127 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3128 {
3129 return Ok(false);
3130 }
3131 }
3132 Ok(true)
3133 })
3134 }
3135
3136 pub fn open_workspace_for_paths(
3137 &mut self,
3138 replace_current_window: bool,
3139 paths: Vec<PathBuf>,
3140 window: &mut Window,
3141 cx: &mut Context<Self>,
3142 ) -> Task<Result<Entity<Workspace>>> {
3143 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
3144 let is_remote = self.project.read(cx).is_via_collab();
3145 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3146 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3147
3148 let window_to_replace = if replace_current_window {
3149 window_handle
3150 } else if is_remote || has_worktree || has_dirty_items {
3151 None
3152 } else {
3153 window_handle
3154 };
3155 let app_state = self.app_state.clone();
3156
3157 cx.spawn(async move |_, cx| {
3158 let OpenResult { workspace, .. } = cx
3159 .update(|cx| {
3160 open_paths(
3161 &paths,
3162 app_state,
3163 OpenOptions {
3164 replace_window: window_to_replace,
3165 ..Default::default()
3166 },
3167 cx,
3168 )
3169 })
3170 .await?;
3171 Ok(workspace)
3172 })
3173 }
3174
3175 #[allow(clippy::type_complexity)]
3176 pub fn open_paths(
3177 &mut self,
3178 mut abs_paths: Vec<PathBuf>,
3179 options: OpenOptions,
3180 pane: Option<WeakEntity<Pane>>,
3181 window: &mut Window,
3182 cx: &mut Context<Self>,
3183 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3184 let fs = self.app_state.fs.clone();
3185
3186 let caller_ordered_abs_paths = abs_paths.clone();
3187
3188 // Sort the paths to ensure we add worktrees for parents before their children.
3189 abs_paths.sort_unstable();
3190 cx.spawn_in(window, async move |this, cx| {
3191 let mut tasks = Vec::with_capacity(abs_paths.len());
3192
3193 for abs_path in &abs_paths {
3194 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3195 OpenVisible::All => Some(true),
3196 OpenVisible::None => Some(false),
3197 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3198 Some(Some(metadata)) => Some(!metadata.is_dir),
3199 Some(None) => Some(true),
3200 None => None,
3201 },
3202 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3203 Some(Some(metadata)) => Some(metadata.is_dir),
3204 Some(None) => Some(false),
3205 None => None,
3206 },
3207 };
3208 let project_path = match visible {
3209 Some(visible) => match this
3210 .update(cx, |this, cx| {
3211 Workspace::project_path_for_path(
3212 this.project.clone(),
3213 abs_path,
3214 visible,
3215 cx,
3216 )
3217 })
3218 .log_err()
3219 {
3220 Some(project_path) => project_path.await.log_err(),
3221 None => None,
3222 },
3223 None => None,
3224 };
3225
3226 let this = this.clone();
3227 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3228 let fs = fs.clone();
3229 let pane = pane.clone();
3230 let task = cx.spawn(async move |cx| {
3231 let (_worktree, project_path) = project_path?;
3232 if fs.is_dir(&abs_path).await {
3233 // Opening a directory should not race to update the active entry.
3234 // We'll select/reveal a deterministic final entry after all paths finish opening.
3235 None
3236 } else {
3237 Some(
3238 this.update_in(cx, |this, window, cx| {
3239 this.open_path(
3240 project_path,
3241 pane,
3242 options.focus.unwrap_or(true),
3243 window,
3244 cx,
3245 )
3246 })
3247 .ok()?
3248 .await,
3249 )
3250 }
3251 });
3252 tasks.push(task);
3253 }
3254
3255 let results = futures::future::join_all(tasks).await;
3256
3257 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3258 let mut winner: Option<(PathBuf, bool)> = None;
3259 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3260 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3261 if !metadata.is_dir {
3262 winner = Some((abs_path, false));
3263 break;
3264 }
3265 if winner.is_none() {
3266 winner = Some((abs_path, true));
3267 }
3268 } else if winner.is_none() {
3269 winner = Some((abs_path, false));
3270 }
3271 }
3272
3273 // Compute the winner entry id on the foreground thread and emit once, after all
3274 // paths finish opening. This avoids races between concurrently-opening paths
3275 // (directories in particular) and makes the resulting project panel selection
3276 // deterministic.
3277 if let Some((winner_abs_path, winner_is_dir)) = winner {
3278 'emit_winner: {
3279 let winner_abs_path: Arc<Path> =
3280 SanitizedPath::new(&winner_abs_path).as_path().into();
3281
3282 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3283 OpenVisible::All => true,
3284 OpenVisible::None => false,
3285 OpenVisible::OnlyFiles => !winner_is_dir,
3286 OpenVisible::OnlyDirectories => winner_is_dir,
3287 };
3288
3289 let Some(worktree_task) = this
3290 .update(cx, |workspace, cx| {
3291 workspace.project.update(cx, |project, cx| {
3292 project.find_or_create_worktree(
3293 winner_abs_path.as_ref(),
3294 visible,
3295 cx,
3296 )
3297 })
3298 })
3299 .ok()
3300 else {
3301 break 'emit_winner;
3302 };
3303
3304 let Ok((worktree, _)) = worktree_task.await else {
3305 break 'emit_winner;
3306 };
3307
3308 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3309 let worktree = worktree.read(cx);
3310 let worktree_abs_path = worktree.abs_path();
3311 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3312 worktree.root_entry()
3313 } else {
3314 winner_abs_path
3315 .strip_prefix(worktree_abs_path.as_ref())
3316 .ok()
3317 .and_then(|relative_path| {
3318 let relative_path =
3319 RelPath::new(relative_path, PathStyle::local())
3320 .log_err()?;
3321 worktree.entry_for_path(&relative_path)
3322 })
3323 }?;
3324 Some(entry.id)
3325 }) else {
3326 break 'emit_winner;
3327 };
3328
3329 this.update(cx, |workspace, cx| {
3330 workspace.project.update(cx, |_, cx| {
3331 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3332 });
3333 })
3334 .ok();
3335 }
3336 }
3337
3338 results
3339 })
3340 }
3341
3342 pub fn open_resolved_path(
3343 &mut self,
3344 path: ResolvedPath,
3345 window: &mut Window,
3346 cx: &mut Context<Self>,
3347 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3348 match path {
3349 ResolvedPath::ProjectPath { project_path, .. } => {
3350 self.open_path(project_path, None, true, window, cx)
3351 }
3352 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3353 PathBuf::from(path),
3354 OpenOptions {
3355 visible: Some(OpenVisible::None),
3356 ..Default::default()
3357 },
3358 window,
3359 cx,
3360 ),
3361 }
3362 }
3363
3364 pub fn absolute_path_of_worktree(
3365 &self,
3366 worktree_id: WorktreeId,
3367 cx: &mut Context<Self>,
3368 ) -> Option<PathBuf> {
3369 self.project
3370 .read(cx)
3371 .worktree_for_id(worktree_id, cx)
3372 // TODO: use `abs_path` or `root_dir`
3373 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3374 }
3375
3376 pub fn add_folder_to_project(
3377 &mut self,
3378 _: &AddFolderToProject,
3379 window: &mut Window,
3380 cx: &mut Context<Self>,
3381 ) {
3382 let project = self.project.read(cx);
3383 if project.is_via_collab() {
3384 self.show_error(
3385 &anyhow!("You cannot add folders to someone else's project"),
3386 cx,
3387 );
3388 return;
3389 }
3390 let paths = self.prompt_for_open_path(
3391 PathPromptOptions {
3392 files: false,
3393 directories: true,
3394 multiple: true,
3395 prompt: None,
3396 },
3397 DirectoryLister::Project(self.project.clone()),
3398 window,
3399 cx,
3400 );
3401 cx.spawn_in(window, async move |this, cx| {
3402 if let Some(paths) = paths.await.log_err().flatten() {
3403 let results = this
3404 .update_in(cx, |this, window, cx| {
3405 this.open_paths(
3406 paths,
3407 OpenOptions {
3408 visible: Some(OpenVisible::All),
3409 ..Default::default()
3410 },
3411 None,
3412 window,
3413 cx,
3414 )
3415 })?
3416 .await;
3417 for result in results.into_iter().flatten() {
3418 result.log_err();
3419 }
3420 }
3421 anyhow::Ok(())
3422 })
3423 .detach_and_log_err(cx);
3424 }
3425
3426 pub fn project_path_for_path(
3427 project: Entity<Project>,
3428 abs_path: &Path,
3429 visible: bool,
3430 cx: &mut App,
3431 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3432 let entry = project.update(cx, |project, cx| {
3433 project.find_or_create_worktree(abs_path, visible, cx)
3434 });
3435 cx.spawn(async move |cx| {
3436 let (worktree, path) = entry.await?;
3437 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3438 Ok((worktree, ProjectPath { worktree_id, path }))
3439 })
3440 }
3441
3442 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3443 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3444 }
3445
3446 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3447 self.items_of_type(cx).max_by_key(|item| item.item_id())
3448 }
3449
3450 pub fn items_of_type<'a, T: Item>(
3451 &'a self,
3452 cx: &'a App,
3453 ) -> impl 'a + Iterator<Item = Entity<T>> {
3454 self.panes
3455 .iter()
3456 .flat_map(|pane| pane.read(cx).items_of_type())
3457 }
3458
3459 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3460 self.active_pane().read(cx).active_item()
3461 }
3462
3463 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3464 let item = self.active_item(cx)?;
3465 item.to_any_view().downcast::<I>().ok()
3466 }
3467
3468 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3469 self.active_item(cx).and_then(|item| item.project_path(cx))
3470 }
3471
3472 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3473 self.recent_navigation_history_iter(cx)
3474 .filter_map(|(path, abs_path)| {
3475 let worktree = self
3476 .project
3477 .read(cx)
3478 .worktree_for_id(path.worktree_id, cx)?;
3479 if worktree.read(cx).is_visible() {
3480 abs_path
3481 } else {
3482 None
3483 }
3484 })
3485 .next()
3486 }
3487
3488 pub fn save_active_item(
3489 &mut self,
3490 save_intent: SaveIntent,
3491 window: &mut Window,
3492 cx: &mut App,
3493 ) -> Task<Result<()>> {
3494 let project = self.project.clone();
3495 let pane = self.active_pane();
3496 let item = pane.read(cx).active_item();
3497 let pane = pane.downgrade();
3498
3499 window.spawn(cx, async move |cx| {
3500 if let Some(item) = item {
3501 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3502 .await
3503 .map(|_| ())
3504 } else {
3505 Ok(())
3506 }
3507 })
3508 }
3509
3510 pub fn close_inactive_items_and_panes(
3511 &mut self,
3512 action: &CloseInactiveTabsAndPanes,
3513 window: &mut Window,
3514 cx: &mut Context<Self>,
3515 ) {
3516 if let Some(task) = self.close_all_internal(
3517 true,
3518 action.save_intent.unwrap_or(SaveIntent::Close),
3519 window,
3520 cx,
3521 ) {
3522 task.detach_and_log_err(cx)
3523 }
3524 }
3525
3526 pub fn close_all_items_and_panes(
3527 &mut self,
3528 action: &CloseAllItemsAndPanes,
3529 window: &mut Window,
3530 cx: &mut Context<Self>,
3531 ) {
3532 if let Some(task) = self.close_all_internal(
3533 false,
3534 action.save_intent.unwrap_or(SaveIntent::Close),
3535 window,
3536 cx,
3537 ) {
3538 task.detach_and_log_err(cx)
3539 }
3540 }
3541
3542 /// Closes the active item across all panes.
3543 pub fn close_item_in_all_panes(
3544 &mut self,
3545 action: &CloseItemInAllPanes,
3546 window: &mut Window,
3547 cx: &mut Context<Self>,
3548 ) {
3549 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3550 return;
3551 };
3552
3553 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3554 let close_pinned = action.close_pinned;
3555
3556 if let Some(project_path) = active_item.project_path(cx) {
3557 self.close_items_with_project_path(
3558 &project_path,
3559 save_intent,
3560 close_pinned,
3561 window,
3562 cx,
3563 );
3564 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3565 let item_id = active_item.item_id();
3566 self.active_pane().update(cx, |pane, cx| {
3567 pane.close_item_by_id(item_id, save_intent, window, cx)
3568 .detach_and_log_err(cx);
3569 });
3570 }
3571 }
3572
3573 /// Closes all items with the given project path across all panes.
3574 pub fn close_items_with_project_path(
3575 &mut self,
3576 project_path: &ProjectPath,
3577 save_intent: SaveIntent,
3578 close_pinned: bool,
3579 window: &mut Window,
3580 cx: &mut Context<Self>,
3581 ) {
3582 let panes = self.panes().to_vec();
3583 for pane in panes {
3584 pane.update(cx, |pane, cx| {
3585 pane.close_items_for_project_path(
3586 project_path,
3587 save_intent,
3588 close_pinned,
3589 window,
3590 cx,
3591 )
3592 .detach_and_log_err(cx);
3593 });
3594 }
3595 }
3596
3597 fn close_all_internal(
3598 &mut self,
3599 retain_active_pane: bool,
3600 save_intent: SaveIntent,
3601 window: &mut Window,
3602 cx: &mut Context<Self>,
3603 ) -> Option<Task<Result<()>>> {
3604 let current_pane = self.active_pane();
3605
3606 let mut tasks = Vec::new();
3607
3608 if retain_active_pane {
3609 let current_pane_close = current_pane.update(cx, |pane, cx| {
3610 pane.close_other_items(
3611 &CloseOtherItems {
3612 save_intent: None,
3613 close_pinned: false,
3614 },
3615 None,
3616 window,
3617 cx,
3618 )
3619 });
3620
3621 tasks.push(current_pane_close);
3622 }
3623
3624 for pane in self.panes() {
3625 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3626 continue;
3627 }
3628
3629 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3630 pane.close_all_items(
3631 &CloseAllItems {
3632 save_intent: Some(save_intent),
3633 close_pinned: false,
3634 },
3635 window,
3636 cx,
3637 )
3638 });
3639
3640 tasks.push(close_pane_items)
3641 }
3642
3643 if tasks.is_empty() {
3644 None
3645 } else {
3646 Some(cx.spawn_in(window, async move |_, _| {
3647 for task in tasks {
3648 task.await?
3649 }
3650 Ok(())
3651 }))
3652 }
3653 }
3654
3655 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3656 self.dock_at_position(position).read(cx).is_open()
3657 }
3658
3659 pub fn toggle_dock(
3660 &mut self,
3661 dock_side: DockPosition,
3662 window: &mut Window,
3663 cx: &mut Context<Self>,
3664 ) {
3665 let mut focus_center = false;
3666 let mut reveal_dock = false;
3667
3668 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3669 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3670
3671 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3672 telemetry::event!(
3673 "Panel Button Clicked",
3674 name = panel.persistent_name(),
3675 toggle_state = !was_visible
3676 );
3677 }
3678 if was_visible {
3679 self.save_open_dock_positions(cx);
3680 }
3681
3682 let dock = self.dock_at_position(dock_side);
3683 dock.update(cx, |dock, cx| {
3684 dock.set_open(!was_visible, window, cx);
3685
3686 if dock.active_panel().is_none() {
3687 let Some(panel_ix) = dock
3688 .first_enabled_panel_idx(cx)
3689 .log_with_level(log::Level::Info)
3690 else {
3691 return;
3692 };
3693 dock.activate_panel(panel_ix, window, cx);
3694 }
3695
3696 if let Some(active_panel) = dock.active_panel() {
3697 if was_visible {
3698 if active_panel
3699 .panel_focus_handle(cx)
3700 .contains_focused(window, cx)
3701 {
3702 focus_center = true;
3703 }
3704 } else {
3705 let focus_handle = &active_panel.panel_focus_handle(cx);
3706 window.focus(focus_handle, cx);
3707 reveal_dock = true;
3708 }
3709 }
3710 });
3711
3712 if reveal_dock {
3713 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3714 }
3715
3716 if focus_center {
3717 self.active_pane
3718 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3719 }
3720
3721 cx.notify();
3722 self.serialize_workspace(window, cx);
3723 }
3724
3725 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3726 self.all_docks().into_iter().find(|&dock| {
3727 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3728 })
3729 }
3730
3731 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3732 if let Some(dock) = self.active_dock(window, cx).cloned() {
3733 self.save_open_dock_positions(cx);
3734 dock.update(cx, |dock, cx| {
3735 dock.set_open(false, window, cx);
3736 });
3737 return true;
3738 }
3739 false
3740 }
3741
3742 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3743 self.save_open_dock_positions(cx);
3744 for dock in self.all_docks() {
3745 dock.update(cx, |dock, cx| {
3746 dock.set_open(false, window, cx);
3747 });
3748 }
3749
3750 cx.focus_self(window);
3751 cx.notify();
3752 self.serialize_workspace(window, cx);
3753 }
3754
3755 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
3756 self.all_docks()
3757 .into_iter()
3758 .filter_map(|dock| {
3759 let dock_ref = dock.read(cx);
3760 if dock_ref.is_open() {
3761 Some(dock_ref.position())
3762 } else {
3763 None
3764 }
3765 })
3766 .collect()
3767 }
3768
3769 /// Saves the positions of currently open docks.
3770 ///
3771 /// Updates `last_open_dock_positions` with positions of all currently open
3772 /// docks, to later be restored by the 'Toggle All Docks' action.
3773 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
3774 let open_dock_positions = self.get_open_dock_positions(cx);
3775 if !open_dock_positions.is_empty() {
3776 self.last_open_dock_positions = open_dock_positions;
3777 }
3778 }
3779
3780 /// Toggles all docks between open and closed states.
3781 ///
3782 /// If any docks are open, closes all and remembers their positions. If all
3783 /// docks are closed, restores the last remembered dock configuration.
3784 fn toggle_all_docks(
3785 &mut self,
3786 _: &ToggleAllDocks,
3787 window: &mut Window,
3788 cx: &mut Context<Self>,
3789 ) {
3790 let open_dock_positions = self.get_open_dock_positions(cx);
3791
3792 if !open_dock_positions.is_empty() {
3793 self.close_all_docks(window, cx);
3794 } else if !self.last_open_dock_positions.is_empty() {
3795 self.restore_last_open_docks(window, cx);
3796 }
3797 }
3798
3799 /// Reopens docks from the most recently remembered configuration.
3800 ///
3801 /// Opens all docks whose positions are stored in `last_open_dock_positions`
3802 /// and clears the stored positions.
3803 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3804 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
3805
3806 for position in positions_to_open {
3807 let dock = self.dock_at_position(position);
3808 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
3809 }
3810
3811 cx.focus_self(window);
3812 cx.notify();
3813 self.serialize_workspace(window, cx);
3814 }
3815
3816 /// Transfer focus to the panel of the given type.
3817 pub fn focus_panel<T: Panel>(
3818 &mut self,
3819 window: &mut Window,
3820 cx: &mut Context<Self>,
3821 ) -> Option<Entity<T>> {
3822 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
3823 panel.to_any().downcast().ok()
3824 }
3825
3826 /// Focus the panel of the given type if it isn't already focused. If it is
3827 /// already focused, then transfer focus back to the workspace center.
3828 /// When the `close_panel_on_toggle` setting is enabled, also closes the
3829 /// panel when transferring focus back to the center.
3830 pub fn toggle_panel_focus<T: Panel>(
3831 &mut self,
3832 window: &mut Window,
3833 cx: &mut Context<Self>,
3834 ) -> bool {
3835 let mut did_focus_panel = false;
3836 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
3837 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
3838 did_focus_panel
3839 });
3840
3841 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
3842 self.close_panel::<T>(window, cx);
3843 }
3844
3845 telemetry::event!(
3846 "Panel Button Clicked",
3847 name = T::persistent_name(),
3848 toggle_state = did_focus_panel
3849 );
3850
3851 did_focus_panel
3852 }
3853
3854 pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3855 if let Some(item) = self.active_item(cx) {
3856 item.item_focus_handle(cx).focus(window, cx);
3857 } else {
3858 log::error!("Could not find a focus target when switching focus to the center panes",);
3859 }
3860 }
3861
3862 pub fn activate_panel_for_proto_id(
3863 &mut self,
3864 panel_id: PanelId,
3865 window: &mut Window,
3866 cx: &mut Context<Self>,
3867 ) -> Option<Arc<dyn PanelHandle>> {
3868 let mut panel = None;
3869 for dock in self.all_docks() {
3870 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
3871 panel = dock.update(cx, |dock, cx| {
3872 dock.activate_panel(panel_index, window, cx);
3873 dock.set_open(true, window, cx);
3874 dock.active_panel().cloned()
3875 });
3876 break;
3877 }
3878 }
3879
3880 if panel.is_some() {
3881 cx.notify();
3882 self.serialize_workspace(window, cx);
3883 }
3884
3885 panel
3886 }
3887
3888 /// Focus or unfocus the given panel type, depending on the given callback.
3889 fn focus_or_unfocus_panel<T: Panel>(
3890 &mut self,
3891 window: &mut Window,
3892 cx: &mut Context<Self>,
3893 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
3894 ) -> Option<Arc<dyn PanelHandle>> {
3895 let mut result_panel = None;
3896 let mut serialize = false;
3897 for dock in self.all_docks() {
3898 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3899 let mut focus_center = false;
3900 let panel = dock.update(cx, |dock, cx| {
3901 dock.activate_panel(panel_index, window, cx);
3902
3903 let panel = dock.active_panel().cloned();
3904 if let Some(panel) = panel.as_ref() {
3905 if should_focus(&**panel, window, cx) {
3906 dock.set_open(true, window, cx);
3907 panel.panel_focus_handle(cx).focus(window, cx);
3908 } else {
3909 focus_center = true;
3910 }
3911 }
3912 panel
3913 });
3914
3915 if focus_center {
3916 self.active_pane
3917 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3918 }
3919
3920 result_panel = panel;
3921 serialize = true;
3922 break;
3923 }
3924 }
3925
3926 if serialize {
3927 self.serialize_workspace(window, cx);
3928 }
3929
3930 cx.notify();
3931 result_panel
3932 }
3933
3934 /// Open the panel of the given type
3935 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3936 for dock in self.all_docks() {
3937 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3938 dock.update(cx, |dock, cx| {
3939 dock.activate_panel(panel_index, window, cx);
3940 dock.set_open(true, window, cx);
3941 });
3942 }
3943 }
3944 }
3945
3946 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
3947 for dock in self.all_docks().iter() {
3948 dock.update(cx, |dock, cx| {
3949 if dock.panel::<T>().is_some() {
3950 dock.set_open(false, window, cx)
3951 }
3952 })
3953 }
3954 }
3955
3956 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
3957 self.all_docks()
3958 .iter()
3959 .find_map(|dock| dock.read(cx).panel::<T>())
3960 }
3961
3962 fn dismiss_zoomed_items_to_reveal(
3963 &mut self,
3964 dock_to_reveal: Option<DockPosition>,
3965 window: &mut Window,
3966 cx: &mut Context<Self>,
3967 ) {
3968 // If a center pane is zoomed, unzoom it.
3969 for pane in &self.panes {
3970 if pane != &self.active_pane || dock_to_reveal.is_some() {
3971 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
3972 }
3973 }
3974
3975 // If another dock is zoomed, hide it.
3976 let mut focus_center = false;
3977 for dock in self.all_docks() {
3978 dock.update(cx, |dock, cx| {
3979 if Some(dock.position()) != dock_to_reveal
3980 && let Some(panel) = dock.active_panel()
3981 && panel.is_zoomed(window, cx)
3982 {
3983 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
3984 dock.set_open(false, window, cx);
3985 }
3986 });
3987 }
3988
3989 if focus_center {
3990 self.active_pane
3991 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3992 }
3993
3994 if self.zoomed_position != dock_to_reveal {
3995 self.zoomed = None;
3996 self.zoomed_position = None;
3997 cx.emit(Event::ZoomChanged);
3998 }
3999
4000 cx.notify();
4001 }
4002
4003 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4004 let pane = cx.new(|cx| {
4005 let mut pane = Pane::new(
4006 self.weak_handle(),
4007 self.project.clone(),
4008 self.pane_history_timestamp.clone(),
4009 None,
4010 NewFile.boxed_clone(),
4011 true,
4012 window,
4013 cx,
4014 );
4015 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
4016 pane
4017 });
4018 cx.subscribe_in(&pane, window, Self::handle_pane_event)
4019 .detach();
4020 self.panes.push(pane.clone());
4021
4022 window.focus(&pane.focus_handle(cx), cx);
4023
4024 cx.emit(Event::PaneAdded(pane.clone()));
4025 pane
4026 }
4027
4028 pub fn add_item_to_center(
4029 &mut self,
4030 item: Box<dyn ItemHandle>,
4031 window: &mut Window,
4032 cx: &mut Context<Self>,
4033 ) -> bool {
4034 if let Some(center_pane) = self.last_active_center_pane.clone() {
4035 if let Some(center_pane) = center_pane.upgrade() {
4036 center_pane.update(cx, |pane, cx| {
4037 pane.add_item(item, true, true, None, window, cx)
4038 });
4039 true
4040 } else {
4041 false
4042 }
4043 } else {
4044 false
4045 }
4046 }
4047
4048 pub fn add_item_to_active_pane(
4049 &mut self,
4050 item: Box<dyn ItemHandle>,
4051 destination_index: Option<usize>,
4052 focus_item: bool,
4053 window: &mut Window,
4054 cx: &mut App,
4055 ) {
4056 self.add_item(
4057 self.active_pane.clone(),
4058 item,
4059 destination_index,
4060 false,
4061 focus_item,
4062 window,
4063 cx,
4064 )
4065 }
4066
4067 pub fn add_item(
4068 &mut self,
4069 pane: Entity<Pane>,
4070 item: Box<dyn ItemHandle>,
4071 destination_index: Option<usize>,
4072 activate_pane: bool,
4073 focus_item: bool,
4074 window: &mut Window,
4075 cx: &mut App,
4076 ) {
4077 pane.update(cx, |pane, cx| {
4078 pane.add_item(
4079 item,
4080 activate_pane,
4081 focus_item,
4082 destination_index,
4083 window,
4084 cx,
4085 )
4086 });
4087 }
4088
4089 pub fn split_item(
4090 &mut self,
4091 split_direction: SplitDirection,
4092 item: Box<dyn ItemHandle>,
4093 window: &mut Window,
4094 cx: &mut Context<Self>,
4095 ) {
4096 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4097 self.add_item(new_pane, item, None, true, true, window, cx);
4098 }
4099
4100 pub fn open_abs_path(
4101 &mut self,
4102 abs_path: PathBuf,
4103 options: OpenOptions,
4104 window: &mut Window,
4105 cx: &mut Context<Self>,
4106 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4107 cx.spawn_in(window, async move |workspace, cx| {
4108 let open_paths_task_result = workspace
4109 .update_in(cx, |workspace, window, cx| {
4110 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4111 })
4112 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4113 .await;
4114 anyhow::ensure!(
4115 open_paths_task_result.len() == 1,
4116 "open abs path {abs_path:?} task returned incorrect number of results"
4117 );
4118 match open_paths_task_result
4119 .into_iter()
4120 .next()
4121 .expect("ensured single task result")
4122 {
4123 Some(open_result) => {
4124 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4125 }
4126 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4127 }
4128 })
4129 }
4130
4131 pub fn split_abs_path(
4132 &mut self,
4133 abs_path: PathBuf,
4134 visible: bool,
4135 window: &mut Window,
4136 cx: &mut Context<Self>,
4137 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4138 let project_path_task =
4139 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4140 cx.spawn_in(window, async move |this, cx| {
4141 let (_, path) = project_path_task.await?;
4142 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4143 .await
4144 })
4145 }
4146
4147 pub fn open_path(
4148 &mut self,
4149 path: impl Into<ProjectPath>,
4150 pane: Option<WeakEntity<Pane>>,
4151 focus_item: bool,
4152 window: &mut Window,
4153 cx: &mut App,
4154 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4155 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4156 }
4157
4158 pub fn open_path_preview(
4159 &mut self,
4160 path: impl Into<ProjectPath>,
4161 pane: Option<WeakEntity<Pane>>,
4162 focus_item: bool,
4163 allow_preview: bool,
4164 activate: bool,
4165 window: &mut Window,
4166 cx: &mut App,
4167 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4168 let pane = pane.unwrap_or_else(|| {
4169 self.last_active_center_pane.clone().unwrap_or_else(|| {
4170 self.panes
4171 .first()
4172 .expect("There must be an active pane")
4173 .downgrade()
4174 })
4175 });
4176
4177 let project_path = path.into();
4178 let task = self.load_path(project_path.clone(), window, cx);
4179 window.spawn(cx, async move |cx| {
4180 let (project_entry_id, build_item) = task.await?;
4181
4182 pane.update_in(cx, |pane, window, cx| {
4183 pane.open_item(
4184 project_entry_id,
4185 project_path,
4186 focus_item,
4187 allow_preview,
4188 activate,
4189 None,
4190 window,
4191 cx,
4192 build_item,
4193 )
4194 })
4195 })
4196 }
4197
4198 pub fn split_path(
4199 &mut self,
4200 path: impl Into<ProjectPath>,
4201 window: &mut Window,
4202 cx: &mut Context<Self>,
4203 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4204 self.split_path_preview(path, false, None, window, cx)
4205 }
4206
4207 pub fn split_path_preview(
4208 &mut self,
4209 path: impl Into<ProjectPath>,
4210 allow_preview: bool,
4211 split_direction: Option<SplitDirection>,
4212 window: &mut Window,
4213 cx: &mut Context<Self>,
4214 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4215 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4216 self.panes
4217 .first()
4218 .expect("There must be an active pane")
4219 .downgrade()
4220 });
4221
4222 if let Member::Pane(center_pane) = &self.center.root
4223 && center_pane.read(cx).items_len() == 0
4224 {
4225 return self.open_path(path, Some(pane), true, window, cx);
4226 }
4227
4228 let project_path = path.into();
4229 let task = self.load_path(project_path.clone(), window, cx);
4230 cx.spawn_in(window, async move |this, cx| {
4231 let (project_entry_id, build_item) = task.await?;
4232 this.update_in(cx, move |this, window, cx| -> Option<_> {
4233 let pane = pane.upgrade()?;
4234 let new_pane = this.split_pane(
4235 pane,
4236 split_direction.unwrap_or(SplitDirection::Right),
4237 window,
4238 cx,
4239 );
4240 new_pane.update(cx, |new_pane, cx| {
4241 Some(new_pane.open_item(
4242 project_entry_id,
4243 project_path,
4244 true,
4245 allow_preview,
4246 true,
4247 None,
4248 window,
4249 cx,
4250 build_item,
4251 ))
4252 })
4253 })
4254 .map(|option| option.context("pane was dropped"))?
4255 })
4256 }
4257
4258 fn load_path(
4259 &mut self,
4260 path: ProjectPath,
4261 window: &mut Window,
4262 cx: &mut App,
4263 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4264 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4265 registry.open_path(self.project(), &path, window, cx)
4266 }
4267
4268 pub fn find_project_item<T>(
4269 &self,
4270 pane: &Entity<Pane>,
4271 project_item: &Entity<T::Item>,
4272 cx: &App,
4273 ) -> Option<Entity<T>>
4274 where
4275 T: ProjectItem,
4276 {
4277 use project::ProjectItem as _;
4278 let project_item = project_item.read(cx);
4279 let entry_id = project_item.entry_id(cx);
4280 let project_path = project_item.project_path(cx);
4281
4282 let mut item = None;
4283 if let Some(entry_id) = entry_id {
4284 item = pane.read(cx).item_for_entry(entry_id, cx);
4285 }
4286 if item.is_none()
4287 && let Some(project_path) = project_path
4288 {
4289 item = pane.read(cx).item_for_path(project_path, cx);
4290 }
4291
4292 item.and_then(|item| item.downcast::<T>())
4293 }
4294
4295 pub fn is_project_item_open<T>(
4296 &self,
4297 pane: &Entity<Pane>,
4298 project_item: &Entity<T::Item>,
4299 cx: &App,
4300 ) -> bool
4301 where
4302 T: ProjectItem,
4303 {
4304 self.find_project_item::<T>(pane, project_item, cx)
4305 .is_some()
4306 }
4307
4308 pub fn open_project_item<T>(
4309 &mut self,
4310 pane: Entity<Pane>,
4311 project_item: Entity<T::Item>,
4312 activate_pane: bool,
4313 focus_item: bool,
4314 keep_old_preview: bool,
4315 allow_new_preview: bool,
4316 window: &mut Window,
4317 cx: &mut Context<Self>,
4318 ) -> Entity<T>
4319 where
4320 T: ProjectItem,
4321 {
4322 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4323
4324 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4325 if !keep_old_preview
4326 && let Some(old_id) = old_item_id
4327 && old_id != item.item_id()
4328 {
4329 // switching to a different item, so unpreview old active item
4330 pane.update(cx, |pane, _| {
4331 pane.unpreview_item_if_preview(old_id);
4332 });
4333 }
4334
4335 self.activate_item(&item, activate_pane, focus_item, window, cx);
4336 if !allow_new_preview {
4337 pane.update(cx, |pane, _| {
4338 pane.unpreview_item_if_preview(item.item_id());
4339 });
4340 }
4341 return item;
4342 }
4343
4344 let item = pane.update(cx, |pane, cx| {
4345 cx.new(|cx| {
4346 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4347 })
4348 });
4349 let mut destination_index = None;
4350 pane.update(cx, |pane, cx| {
4351 if !keep_old_preview && let Some(old_id) = old_item_id {
4352 pane.unpreview_item_if_preview(old_id);
4353 }
4354 if allow_new_preview {
4355 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4356 }
4357 });
4358
4359 self.add_item(
4360 pane,
4361 Box::new(item.clone()),
4362 destination_index,
4363 activate_pane,
4364 focus_item,
4365 window,
4366 cx,
4367 );
4368 item
4369 }
4370
4371 pub fn open_shared_screen(
4372 &mut self,
4373 peer_id: PeerId,
4374 window: &mut Window,
4375 cx: &mut Context<Self>,
4376 ) {
4377 if let Some(shared_screen) =
4378 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4379 {
4380 self.active_pane.update(cx, |pane, cx| {
4381 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4382 });
4383 }
4384 }
4385
4386 pub fn activate_item(
4387 &mut self,
4388 item: &dyn ItemHandle,
4389 activate_pane: bool,
4390 focus_item: bool,
4391 window: &mut Window,
4392 cx: &mut App,
4393 ) -> bool {
4394 let result = self.panes.iter().find_map(|pane| {
4395 pane.read(cx)
4396 .index_for_item(item)
4397 .map(|ix| (pane.clone(), ix))
4398 });
4399 if let Some((pane, ix)) = result {
4400 pane.update(cx, |pane, cx| {
4401 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4402 });
4403 true
4404 } else {
4405 false
4406 }
4407 }
4408
4409 fn activate_pane_at_index(
4410 &mut self,
4411 action: &ActivatePane,
4412 window: &mut Window,
4413 cx: &mut Context<Self>,
4414 ) {
4415 let panes = self.center.panes();
4416 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4417 window.focus(&pane.focus_handle(cx), cx);
4418 } else {
4419 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4420 .detach();
4421 }
4422 }
4423
4424 fn move_item_to_pane_at_index(
4425 &mut self,
4426 action: &MoveItemToPane,
4427 window: &mut Window,
4428 cx: &mut Context<Self>,
4429 ) {
4430 let panes = self.center.panes();
4431 let destination = match panes.get(action.destination) {
4432 Some(&destination) => destination.clone(),
4433 None => {
4434 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4435 return;
4436 }
4437 let direction = SplitDirection::Right;
4438 let split_off_pane = self
4439 .find_pane_in_direction(direction, cx)
4440 .unwrap_or_else(|| self.active_pane.clone());
4441 let new_pane = self.add_pane(window, cx);
4442 self.center.split(&split_off_pane, &new_pane, direction, cx);
4443 new_pane
4444 }
4445 };
4446
4447 if action.clone {
4448 if self
4449 .active_pane
4450 .read(cx)
4451 .active_item()
4452 .is_some_and(|item| item.can_split(cx))
4453 {
4454 clone_active_item(
4455 self.database_id(),
4456 &self.active_pane,
4457 &destination,
4458 action.focus,
4459 window,
4460 cx,
4461 );
4462 return;
4463 }
4464 }
4465 move_active_item(
4466 &self.active_pane,
4467 &destination,
4468 action.focus,
4469 true,
4470 window,
4471 cx,
4472 )
4473 }
4474
4475 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4476 let panes = self.center.panes();
4477 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4478 let next_ix = (ix + 1) % panes.len();
4479 let next_pane = panes[next_ix].clone();
4480 window.focus(&next_pane.focus_handle(cx), cx);
4481 }
4482 }
4483
4484 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4485 let panes = self.center.panes();
4486 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4487 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4488 let prev_pane = panes[prev_ix].clone();
4489 window.focus(&prev_pane.focus_handle(cx), cx);
4490 }
4491 }
4492
4493 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4494 let last_pane = self.center.last_pane();
4495 window.focus(&last_pane.focus_handle(cx), cx);
4496 }
4497
4498 pub fn activate_pane_in_direction(
4499 &mut self,
4500 direction: SplitDirection,
4501 window: &mut Window,
4502 cx: &mut App,
4503 ) {
4504 use ActivateInDirectionTarget as Target;
4505 enum Origin {
4506 Sidebar,
4507 LeftDock,
4508 RightDock,
4509 BottomDock,
4510 Center,
4511 }
4512
4513 let origin: Origin = if self
4514 .sidebar_focus_handle
4515 .as_ref()
4516 .is_some_and(|h| h.contains_focused(window, cx))
4517 {
4518 Origin::Sidebar
4519 } else {
4520 [
4521 (&self.left_dock, Origin::LeftDock),
4522 (&self.right_dock, Origin::RightDock),
4523 (&self.bottom_dock, Origin::BottomDock),
4524 ]
4525 .into_iter()
4526 .find_map(|(dock, origin)| {
4527 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4528 Some(origin)
4529 } else {
4530 None
4531 }
4532 })
4533 .unwrap_or(Origin::Center)
4534 };
4535
4536 let get_last_active_pane = || {
4537 let pane = self
4538 .last_active_center_pane
4539 .clone()
4540 .unwrap_or_else(|| {
4541 self.panes
4542 .first()
4543 .expect("There must be an active pane")
4544 .downgrade()
4545 })
4546 .upgrade()?;
4547 (pane.read(cx).items_len() != 0).then_some(pane)
4548 };
4549
4550 let try_dock =
4551 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4552
4553 let sidebar_target = self
4554 .sidebar_focus_handle
4555 .as_ref()
4556 .map(|h| Target::Sidebar(h.clone()));
4557
4558 let target = match (origin, direction) {
4559 // From the sidebar, only Right navigates into the workspace.
4560 (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
4561 .or_else(|| get_last_active_pane().map(Target::Pane))
4562 .or_else(|| try_dock(&self.bottom_dock))
4563 .or_else(|| try_dock(&self.right_dock)),
4564
4565 (Origin::Sidebar, _) => None,
4566
4567 // We're in the center, so we first try to go to a different pane,
4568 // otherwise try to go to a dock.
4569 (Origin::Center, direction) => {
4570 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4571 Some(Target::Pane(pane))
4572 } else {
4573 match direction {
4574 SplitDirection::Up => None,
4575 SplitDirection::Down => try_dock(&self.bottom_dock),
4576 SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
4577 SplitDirection::Right => try_dock(&self.right_dock),
4578 }
4579 }
4580 }
4581
4582 (Origin::LeftDock, SplitDirection::Right) => {
4583 if let Some(last_active_pane) = get_last_active_pane() {
4584 Some(Target::Pane(last_active_pane))
4585 } else {
4586 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4587 }
4588 }
4589
4590 (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
4591
4592 (Origin::LeftDock, SplitDirection::Down)
4593 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4594
4595 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4596 (Origin::BottomDock, SplitDirection::Left) => {
4597 try_dock(&self.left_dock).or(sidebar_target)
4598 }
4599 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4600
4601 (Origin::RightDock, SplitDirection::Left) => {
4602 if let Some(last_active_pane) = get_last_active_pane() {
4603 Some(Target::Pane(last_active_pane))
4604 } else {
4605 try_dock(&self.bottom_dock)
4606 .or_else(|| try_dock(&self.left_dock))
4607 .or(sidebar_target)
4608 }
4609 }
4610
4611 _ => None,
4612 };
4613
4614 match target {
4615 Some(ActivateInDirectionTarget::Pane(pane)) => {
4616 let pane = pane.read(cx);
4617 if let Some(item) = pane.active_item() {
4618 item.item_focus_handle(cx).focus(window, cx);
4619 } else {
4620 log::error!(
4621 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4622 );
4623 }
4624 }
4625 Some(ActivateInDirectionTarget::Dock(dock)) => {
4626 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4627 window.defer(cx, move |window, cx| {
4628 let dock = dock.read(cx);
4629 if let Some(panel) = dock.active_panel() {
4630 panel.panel_focus_handle(cx).focus(window, cx);
4631 } else {
4632 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4633 }
4634 })
4635 }
4636 Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
4637 focus_handle.focus(window, cx);
4638 }
4639 None => {}
4640 }
4641 }
4642
4643 pub fn move_item_to_pane_in_direction(
4644 &mut self,
4645 action: &MoveItemToPaneInDirection,
4646 window: &mut Window,
4647 cx: &mut Context<Self>,
4648 ) {
4649 let destination = match self.find_pane_in_direction(action.direction, cx) {
4650 Some(destination) => destination,
4651 None => {
4652 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4653 return;
4654 }
4655 let new_pane = self.add_pane(window, cx);
4656 self.center
4657 .split(&self.active_pane, &new_pane, action.direction, cx);
4658 new_pane
4659 }
4660 };
4661
4662 if action.clone {
4663 if self
4664 .active_pane
4665 .read(cx)
4666 .active_item()
4667 .is_some_and(|item| item.can_split(cx))
4668 {
4669 clone_active_item(
4670 self.database_id(),
4671 &self.active_pane,
4672 &destination,
4673 action.focus,
4674 window,
4675 cx,
4676 );
4677 return;
4678 }
4679 }
4680 move_active_item(
4681 &self.active_pane,
4682 &destination,
4683 action.focus,
4684 true,
4685 window,
4686 cx,
4687 );
4688 }
4689
4690 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4691 self.center.bounding_box_for_pane(pane)
4692 }
4693
4694 pub fn find_pane_in_direction(
4695 &mut self,
4696 direction: SplitDirection,
4697 cx: &App,
4698 ) -> Option<Entity<Pane>> {
4699 self.center
4700 .find_pane_in_direction(&self.active_pane, direction, cx)
4701 .cloned()
4702 }
4703
4704 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4705 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4706 self.center.swap(&self.active_pane, &to, cx);
4707 cx.notify();
4708 }
4709 }
4710
4711 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4712 if self
4713 .center
4714 .move_to_border(&self.active_pane, direction, cx)
4715 .unwrap()
4716 {
4717 cx.notify();
4718 }
4719 }
4720
4721 pub fn resize_pane(
4722 &mut self,
4723 axis: gpui::Axis,
4724 amount: Pixels,
4725 window: &mut Window,
4726 cx: &mut Context<Self>,
4727 ) {
4728 let docks = self.all_docks();
4729 let active_dock = docks
4730 .into_iter()
4731 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4732
4733 if let Some(dock) = active_dock {
4734 let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
4735 return;
4736 };
4737 match dock.read(cx).position() {
4738 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4739 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4740 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4741 }
4742 } else {
4743 self.center
4744 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
4745 }
4746 cx.notify();
4747 }
4748
4749 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
4750 self.center.reset_pane_sizes(cx);
4751 cx.notify();
4752 }
4753
4754 fn handle_pane_focused(
4755 &mut self,
4756 pane: Entity<Pane>,
4757 window: &mut Window,
4758 cx: &mut Context<Self>,
4759 ) {
4760 // This is explicitly hoisted out of the following check for pane identity as
4761 // terminal panel panes are not registered as a center panes.
4762 self.status_bar.update(cx, |status_bar, cx| {
4763 status_bar.set_active_pane(&pane, window, cx);
4764 });
4765 if self.active_pane != pane {
4766 self.set_active_pane(&pane, window, cx);
4767 }
4768
4769 if self.last_active_center_pane.is_none() {
4770 self.last_active_center_pane = Some(pane.downgrade());
4771 }
4772
4773 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
4774 // This prevents the dock from closing when focus events fire during window activation.
4775 // We also preserve any dock whose active panel itself has focus — this covers
4776 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
4777 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
4778 let dock_read = dock.read(cx);
4779 if let Some(panel) = dock_read.active_panel() {
4780 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
4781 || panel.panel_focus_handle(cx).contains_focused(window, cx)
4782 {
4783 return Some(dock_read.position());
4784 }
4785 }
4786 None
4787 });
4788
4789 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
4790 if pane.read(cx).is_zoomed() {
4791 self.zoomed = Some(pane.downgrade().into());
4792 } else {
4793 self.zoomed = None;
4794 }
4795 self.zoomed_position = None;
4796 cx.emit(Event::ZoomChanged);
4797 self.update_active_view_for_followers(window, cx);
4798 pane.update(cx, |pane, _| {
4799 pane.track_alternate_file_items();
4800 });
4801
4802 cx.notify();
4803 }
4804
4805 fn set_active_pane(
4806 &mut self,
4807 pane: &Entity<Pane>,
4808 window: &mut Window,
4809 cx: &mut Context<Self>,
4810 ) {
4811 self.active_pane = pane.clone();
4812 self.active_item_path_changed(true, window, cx);
4813 self.last_active_center_pane = Some(pane.downgrade());
4814 }
4815
4816 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4817 self.update_active_view_for_followers(window, cx);
4818 }
4819
4820 fn handle_pane_event(
4821 &mut self,
4822 pane: &Entity<Pane>,
4823 event: &pane::Event,
4824 window: &mut Window,
4825 cx: &mut Context<Self>,
4826 ) {
4827 let mut serialize_workspace = true;
4828 match event {
4829 pane::Event::AddItem { item } => {
4830 item.added_to_pane(self, pane.clone(), window, cx);
4831 cx.emit(Event::ItemAdded {
4832 item: item.boxed_clone(),
4833 });
4834 }
4835 pane::Event::Split { direction, mode } => {
4836 match mode {
4837 SplitMode::ClonePane => {
4838 self.split_and_clone(pane.clone(), *direction, window, cx)
4839 .detach();
4840 }
4841 SplitMode::EmptyPane => {
4842 self.split_pane(pane.clone(), *direction, window, cx);
4843 }
4844 SplitMode::MovePane => {
4845 self.split_and_move(pane.clone(), *direction, window, cx);
4846 }
4847 };
4848 }
4849 pane::Event::JoinIntoNext => {
4850 self.join_pane_into_next(pane.clone(), window, cx);
4851 }
4852 pane::Event::JoinAll => {
4853 self.join_all_panes(window, cx);
4854 }
4855 pane::Event::Remove { focus_on_pane } => {
4856 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
4857 }
4858 pane::Event::ActivateItem {
4859 local,
4860 focus_changed,
4861 } => {
4862 window.invalidate_character_coordinates();
4863
4864 pane.update(cx, |pane, _| {
4865 pane.track_alternate_file_items();
4866 });
4867 if *local {
4868 self.unfollow_in_pane(pane, window, cx);
4869 }
4870 serialize_workspace = *focus_changed || pane != self.active_pane();
4871 if pane == self.active_pane() {
4872 self.active_item_path_changed(*focus_changed, window, cx);
4873 self.update_active_view_for_followers(window, cx);
4874 } else if *local {
4875 self.set_active_pane(pane, window, cx);
4876 }
4877 }
4878 pane::Event::UserSavedItem { item, save_intent } => {
4879 cx.emit(Event::UserSavedItem {
4880 pane: pane.downgrade(),
4881 item: item.boxed_clone(),
4882 save_intent: *save_intent,
4883 });
4884 serialize_workspace = false;
4885 }
4886 pane::Event::ChangeItemTitle => {
4887 if *pane == self.active_pane {
4888 self.active_item_path_changed(false, window, cx);
4889 }
4890 serialize_workspace = false;
4891 }
4892 pane::Event::RemovedItem { item } => {
4893 cx.emit(Event::ActiveItemChanged);
4894 self.update_window_edited(window, cx);
4895 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
4896 && entry.get().entity_id() == pane.entity_id()
4897 {
4898 entry.remove();
4899 }
4900 cx.emit(Event::ItemRemoved {
4901 item_id: item.item_id(),
4902 });
4903 }
4904 pane::Event::Focus => {
4905 window.invalidate_character_coordinates();
4906 self.handle_pane_focused(pane.clone(), window, cx);
4907 }
4908 pane::Event::ZoomIn => {
4909 if *pane == self.active_pane {
4910 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
4911 if pane.read(cx).has_focus(window, cx) {
4912 self.zoomed = Some(pane.downgrade().into());
4913 self.zoomed_position = None;
4914 cx.emit(Event::ZoomChanged);
4915 }
4916 cx.notify();
4917 }
4918 }
4919 pane::Event::ZoomOut => {
4920 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4921 if self.zoomed_position.is_none() {
4922 self.zoomed = None;
4923 cx.emit(Event::ZoomChanged);
4924 }
4925 cx.notify();
4926 }
4927 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
4928 }
4929
4930 if serialize_workspace {
4931 self.serialize_workspace(window, cx);
4932 }
4933 }
4934
4935 pub fn unfollow_in_pane(
4936 &mut self,
4937 pane: &Entity<Pane>,
4938 window: &mut Window,
4939 cx: &mut Context<Workspace>,
4940 ) -> Option<CollaboratorId> {
4941 let leader_id = self.leader_for_pane(pane)?;
4942 self.unfollow(leader_id, window, cx);
4943 Some(leader_id)
4944 }
4945
4946 pub fn split_pane(
4947 &mut self,
4948 pane_to_split: Entity<Pane>,
4949 split_direction: SplitDirection,
4950 window: &mut Window,
4951 cx: &mut Context<Self>,
4952 ) -> Entity<Pane> {
4953 let new_pane = self.add_pane(window, cx);
4954 self.center
4955 .split(&pane_to_split, &new_pane, split_direction, cx);
4956 cx.notify();
4957 new_pane
4958 }
4959
4960 pub fn split_and_move(
4961 &mut self,
4962 pane: Entity<Pane>,
4963 direction: SplitDirection,
4964 window: &mut Window,
4965 cx: &mut Context<Self>,
4966 ) {
4967 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
4968 return;
4969 };
4970 let new_pane = self.add_pane(window, cx);
4971 new_pane.update(cx, |pane, cx| {
4972 pane.add_item(item, true, true, None, window, cx)
4973 });
4974 self.center.split(&pane, &new_pane, direction, cx);
4975 cx.notify();
4976 }
4977
4978 pub fn split_and_clone(
4979 &mut self,
4980 pane: Entity<Pane>,
4981 direction: SplitDirection,
4982 window: &mut Window,
4983 cx: &mut Context<Self>,
4984 ) -> Task<Option<Entity<Pane>>> {
4985 let Some(item) = pane.read(cx).active_item() else {
4986 return Task::ready(None);
4987 };
4988 if !item.can_split(cx) {
4989 return Task::ready(None);
4990 }
4991 let task = item.clone_on_split(self.database_id(), window, cx);
4992 cx.spawn_in(window, async move |this, cx| {
4993 if let Some(clone) = task.await {
4994 this.update_in(cx, |this, window, cx| {
4995 let new_pane = this.add_pane(window, cx);
4996 let nav_history = pane.read(cx).fork_nav_history();
4997 new_pane.update(cx, |pane, cx| {
4998 pane.set_nav_history(nav_history, cx);
4999 pane.add_item(clone, true, true, None, window, cx)
5000 });
5001 this.center.split(&pane, &new_pane, direction, cx);
5002 cx.notify();
5003 new_pane
5004 })
5005 .ok()
5006 } else {
5007 None
5008 }
5009 })
5010 }
5011
5012 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5013 let active_item = self.active_pane.read(cx).active_item();
5014 for pane in &self.panes {
5015 join_pane_into_active(&self.active_pane, pane, window, cx);
5016 }
5017 if let Some(active_item) = active_item {
5018 self.activate_item(active_item.as_ref(), true, true, window, cx);
5019 }
5020 cx.notify();
5021 }
5022
5023 pub fn join_pane_into_next(
5024 &mut self,
5025 pane: Entity<Pane>,
5026 window: &mut Window,
5027 cx: &mut Context<Self>,
5028 ) {
5029 let next_pane = self
5030 .find_pane_in_direction(SplitDirection::Right, cx)
5031 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
5032 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
5033 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
5034 let Some(next_pane) = next_pane else {
5035 return;
5036 };
5037 move_all_items(&pane, &next_pane, window, cx);
5038 cx.notify();
5039 }
5040
5041 fn remove_pane(
5042 &mut self,
5043 pane: Entity<Pane>,
5044 focus_on: Option<Entity<Pane>>,
5045 window: &mut Window,
5046 cx: &mut Context<Self>,
5047 ) {
5048 if self.center.remove(&pane, cx).unwrap() {
5049 self.force_remove_pane(&pane, &focus_on, window, cx);
5050 self.unfollow_in_pane(&pane, window, cx);
5051 self.last_leaders_by_pane.remove(&pane.downgrade());
5052 for removed_item in pane.read(cx).items() {
5053 self.panes_by_item.remove(&removed_item.item_id());
5054 }
5055
5056 cx.notify();
5057 } else {
5058 self.active_item_path_changed(true, window, cx);
5059 }
5060 cx.emit(Event::PaneRemoved);
5061 }
5062
5063 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5064 &mut self.panes
5065 }
5066
5067 pub fn panes(&self) -> &[Entity<Pane>] {
5068 &self.panes
5069 }
5070
5071 pub fn active_pane(&self) -> &Entity<Pane> {
5072 &self.active_pane
5073 }
5074
5075 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5076 for dock in self.all_docks() {
5077 if dock.focus_handle(cx).contains_focused(window, cx)
5078 && let Some(pane) = dock
5079 .read(cx)
5080 .active_panel()
5081 .and_then(|panel| panel.pane(cx))
5082 {
5083 return pane;
5084 }
5085 }
5086 self.active_pane().clone()
5087 }
5088
5089 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5090 self.find_pane_in_direction(SplitDirection::Right, cx)
5091 .unwrap_or_else(|| {
5092 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5093 })
5094 }
5095
5096 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5097 self.pane_for_item_id(handle.item_id())
5098 }
5099
5100 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5101 let weak_pane = self.panes_by_item.get(&item_id)?;
5102 weak_pane.upgrade()
5103 }
5104
5105 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5106 self.panes
5107 .iter()
5108 .find(|pane| pane.entity_id() == entity_id)
5109 .cloned()
5110 }
5111
5112 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5113 self.follower_states.retain(|leader_id, state| {
5114 if *leader_id == CollaboratorId::PeerId(peer_id) {
5115 for item in state.items_by_leader_view_id.values() {
5116 item.view.set_leader_id(None, window, cx);
5117 }
5118 false
5119 } else {
5120 true
5121 }
5122 });
5123 cx.notify();
5124 }
5125
5126 pub fn start_following(
5127 &mut self,
5128 leader_id: impl Into<CollaboratorId>,
5129 window: &mut Window,
5130 cx: &mut Context<Self>,
5131 ) -> Option<Task<Result<()>>> {
5132 let leader_id = leader_id.into();
5133 let pane = self.active_pane().clone();
5134
5135 self.last_leaders_by_pane
5136 .insert(pane.downgrade(), leader_id);
5137 self.unfollow(leader_id, window, cx);
5138 self.unfollow_in_pane(&pane, window, cx);
5139 self.follower_states.insert(
5140 leader_id,
5141 FollowerState {
5142 center_pane: pane.clone(),
5143 dock_pane: None,
5144 active_view_id: None,
5145 items_by_leader_view_id: Default::default(),
5146 },
5147 );
5148 cx.notify();
5149
5150 match leader_id {
5151 CollaboratorId::PeerId(leader_peer_id) => {
5152 let room_id = self.active_call()?.room_id(cx)?;
5153 let project_id = self.project.read(cx).remote_id();
5154 let request = self.app_state.client.request(proto::Follow {
5155 room_id,
5156 project_id,
5157 leader_id: Some(leader_peer_id),
5158 });
5159
5160 Some(cx.spawn_in(window, async move |this, cx| {
5161 let response = request.await?;
5162 this.update(cx, |this, _| {
5163 let state = this
5164 .follower_states
5165 .get_mut(&leader_id)
5166 .context("following interrupted")?;
5167 state.active_view_id = response
5168 .active_view
5169 .as_ref()
5170 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5171 anyhow::Ok(())
5172 })??;
5173 if let Some(view) = response.active_view {
5174 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5175 }
5176 this.update_in(cx, |this, window, cx| {
5177 this.leader_updated(leader_id, window, cx)
5178 })?;
5179 Ok(())
5180 }))
5181 }
5182 CollaboratorId::Agent => {
5183 self.leader_updated(leader_id, window, cx)?;
5184 Some(Task::ready(Ok(())))
5185 }
5186 }
5187 }
5188
5189 pub fn follow_next_collaborator(
5190 &mut self,
5191 _: &FollowNextCollaborator,
5192 window: &mut Window,
5193 cx: &mut Context<Self>,
5194 ) {
5195 let collaborators = self.project.read(cx).collaborators();
5196 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5197 let mut collaborators = collaborators.keys().copied();
5198 for peer_id in collaborators.by_ref() {
5199 if CollaboratorId::PeerId(peer_id) == leader_id {
5200 break;
5201 }
5202 }
5203 collaborators.next().map(CollaboratorId::PeerId)
5204 } else if let Some(last_leader_id) =
5205 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5206 {
5207 match last_leader_id {
5208 CollaboratorId::PeerId(peer_id) => {
5209 if collaborators.contains_key(peer_id) {
5210 Some(*last_leader_id)
5211 } else {
5212 None
5213 }
5214 }
5215 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5216 }
5217 } else {
5218 None
5219 };
5220
5221 let pane = self.active_pane.clone();
5222 let Some(leader_id) = next_leader_id.or_else(|| {
5223 Some(CollaboratorId::PeerId(
5224 collaborators.keys().copied().next()?,
5225 ))
5226 }) else {
5227 return;
5228 };
5229 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5230 return;
5231 }
5232 if let Some(task) = self.start_following(leader_id, window, cx) {
5233 task.detach_and_log_err(cx)
5234 }
5235 }
5236
5237 pub fn follow(
5238 &mut self,
5239 leader_id: impl Into<CollaboratorId>,
5240 window: &mut Window,
5241 cx: &mut Context<Self>,
5242 ) {
5243 let leader_id = leader_id.into();
5244
5245 if let CollaboratorId::PeerId(peer_id) = leader_id {
5246 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5247 return;
5248 };
5249 let Some(remote_participant) =
5250 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5251 else {
5252 return;
5253 };
5254
5255 let project = self.project.read(cx);
5256
5257 let other_project_id = match remote_participant.location {
5258 ParticipantLocation::External => None,
5259 ParticipantLocation::UnsharedProject => None,
5260 ParticipantLocation::SharedProject { project_id } => {
5261 if Some(project_id) == project.remote_id() {
5262 None
5263 } else {
5264 Some(project_id)
5265 }
5266 }
5267 };
5268
5269 // if they are active in another project, follow there.
5270 if let Some(project_id) = other_project_id {
5271 let app_state = self.app_state.clone();
5272 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5273 .detach_and_log_err(cx);
5274 }
5275 }
5276
5277 // if you're already following, find the right pane and focus it.
5278 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5279 window.focus(&follower_state.pane().focus_handle(cx), cx);
5280
5281 return;
5282 }
5283
5284 // Otherwise, follow.
5285 if let Some(task) = self.start_following(leader_id, window, cx) {
5286 task.detach_and_log_err(cx)
5287 }
5288 }
5289
5290 pub fn unfollow(
5291 &mut self,
5292 leader_id: impl Into<CollaboratorId>,
5293 window: &mut Window,
5294 cx: &mut Context<Self>,
5295 ) -> Option<()> {
5296 cx.notify();
5297
5298 let leader_id = leader_id.into();
5299 let state = self.follower_states.remove(&leader_id)?;
5300 for (_, item) in state.items_by_leader_view_id {
5301 item.view.set_leader_id(None, window, cx);
5302 }
5303
5304 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5305 let project_id = self.project.read(cx).remote_id();
5306 let room_id = self.active_call()?.room_id(cx)?;
5307 self.app_state
5308 .client
5309 .send(proto::Unfollow {
5310 room_id,
5311 project_id,
5312 leader_id: Some(leader_peer_id),
5313 })
5314 .log_err();
5315 }
5316
5317 Some(())
5318 }
5319
5320 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5321 self.follower_states.contains_key(&id.into())
5322 }
5323
5324 fn active_item_path_changed(
5325 &mut self,
5326 focus_changed: bool,
5327 window: &mut Window,
5328 cx: &mut Context<Self>,
5329 ) {
5330 cx.emit(Event::ActiveItemChanged);
5331 let active_entry = self.active_project_path(cx);
5332 self.project.update(cx, |project, cx| {
5333 project.set_active_path(active_entry.clone(), cx)
5334 });
5335
5336 if focus_changed && let Some(project_path) = &active_entry {
5337 let git_store_entity = self.project.read(cx).git_store().clone();
5338 git_store_entity.update(cx, |git_store, cx| {
5339 git_store.set_active_repo_for_path(project_path, cx);
5340 });
5341 }
5342
5343 self.update_window_title(window, cx);
5344 }
5345
5346 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5347 let project = self.project().read(cx);
5348 let mut title = String::new();
5349
5350 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5351 let name = {
5352 let settings_location = SettingsLocation {
5353 worktree_id: worktree.read(cx).id(),
5354 path: RelPath::empty(),
5355 };
5356
5357 let settings = WorktreeSettings::get(Some(settings_location), cx);
5358 match &settings.project_name {
5359 Some(name) => name.as_str(),
5360 None => worktree.read(cx).root_name_str(),
5361 }
5362 };
5363 if i > 0 {
5364 title.push_str(", ");
5365 }
5366 title.push_str(name);
5367 }
5368
5369 if title.is_empty() {
5370 title = "empty project".to_string();
5371 }
5372
5373 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5374 let filename = path.path.file_name().or_else(|| {
5375 Some(
5376 project
5377 .worktree_for_id(path.worktree_id, cx)?
5378 .read(cx)
5379 .root_name_str(),
5380 )
5381 });
5382
5383 if let Some(filename) = filename {
5384 title.push_str(" — ");
5385 title.push_str(filename.as_ref());
5386 }
5387 }
5388
5389 if project.is_via_collab() {
5390 title.push_str(" ↙");
5391 } else if project.is_shared() {
5392 title.push_str(" ↗");
5393 }
5394
5395 if let Some(last_title) = self.last_window_title.as_ref()
5396 && &title == last_title
5397 {
5398 return;
5399 }
5400 window.set_window_title(&title);
5401 SystemWindowTabController::update_tab_title(
5402 cx,
5403 window.window_handle().window_id(),
5404 SharedString::from(&title),
5405 );
5406 self.last_window_title = Some(title);
5407 }
5408
5409 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5410 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5411 if is_edited != self.window_edited {
5412 self.window_edited = is_edited;
5413 window.set_window_edited(self.window_edited)
5414 }
5415 }
5416
5417 fn update_item_dirty_state(
5418 &mut self,
5419 item: &dyn ItemHandle,
5420 window: &mut Window,
5421 cx: &mut App,
5422 ) {
5423 let is_dirty = item.is_dirty(cx);
5424 let item_id = item.item_id();
5425 let was_dirty = self.dirty_items.contains_key(&item_id);
5426 if is_dirty == was_dirty {
5427 return;
5428 }
5429 if was_dirty {
5430 self.dirty_items.remove(&item_id);
5431 self.update_window_edited(window, cx);
5432 return;
5433 }
5434
5435 let workspace = self.weak_handle();
5436 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5437 return;
5438 };
5439 let on_release_callback = Box::new(move |cx: &mut App| {
5440 window_handle
5441 .update(cx, |_, window, cx| {
5442 workspace
5443 .update(cx, |workspace, cx| {
5444 workspace.dirty_items.remove(&item_id);
5445 workspace.update_window_edited(window, cx)
5446 })
5447 .ok();
5448 })
5449 .ok();
5450 });
5451
5452 let s = item.on_release(cx, on_release_callback);
5453 self.dirty_items.insert(item_id, s);
5454 self.update_window_edited(window, cx);
5455 }
5456
5457 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5458 if self.notifications.is_empty() {
5459 None
5460 } else {
5461 Some(
5462 div()
5463 .absolute()
5464 .right_3()
5465 .bottom_3()
5466 .w_112()
5467 .h_full()
5468 .flex()
5469 .flex_col()
5470 .justify_end()
5471 .gap_2()
5472 .children(
5473 self.notifications
5474 .iter()
5475 .map(|(_, notification)| notification.clone().into_any()),
5476 ),
5477 )
5478 }
5479 }
5480
5481 // RPC handlers
5482
5483 fn active_view_for_follower(
5484 &self,
5485 follower_project_id: Option<u64>,
5486 window: &mut Window,
5487 cx: &mut Context<Self>,
5488 ) -> Option<proto::View> {
5489 let (item, panel_id) = self.active_item_for_followers(window, cx);
5490 let item = item?;
5491 let leader_id = self
5492 .pane_for(&*item)
5493 .and_then(|pane| self.leader_for_pane(&pane));
5494 let leader_peer_id = match leader_id {
5495 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5496 Some(CollaboratorId::Agent) | None => None,
5497 };
5498
5499 let item_handle = item.to_followable_item_handle(cx)?;
5500 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5501 let variant = item_handle.to_state_proto(window, cx)?;
5502
5503 if item_handle.is_project_item(window, cx)
5504 && (follower_project_id.is_none()
5505 || follower_project_id != self.project.read(cx).remote_id())
5506 {
5507 return None;
5508 }
5509
5510 Some(proto::View {
5511 id: id.to_proto(),
5512 leader_id: leader_peer_id,
5513 variant: Some(variant),
5514 panel_id: panel_id.map(|id| id as i32),
5515 })
5516 }
5517
5518 fn handle_follow(
5519 &mut self,
5520 follower_project_id: Option<u64>,
5521 window: &mut Window,
5522 cx: &mut Context<Self>,
5523 ) -> proto::FollowResponse {
5524 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5525
5526 cx.notify();
5527 proto::FollowResponse {
5528 views: active_view.iter().cloned().collect(),
5529 active_view,
5530 }
5531 }
5532
5533 fn handle_update_followers(
5534 &mut self,
5535 leader_id: PeerId,
5536 message: proto::UpdateFollowers,
5537 _window: &mut Window,
5538 _cx: &mut Context<Self>,
5539 ) {
5540 self.leader_updates_tx
5541 .unbounded_send((leader_id, message))
5542 .ok();
5543 }
5544
5545 async fn process_leader_update(
5546 this: &WeakEntity<Self>,
5547 leader_id: PeerId,
5548 update: proto::UpdateFollowers,
5549 cx: &mut AsyncWindowContext,
5550 ) -> Result<()> {
5551 match update.variant.context("invalid update")? {
5552 proto::update_followers::Variant::CreateView(view) => {
5553 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5554 let should_add_view = this.update(cx, |this, _| {
5555 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5556 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5557 } else {
5558 anyhow::Ok(false)
5559 }
5560 })??;
5561
5562 if should_add_view {
5563 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5564 }
5565 }
5566 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5567 let should_add_view = this.update(cx, |this, _| {
5568 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5569 state.active_view_id = update_active_view
5570 .view
5571 .as_ref()
5572 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5573
5574 if state.active_view_id.is_some_and(|view_id| {
5575 !state.items_by_leader_view_id.contains_key(&view_id)
5576 }) {
5577 anyhow::Ok(true)
5578 } else {
5579 anyhow::Ok(false)
5580 }
5581 } else {
5582 anyhow::Ok(false)
5583 }
5584 })??;
5585
5586 if should_add_view && let Some(view) = update_active_view.view {
5587 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5588 }
5589 }
5590 proto::update_followers::Variant::UpdateView(update_view) => {
5591 let variant = update_view.variant.context("missing update view variant")?;
5592 let id = update_view.id.context("missing update view id")?;
5593 let mut tasks = Vec::new();
5594 this.update_in(cx, |this, window, cx| {
5595 let project = this.project.clone();
5596 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5597 let view_id = ViewId::from_proto(id.clone())?;
5598 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5599 tasks.push(item.view.apply_update_proto(
5600 &project,
5601 variant.clone(),
5602 window,
5603 cx,
5604 ));
5605 }
5606 }
5607 anyhow::Ok(())
5608 })??;
5609 try_join_all(tasks).await.log_err();
5610 }
5611 }
5612 this.update_in(cx, |this, window, cx| {
5613 this.leader_updated(leader_id, window, cx)
5614 })?;
5615 Ok(())
5616 }
5617
5618 async fn add_view_from_leader(
5619 this: WeakEntity<Self>,
5620 leader_id: PeerId,
5621 view: &proto::View,
5622 cx: &mut AsyncWindowContext,
5623 ) -> Result<()> {
5624 let this = this.upgrade().context("workspace dropped")?;
5625
5626 let Some(id) = view.id.clone() else {
5627 anyhow::bail!("no id for view");
5628 };
5629 let id = ViewId::from_proto(id)?;
5630 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5631
5632 let pane = this.update(cx, |this, _cx| {
5633 let state = this
5634 .follower_states
5635 .get(&leader_id.into())
5636 .context("stopped following")?;
5637 anyhow::Ok(state.pane().clone())
5638 })?;
5639 let existing_item = pane.update_in(cx, |pane, window, cx| {
5640 let client = this.read(cx).client().clone();
5641 pane.items().find_map(|item| {
5642 let item = item.to_followable_item_handle(cx)?;
5643 if item.remote_id(&client, window, cx) == Some(id) {
5644 Some(item)
5645 } else {
5646 None
5647 }
5648 })
5649 })?;
5650 let item = if let Some(existing_item) = existing_item {
5651 existing_item
5652 } else {
5653 let variant = view.variant.clone();
5654 anyhow::ensure!(variant.is_some(), "missing view variant");
5655
5656 let task = cx.update(|window, cx| {
5657 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5658 })?;
5659
5660 let Some(task) = task else {
5661 anyhow::bail!(
5662 "failed to construct view from leader (maybe from a different version of zed?)"
5663 );
5664 };
5665
5666 let mut new_item = task.await?;
5667 pane.update_in(cx, |pane, window, cx| {
5668 let mut item_to_remove = None;
5669 for (ix, item) in pane.items().enumerate() {
5670 if let Some(item) = item.to_followable_item_handle(cx) {
5671 match new_item.dedup(item.as_ref(), window, cx) {
5672 Some(item::Dedup::KeepExisting) => {
5673 new_item =
5674 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5675 break;
5676 }
5677 Some(item::Dedup::ReplaceExisting) => {
5678 item_to_remove = Some((ix, item.item_id()));
5679 break;
5680 }
5681 None => {}
5682 }
5683 }
5684 }
5685
5686 if let Some((ix, id)) = item_to_remove {
5687 pane.remove_item(id, false, false, window, cx);
5688 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5689 }
5690 })?;
5691
5692 new_item
5693 };
5694
5695 this.update_in(cx, |this, window, cx| {
5696 let state = this.follower_states.get_mut(&leader_id.into())?;
5697 item.set_leader_id(Some(leader_id.into()), window, cx);
5698 state.items_by_leader_view_id.insert(
5699 id,
5700 FollowerView {
5701 view: item,
5702 location: panel_id,
5703 },
5704 );
5705
5706 Some(())
5707 })
5708 .context("no follower state")?;
5709
5710 Ok(())
5711 }
5712
5713 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5714 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5715 return;
5716 };
5717
5718 if let Some(agent_location) = self.project.read(cx).agent_location() {
5719 let buffer_entity_id = agent_location.buffer.entity_id();
5720 let view_id = ViewId {
5721 creator: CollaboratorId::Agent,
5722 id: buffer_entity_id.as_u64(),
5723 };
5724 follower_state.active_view_id = Some(view_id);
5725
5726 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5727 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5728 hash_map::Entry::Vacant(entry) => {
5729 let existing_view =
5730 follower_state
5731 .center_pane
5732 .read(cx)
5733 .items()
5734 .find_map(|item| {
5735 let item = item.to_followable_item_handle(cx)?;
5736 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5737 && item.project_item_model_ids(cx).as_slice()
5738 == [buffer_entity_id]
5739 {
5740 Some(item)
5741 } else {
5742 None
5743 }
5744 });
5745 let view = existing_view.or_else(|| {
5746 agent_location.buffer.upgrade().and_then(|buffer| {
5747 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
5748 registry.build_item(buffer, self.project.clone(), None, window, cx)
5749 })?
5750 .to_followable_item_handle(cx)
5751 })
5752 });
5753
5754 view.map(|view| {
5755 entry.insert(FollowerView {
5756 view,
5757 location: None,
5758 })
5759 })
5760 }
5761 };
5762
5763 if let Some(item) = item {
5764 item.view
5765 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
5766 item.view
5767 .update_agent_location(agent_location.position, window, cx);
5768 }
5769 } else {
5770 follower_state.active_view_id = None;
5771 }
5772
5773 self.leader_updated(CollaboratorId::Agent, window, cx);
5774 }
5775
5776 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
5777 let mut is_project_item = true;
5778 let mut update = proto::UpdateActiveView::default();
5779 if window.is_window_active() {
5780 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
5781
5782 if let Some(item) = active_item
5783 && item.item_focus_handle(cx).contains_focused(window, cx)
5784 {
5785 let leader_id = self
5786 .pane_for(&*item)
5787 .and_then(|pane| self.leader_for_pane(&pane));
5788 let leader_peer_id = match leader_id {
5789 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5790 Some(CollaboratorId::Agent) | None => None,
5791 };
5792
5793 if let Some(item) = item.to_followable_item_handle(cx) {
5794 let id = item
5795 .remote_id(&self.app_state.client, window, cx)
5796 .map(|id| id.to_proto());
5797
5798 if let Some(id) = id
5799 && let Some(variant) = item.to_state_proto(window, cx)
5800 {
5801 let view = Some(proto::View {
5802 id,
5803 leader_id: leader_peer_id,
5804 variant: Some(variant),
5805 panel_id: panel_id.map(|id| id as i32),
5806 });
5807
5808 is_project_item = item.is_project_item(window, cx);
5809 update = proto::UpdateActiveView { view };
5810 };
5811 }
5812 }
5813 }
5814
5815 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
5816 if active_view_id != self.last_active_view_id.as_ref() {
5817 self.last_active_view_id = active_view_id.cloned();
5818 self.update_followers(
5819 is_project_item,
5820 proto::update_followers::Variant::UpdateActiveView(update),
5821 window,
5822 cx,
5823 );
5824 }
5825 }
5826
5827 fn active_item_for_followers(
5828 &self,
5829 window: &mut Window,
5830 cx: &mut App,
5831 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
5832 let mut active_item = None;
5833 let mut panel_id = None;
5834 for dock in self.all_docks() {
5835 if dock.focus_handle(cx).contains_focused(window, cx)
5836 && let Some(panel) = dock.read(cx).active_panel()
5837 && let Some(pane) = panel.pane(cx)
5838 && let Some(item) = pane.read(cx).active_item()
5839 {
5840 active_item = Some(item);
5841 panel_id = panel.remote_id();
5842 break;
5843 }
5844 }
5845
5846 if active_item.is_none() {
5847 active_item = self.active_pane().read(cx).active_item();
5848 }
5849 (active_item, panel_id)
5850 }
5851
5852 fn update_followers(
5853 &self,
5854 project_only: bool,
5855 update: proto::update_followers::Variant,
5856 _: &mut Window,
5857 cx: &mut App,
5858 ) -> Option<()> {
5859 // If this update only applies to for followers in the current project,
5860 // then skip it unless this project is shared. If it applies to all
5861 // followers, regardless of project, then set `project_id` to none,
5862 // indicating that it goes to all followers.
5863 let project_id = if project_only {
5864 Some(self.project.read(cx).remote_id()?)
5865 } else {
5866 None
5867 };
5868 self.app_state().workspace_store.update(cx, |store, cx| {
5869 store.update_followers(project_id, update, cx)
5870 })
5871 }
5872
5873 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
5874 self.follower_states.iter().find_map(|(leader_id, state)| {
5875 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
5876 Some(*leader_id)
5877 } else {
5878 None
5879 }
5880 })
5881 }
5882
5883 fn leader_updated(
5884 &mut self,
5885 leader_id: impl Into<CollaboratorId>,
5886 window: &mut Window,
5887 cx: &mut Context<Self>,
5888 ) -> Option<Box<dyn ItemHandle>> {
5889 cx.notify();
5890
5891 let leader_id = leader_id.into();
5892 let (panel_id, item) = match leader_id {
5893 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
5894 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
5895 };
5896
5897 let state = self.follower_states.get(&leader_id)?;
5898 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
5899 let pane;
5900 if let Some(panel_id) = panel_id {
5901 pane = self
5902 .activate_panel_for_proto_id(panel_id, window, cx)?
5903 .pane(cx)?;
5904 let state = self.follower_states.get_mut(&leader_id)?;
5905 state.dock_pane = Some(pane.clone());
5906 } else {
5907 pane = state.center_pane.clone();
5908 let state = self.follower_states.get_mut(&leader_id)?;
5909 if let Some(dock_pane) = state.dock_pane.take() {
5910 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
5911 }
5912 }
5913
5914 pane.update(cx, |pane, cx| {
5915 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
5916 if let Some(index) = pane.index_for_item(item.as_ref()) {
5917 pane.activate_item(index, false, false, window, cx);
5918 } else {
5919 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
5920 }
5921
5922 if focus_active_item {
5923 pane.focus_active_item(window, cx)
5924 }
5925 });
5926
5927 Some(item)
5928 }
5929
5930 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
5931 let state = self.follower_states.get(&CollaboratorId::Agent)?;
5932 let active_view_id = state.active_view_id?;
5933 Some(
5934 state
5935 .items_by_leader_view_id
5936 .get(&active_view_id)?
5937 .view
5938 .boxed_clone(),
5939 )
5940 }
5941
5942 fn active_item_for_peer(
5943 &self,
5944 peer_id: PeerId,
5945 window: &mut Window,
5946 cx: &mut Context<Self>,
5947 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
5948 let call = self.active_call()?;
5949 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
5950 let leader_in_this_app;
5951 let leader_in_this_project;
5952 match participant.location {
5953 ParticipantLocation::SharedProject { project_id } => {
5954 leader_in_this_app = true;
5955 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
5956 }
5957 ParticipantLocation::UnsharedProject => {
5958 leader_in_this_app = true;
5959 leader_in_this_project = false;
5960 }
5961 ParticipantLocation::External => {
5962 leader_in_this_app = false;
5963 leader_in_this_project = false;
5964 }
5965 };
5966 let state = self.follower_states.get(&peer_id.into())?;
5967 let mut item_to_activate = None;
5968 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
5969 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
5970 && (leader_in_this_project || !item.view.is_project_item(window, cx))
5971 {
5972 item_to_activate = Some((item.location, item.view.boxed_clone()));
5973 }
5974 } else if let Some(shared_screen) =
5975 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
5976 {
5977 item_to_activate = Some((None, Box::new(shared_screen)));
5978 }
5979 item_to_activate
5980 }
5981
5982 fn shared_screen_for_peer(
5983 &self,
5984 peer_id: PeerId,
5985 pane: &Entity<Pane>,
5986 window: &mut Window,
5987 cx: &mut App,
5988 ) -> Option<Entity<SharedScreen>> {
5989 self.active_call()?
5990 .create_shared_screen(peer_id, pane, window, cx)
5991 }
5992
5993 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5994 if window.is_window_active() {
5995 self.update_active_view_for_followers(window, cx);
5996
5997 if let Some(database_id) = self.database_id {
5998 let db = WorkspaceDb::global(cx);
5999 cx.background_spawn(async move { db.update_timestamp(database_id).await })
6000 .detach();
6001 }
6002 } else {
6003 for pane in &self.panes {
6004 pane.update(cx, |pane, cx| {
6005 if let Some(item) = pane.active_item() {
6006 item.workspace_deactivated(window, cx);
6007 }
6008 for item in pane.items() {
6009 if matches!(
6010 item.workspace_settings(cx).autosave,
6011 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
6012 ) {
6013 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
6014 .detach_and_log_err(cx);
6015 }
6016 }
6017 });
6018 }
6019 }
6020 }
6021
6022 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
6023 self.active_call.as_ref().map(|(call, _)| &*call.0)
6024 }
6025
6026 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
6027 self.active_call.as_ref().map(|(call, _)| call.clone())
6028 }
6029
6030 fn on_active_call_event(
6031 &mut self,
6032 event: &ActiveCallEvent,
6033 window: &mut Window,
6034 cx: &mut Context<Self>,
6035 ) {
6036 match event {
6037 ActiveCallEvent::ParticipantLocationChanged { participant_id }
6038 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
6039 self.leader_updated(participant_id, window, cx);
6040 }
6041 }
6042 }
6043
6044 pub fn database_id(&self) -> Option<WorkspaceId> {
6045 self.database_id
6046 }
6047
6048 #[cfg(any(test, feature = "test-support"))]
6049 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
6050 self.database_id = Some(id);
6051 }
6052
6053 pub fn session_id(&self) -> Option<String> {
6054 self.session_id.clone()
6055 }
6056
6057 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6058 let Some(display) = window.display(cx) else {
6059 return Task::ready(());
6060 };
6061 let Ok(display_uuid) = display.uuid() else {
6062 return Task::ready(());
6063 };
6064
6065 let window_bounds = window.inner_window_bounds();
6066 let database_id = self.database_id;
6067 let has_paths = !self.root_paths(cx).is_empty();
6068 let db = WorkspaceDb::global(cx);
6069 let kvp = db::kvp::KeyValueStore::global(cx);
6070
6071 cx.background_executor().spawn(async move {
6072 if !has_paths {
6073 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6074 .await
6075 .log_err();
6076 }
6077 if let Some(database_id) = database_id {
6078 db.set_window_open_status(
6079 database_id,
6080 SerializedWindowBounds(window_bounds),
6081 display_uuid,
6082 )
6083 .await
6084 .log_err();
6085 } else {
6086 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6087 .await
6088 .log_err();
6089 }
6090 })
6091 }
6092
6093 /// Bypass the 200ms serialization throttle and write workspace state to
6094 /// the DB immediately. Returns a task the caller can await to ensure the
6095 /// write completes. Used by the quit handler so the most recent state
6096 /// isn't lost to a pending throttle timer when the process exits.
6097 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6098 self._schedule_serialize_workspace.take();
6099 self._serialize_workspace_task.take();
6100 self.bounds_save_task_queued.take();
6101
6102 let bounds_task = self.save_window_bounds(window, cx);
6103 let serialize_task = self.serialize_workspace_internal(window, cx);
6104 cx.spawn(async move |_| {
6105 bounds_task.await;
6106 serialize_task.await;
6107 })
6108 }
6109
6110 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6111 let project = self.project().read(cx);
6112 project
6113 .visible_worktrees(cx)
6114 .map(|worktree| worktree.read(cx).abs_path())
6115 .collect::<Vec<_>>()
6116 }
6117
6118 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6119 match member {
6120 Member::Axis(PaneAxis { members, .. }) => {
6121 for child in members.iter() {
6122 self.remove_panes(child.clone(), window, cx)
6123 }
6124 }
6125 Member::Pane(pane) => {
6126 self.force_remove_pane(&pane, &None, window, cx);
6127 }
6128 }
6129 }
6130
6131 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6132 self.session_id.take();
6133 self.serialize_workspace_internal(window, cx)
6134 }
6135
6136 fn force_remove_pane(
6137 &mut self,
6138 pane: &Entity<Pane>,
6139 focus_on: &Option<Entity<Pane>>,
6140 window: &mut Window,
6141 cx: &mut Context<Workspace>,
6142 ) {
6143 self.panes.retain(|p| p != pane);
6144 if let Some(focus_on) = focus_on {
6145 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6146 } else if self.active_pane() == pane {
6147 self.panes
6148 .last()
6149 .unwrap()
6150 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6151 }
6152 if self.last_active_center_pane == Some(pane.downgrade()) {
6153 self.last_active_center_pane = None;
6154 }
6155 cx.notify();
6156 }
6157
6158 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6159 if self._schedule_serialize_workspace.is_none() {
6160 self._schedule_serialize_workspace =
6161 Some(cx.spawn_in(window, async move |this, cx| {
6162 cx.background_executor()
6163 .timer(SERIALIZATION_THROTTLE_TIME)
6164 .await;
6165 this.update_in(cx, |this, window, cx| {
6166 this._serialize_workspace_task =
6167 Some(this.serialize_workspace_internal(window, cx));
6168 this._schedule_serialize_workspace.take();
6169 })
6170 .log_err();
6171 }));
6172 }
6173 }
6174
6175 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6176 let Some(database_id) = self.database_id() else {
6177 return Task::ready(());
6178 };
6179
6180 fn serialize_pane_handle(
6181 pane_handle: &Entity<Pane>,
6182 window: &mut Window,
6183 cx: &mut App,
6184 ) -> SerializedPane {
6185 let (items, active, pinned_count) = {
6186 let pane = pane_handle.read(cx);
6187 let active_item_id = pane.active_item().map(|item| item.item_id());
6188 (
6189 pane.items()
6190 .filter_map(|handle| {
6191 let handle = handle.to_serializable_item_handle(cx)?;
6192
6193 Some(SerializedItem {
6194 kind: Arc::from(handle.serialized_item_kind()),
6195 item_id: handle.item_id().as_u64(),
6196 active: Some(handle.item_id()) == active_item_id,
6197 preview: pane.is_active_preview_item(handle.item_id()),
6198 })
6199 })
6200 .collect::<Vec<_>>(),
6201 pane.has_focus(window, cx),
6202 pane.pinned_count(),
6203 )
6204 };
6205
6206 SerializedPane::new(items, active, pinned_count)
6207 }
6208
6209 fn build_serialized_pane_group(
6210 pane_group: &Member,
6211 window: &mut Window,
6212 cx: &mut App,
6213 ) -> SerializedPaneGroup {
6214 match pane_group {
6215 Member::Axis(PaneAxis {
6216 axis,
6217 members,
6218 flexes,
6219 bounding_boxes: _,
6220 }) => SerializedPaneGroup::Group {
6221 axis: SerializedAxis(*axis),
6222 children: members
6223 .iter()
6224 .map(|member| build_serialized_pane_group(member, window, cx))
6225 .collect::<Vec<_>>(),
6226 flexes: Some(flexes.lock().clone()),
6227 },
6228 Member::Pane(pane_handle) => {
6229 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6230 }
6231 }
6232 }
6233
6234 fn build_serialized_docks(
6235 this: &Workspace,
6236 window: &mut Window,
6237 cx: &mut App,
6238 ) -> DockStructure {
6239 this.capture_dock_state(window, cx)
6240 }
6241
6242 match self.workspace_location(cx) {
6243 WorkspaceLocation::Location(location, paths) => {
6244 let breakpoints = self.project.update(cx, |project, cx| {
6245 project
6246 .breakpoint_store()
6247 .read(cx)
6248 .all_source_breakpoints(cx)
6249 });
6250 let user_toolchains = self
6251 .project
6252 .read(cx)
6253 .user_toolchains(cx)
6254 .unwrap_or_default();
6255
6256 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6257 let docks = build_serialized_docks(self, window, cx);
6258 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6259
6260 let serialized_workspace = SerializedWorkspace {
6261 id: database_id,
6262 location,
6263 paths,
6264 center_group,
6265 window_bounds,
6266 display: Default::default(),
6267 docks,
6268 centered_layout: self.centered_layout,
6269 session_id: self.session_id.clone(),
6270 breakpoints,
6271 window_id: Some(window.window_handle().window_id().as_u64()),
6272 user_toolchains,
6273 };
6274
6275 let db = WorkspaceDb::global(cx);
6276 window.spawn(cx, async move |_| {
6277 db.save_workspace(serialized_workspace).await;
6278 })
6279 }
6280 WorkspaceLocation::DetachFromSession => {
6281 let window_bounds = SerializedWindowBounds(window.window_bounds());
6282 let display = window.display(cx).and_then(|d| d.uuid().ok());
6283 // Save dock state for empty local workspaces
6284 let docks = build_serialized_docks(self, window, cx);
6285 let db = WorkspaceDb::global(cx);
6286 let kvp = db::kvp::KeyValueStore::global(cx);
6287 window.spawn(cx, async move |_| {
6288 db.set_window_open_status(
6289 database_id,
6290 window_bounds,
6291 display.unwrap_or_default(),
6292 )
6293 .await
6294 .log_err();
6295 db.set_session_id(database_id, None).await.log_err();
6296 persistence::write_default_dock_state(&kvp, docks)
6297 .await
6298 .log_err();
6299 })
6300 }
6301 WorkspaceLocation::None => {
6302 // Save dock state for empty non-local workspaces
6303 let docks = build_serialized_docks(self, window, cx);
6304 let kvp = db::kvp::KeyValueStore::global(cx);
6305 window.spawn(cx, async move |_| {
6306 persistence::write_default_dock_state(&kvp, docks)
6307 .await
6308 .log_err();
6309 })
6310 }
6311 }
6312 }
6313
6314 fn has_any_items_open(&self, cx: &App) -> bool {
6315 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6316 }
6317
6318 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6319 let paths = PathList::new(&self.root_paths(cx));
6320 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6321 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6322 } else if self.project.read(cx).is_local() {
6323 if !paths.is_empty() || self.has_any_items_open(cx) {
6324 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6325 } else {
6326 WorkspaceLocation::DetachFromSession
6327 }
6328 } else {
6329 WorkspaceLocation::None
6330 }
6331 }
6332
6333 fn update_history(&self, cx: &mut App) {
6334 let Some(id) = self.database_id() else {
6335 return;
6336 };
6337 if !self.project.read(cx).is_local() {
6338 return;
6339 }
6340 if let Some(manager) = HistoryManager::global(cx) {
6341 let paths = PathList::new(&self.root_paths(cx));
6342 manager.update(cx, |this, cx| {
6343 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6344 });
6345 }
6346 }
6347
6348 async fn serialize_items(
6349 this: &WeakEntity<Self>,
6350 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6351 cx: &mut AsyncWindowContext,
6352 ) -> Result<()> {
6353 const CHUNK_SIZE: usize = 200;
6354
6355 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6356
6357 while let Some(items_received) = serializable_items.next().await {
6358 let unique_items =
6359 items_received
6360 .into_iter()
6361 .fold(HashMap::default(), |mut acc, item| {
6362 acc.entry(item.item_id()).or_insert(item);
6363 acc
6364 });
6365
6366 // We use into_iter() here so that the references to the items are moved into
6367 // the tasks and not kept alive while we're sleeping.
6368 for (_, item) in unique_items.into_iter() {
6369 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6370 item.serialize(workspace, false, window, cx)
6371 }) {
6372 cx.background_spawn(async move { task.await.log_err() })
6373 .detach();
6374 }
6375 }
6376
6377 cx.background_executor()
6378 .timer(SERIALIZATION_THROTTLE_TIME)
6379 .await;
6380 }
6381
6382 Ok(())
6383 }
6384
6385 pub(crate) fn enqueue_item_serialization(
6386 &mut self,
6387 item: Box<dyn SerializableItemHandle>,
6388 ) -> Result<()> {
6389 self.serializable_items_tx
6390 .unbounded_send(item)
6391 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6392 }
6393
6394 pub(crate) fn load_workspace(
6395 serialized_workspace: SerializedWorkspace,
6396 paths_to_open: Vec<Option<ProjectPath>>,
6397 window: &mut Window,
6398 cx: &mut Context<Workspace>,
6399 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6400 cx.spawn_in(window, async move |workspace, cx| {
6401 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6402
6403 let mut center_group = None;
6404 let mut center_items = None;
6405
6406 // Traverse the splits tree and add to things
6407 if let Some((group, active_pane, items)) = serialized_workspace
6408 .center_group
6409 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6410 .await
6411 {
6412 center_items = Some(items);
6413 center_group = Some((group, active_pane))
6414 }
6415
6416 let mut items_by_project_path = HashMap::default();
6417 let mut item_ids_by_kind = HashMap::default();
6418 let mut all_deserialized_items = Vec::default();
6419 cx.update(|_, cx| {
6420 for item in center_items.unwrap_or_default().into_iter().flatten() {
6421 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6422 item_ids_by_kind
6423 .entry(serializable_item_handle.serialized_item_kind())
6424 .or_insert(Vec::new())
6425 .push(item.item_id().as_u64() as ItemId);
6426 }
6427
6428 if let Some(project_path) = item.project_path(cx) {
6429 items_by_project_path.insert(project_path, item.clone());
6430 }
6431 all_deserialized_items.push(item);
6432 }
6433 })?;
6434
6435 let opened_items = paths_to_open
6436 .into_iter()
6437 .map(|path_to_open| {
6438 path_to_open
6439 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6440 })
6441 .collect::<Vec<_>>();
6442
6443 // Remove old panes from workspace panes list
6444 workspace.update_in(cx, |workspace, window, cx| {
6445 if let Some((center_group, active_pane)) = center_group {
6446 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6447
6448 // Swap workspace center group
6449 workspace.center = PaneGroup::with_root(center_group);
6450 workspace.center.set_is_center(true);
6451 workspace.center.mark_positions(cx);
6452
6453 if let Some(active_pane) = active_pane {
6454 workspace.set_active_pane(&active_pane, window, cx);
6455 cx.focus_self(window);
6456 } else {
6457 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6458 }
6459 }
6460
6461 let docks = serialized_workspace.docks;
6462
6463 for (dock, serialized_dock) in [
6464 (&mut workspace.right_dock, docks.right),
6465 (&mut workspace.left_dock, docks.left),
6466 (&mut workspace.bottom_dock, docks.bottom),
6467 ]
6468 .iter_mut()
6469 {
6470 dock.update(cx, |dock, cx| {
6471 dock.serialized_dock = Some(serialized_dock.clone());
6472 dock.restore_state(window, cx);
6473 });
6474 }
6475
6476 cx.notify();
6477 })?;
6478
6479 let _ = project
6480 .update(cx, |project, cx| {
6481 project
6482 .breakpoint_store()
6483 .update(cx, |breakpoint_store, cx| {
6484 breakpoint_store
6485 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6486 })
6487 })
6488 .await;
6489
6490 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6491 // after loading the items, we might have different items and in order to avoid
6492 // the database filling up, we delete items that haven't been loaded now.
6493 //
6494 // The items that have been loaded, have been saved after they've been added to the workspace.
6495 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6496 item_ids_by_kind
6497 .into_iter()
6498 .map(|(item_kind, loaded_items)| {
6499 SerializableItemRegistry::cleanup(
6500 item_kind,
6501 serialized_workspace.id,
6502 loaded_items,
6503 window,
6504 cx,
6505 )
6506 .log_err()
6507 })
6508 .collect::<Vec<_>>()
6509 })?;
6510
6511 futures::future::join_all(clean_up_tasks).await;
6512
6513 workspace
6514 .update_in(cx, |workspace, window, cx| {
6515 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6516 workspace.serialize_workspace_internal(window, cx).detach();
6517
6518 // Ensure that we mark the window as edited if we did load dirty items
6519 workspace.update_window_edited(window, cx);
6520 })
6521 .ok();
6522
6523 Ok(opened_items)
6524 })
6525 }
6526
6527 pub fn key_context(&self, cx: &App) -> KeyContext {
6528 let mut context = KeyContext::new_with_defaults();
6529 context.add("Workspace");
6530 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6531 if let Some(status) = self
6532 .debugger_provider
6533 .as_ref()
6534 .and_then(|provider| provider.active_thread_state(cx))
6535 {
6536 match status {
6537 ThreadStatus::Running | ThreadStatus::Stepping => {
6538 context.add("debugger_running");
6539 }
6540 ThreadStatus::Stopped => context.add("debugger_stopped"),
6541 ThreadStatus::Exited | ThreadStatus::Ended => {}
6542 }
6543 }
6544
6545 if self.left_dock.read(cx).is_open() {
6546 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6547 context.set("left_dock", active_panel.panel_key());
6548 }
6549 }
6550
6551 if self.right_dock.read(cx).is_open() {
6552 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6553 context.set("right_dock", active_panel.panel_key());
6554 }
6555 }
6556
6557 if self.bottom_dock.read(cx).is_open() {
6558 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6559 context.set("bottom_dock", active_panel.panel_key());
6560 }
6561 }
6562
6563 context
6564 }
6565
6566 /// Multiworkspace uses this to add workspace action handling to itself
6567 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6568 self.add_workspace_actions_listeners(div, window, cx)
6569 .on_action(cx.listener(
6570 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6571 for action in &action_sequence.0 {
6572 window.dispatch_action(action.boxed_clone(), cx);
6573 }
6574 },
6575 ))
6576 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6577 .on_action(cx.listener(Self::close_all_items_and_panes))
6578 .on_action(cx.listener(Self::close_item_in_all_panes))
6579 .on_action(cx.listener(Self::save_all))
6580 .on_action(cx.listener(Self::send_keystrokes))
6581 .on_action(cx.listener(Self::add_folder_to_project))
6582 .on_action(cx.listener(Self::follow_next_collaborator))
6583 .on_action(cx.listener(Self::activate_pane_at_index))
6584 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6585 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6586 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6587 .on_action(cx.listener(Self::toggle_theme_mode))
6588 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6589 let pane = workspace.active_pane().clone();
6590 workspace.unfollow_in_pane(&pane, window, cx);
6591 }))
6592 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6593 workspace
6594 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6595 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6596 }))
6597 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6598 workspace
6599 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6600 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6601 }))
6602 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6603 workspace
6604 .save_active_item(SaveIntent::SaveAs, window, cx)
6605 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6606 }))
6607 .on_action(
6608 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6609 workspace.activate_previous_pane(window, cx)
6610 }),
6611 )
6612 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6613 workspace.activate_next_pane(window, cx)
6614 }))
6615 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6616 workspace.activate_last_pane(window, cx)
6617 }))
6618 .on_action(
6619 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6620 workspace.activate_next_window(cx)
6621 }),
6622 )
6623 .on_action(
6624 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6625 workspace.activate_previous_window(cx)
6626 }),
6627 )
6628 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6629 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6630 }))
6631 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6632 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6633 }))
6634 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6635 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6636 }))
6637 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6638 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6639 }))
6640 .on_action(cx.listener(
6641 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6642 workspace.move_item_to_pane_in_direction(action, window, cx)
6643 },
6644 ))
6645 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6646 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6647 }))
6648 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6649 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6650 }))
6651 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6652 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6653 }))
6654 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6655 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6656 }))
6657 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6658 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6659 SplitDirection::Down,
6660 SplitDirection::Up,
6661 SplitDirection::Right,
6662 SplitDirection::Left,
6663 ];
6664 for dir in DIRECTION_PRIORITY {
6665 if workspace.find_pane_in_direction(dir, cx).is_some() {
6666 workspace.swap_pane_in_direction(dir, cx);
6667 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6668 break;
6669 }
6670 }
6671 }))
6672 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6673 workspace.move_pane_to_border(SplitDirection::Left, cx)
6674 }))
6675 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6676 workspace.move_pane_to_border(SplitDirection::Right, cx)
6677 }))
6678 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6679 workspace.move_pane_to_border(SplitDirection::Up, cx)
6680 }))
6681 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6682 workspace.move_pane_to_border(SplitDirection::Down, cx)
6683 }))
6684 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6685 this.toggle_dock(DockPosition::Left, window, cx);
6686 }))
6687 .on_action(cx.listener(
6688 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6689 workspace.toggle_dock(DockPosition::Right, window, cx);
6690 },
6691 ))
6692 .on_action(cx.listener(
6693 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6694 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6695 },
6696 ))
6697 .on_action(cx.listener(
6698 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6699 if !workspace.close_active_dock(window, cx) {
6700 cx.propagate();
6701 }
6702 },
6703 ))
6704 .on_action(
6705 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6706 workspace.close_all_docks(window, cx);
6707 }),
6708 )
6709 .on_action(cx.listener(Self::toggle_all_docks))
6710 .on_action(cx.listener(
6711 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6712 workspace.clear_all_notifications(cx);
6713 },
6714 ))
6715 .on_action(cx.listener(
6716 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6717 workspace.clear_navigation_history(window, cx);
6718 },
6719 ))
6720 .on_action(cx.listener(
6721 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6722 if let Some((notification_id, _)) = workspace.notifications.pop() {
6723 workspace.suppress_notification(¬ification_id, cx);
6724 }
6725 },
6726 ))
6727 .on_action(cx.listener(
6728 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6729 workspace.show_worktree_trust_security_modal(true, window, cx);
6730 },
6731 ))
6732 .on_action(
6733 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6734 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6735 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6736 trusted_worktrees.clear_trusted_paths()
6737 });
6738 let db = WorkspaceDb::global(cx);
6739 cx.spawn(async move |_, cx| {
6740 if db.clear_trusted_worktrees().await.log_err().is_some() {
6741 cx.update(|cx| reload(cx));
6742 }
6743 })
6744 .detach();
6745 }
6746 }),
6747 )
6748 .on_action(cx.listener(
6749 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
6750 workspace.reopen_closed_item(window, cx).detach();
6751 },
6752 ))
6753 .on_action(cx.listener(
6754 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
6755 for dock in workspace.all_docks() {
6756 if dock.focus_handle(cx).contains_focused(window, cx) {
6757 let Some(panel) = dock.read(cx).active_panel() else {
6758 return;
6759 };
6760
6761 // Set to `None`, then the size will fall back to the default.
6762 panel.clone().set_size(None, window, cx);
6763
6764 return;
6765 }
6766 }
6767 },
6768 ))
6769 .on_action(cx.listener(
6770 |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
6771 for dock in workspace.all_docks() {
6772 if let Some(panel) = dock.read(cx).visible_panel() {
6773 // Set to `None`, then the size will fall back to the default.
6774 panel.clone().set_size(None, window, cx);
6775 }
6776 }
6777 },
6778 ))
6779 .on_action(cx.listener(
6780 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
6781 adjust_active_dock_size_by_px(
6782 px_with_ui_font_fallback(act.px, cx),
6783 workspace,
6784 window,
6785 cx,
6786 );
6787 },
6788 ))
6789 .on_action(cx.listener(
6790 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
6791 adjust_active_dock_size_by_px(
6792 px_with_ui_font_fallback(act.px, cx) * -1.,
6793 workspace,
6794 window,
6795 cx,
6796 );
6797 },
6798 ))
6799 .on_action(cx.listener(
6800 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
6801 adjust_open_docks_size_by_px(
6802 px_with_ui_font_fallback(act.px, cx),
6803 workspace,
6804 window,
6805 cx,
6806 );
6807 },
6808 ))
6809 .on_action(cx.listener(
6810 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
6811 adjust_open_docks_size_by_px(
6812 px_with_ui_font_fallback(act.px, cx) * -1.,
6813 workspace,
6814 window,
6815 cx,
6816 );
6817 },
6818 ))
6819 .on_action(cx.listener(Workspace::toggle_centered_layout))
6820 .on_action(cx.listener(
6821 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
6822 if let Some(active_dock) = workspace.active_dock(window, cx) {
6823 let dock = active_dock.read(cx);
6824 if let Some(active_panel) = dock.active_panel() {
6825 if active_panel.pane(cx).is_none() {
6826 let mut recent_pane: Option<Entity<Pane>> = None;
6827 let mut recent_timestamp = 0;
6828 for pane_handle in workspace.panes() {
6829 let pane = pane_handle.read(cx);
6830 for entry in pane.activation_history() {
6831 if entry.timestamp > recent_timestamp {
6832 recent_timestamp = entry.timestamp;
6833 recent_pane = Some(pane_handle.clone());
6834 }
6835 }
6836 }
6837
6838 if let Some(pane) = recent_pane {
6839 pane.update(cx, |pane, cx| {
6840 let current_index = pane.active_item_index();
6841 let items_len = pane.items_len();
6842 if items_len > 0 {
6843 let next_index = if current_index + 1 < items_len {
6844 current_index + 1
6845 } else {
6846 0
6847 };
6848 pane.activate_item(
6849 next_index, false, false, window, cx,
6850 );
6851 }
6852 });
6853 return;
6854 }
6855 }
6856 }
6857 }
6858 cx.propagate();
6859 },
6860 ))
6861 .on_action(cx.listener(
6862 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
6863 if let Some(active_dock) = workspace.active_dock(window, cx) {
6864 let dock = active_dock.read(cx);
6865 if let Some(active_panel) = dock.active_panel() {
6866 if active_panel.pane(cx).is_none() {
6867 let mut recent_pane: Option<Entity<Pane>> = None;
6868 let mut recent_timestamp = 0;
6869 for pane_handle in workspace.panes() {
6870 let pane = pane_handle.read(cx);
6871 for entry in pane.activation_history() {
6872 if entry.timestamp > recent_timestamp {
6873 recent_timestamp = entry.timestamp;
6874 recent_pane = Some(pane_handle.clone());
6875 }
6876 }
6877 }
6878
6879 if let Some(pane) = recent_pane {
6880 pane.update(cx, |pane, cx| {
6881 let current_index = pane.active_item_index();
6882 let items_len = pane.items_len();
6883 if items_len > 0 {
6884 let prev_index = if current_index > 0 {
6885 current_index - 1
6886 } else {
6887 items_len.saturating_sub(1)
6888 };
6889 pane.activate_item(
6890 prev_index, false, false, window, cx,
6891 );
6892 }
6893 });
6894 return;
6895 }
6896 }
6897 }
6898 }
6899 cx.propagate();
6900 },
6901 ))
6902 .on_action(cx.listener(
6903 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
6904 if let Some(active_dock) = workspace.active_dock(window, cx) {
6905 let dock = active_dock.read(cx);
6906 if let Some(active_panel) = dock.active_panel() {
6907 if active_panel.pane(cx).is_none() {
6908 let active_pane = workspace.active_pane().clone();
6909 active_pane.update(cx, |pane, cx| {
6910 pane.close_active_item(action, window, cx)
6911 .detach_and_log_err(cx);
6912 });
6913 return;
6914 }
6915 }
6916 }
6917 cx.propagate();
6918 },
6919 ))
6920 .on_action(
6921 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
6922 let pane = workspace.active_pane().clone();
6923 if let Some(item) = pane.read(cx).active_item() {
6924 item.toggle_read_only(window, cx);
6925 }
6926 }),
6927 )
6928 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
6929 workspace.focus_center_pane(window, cx);
6930 }))
6931 .on_action(cx.listener(Workspace::cancel))
6932 }
6933
6934 #[cfg(any(test, feature = "test-support"))]
6935 pub fn set_random_database_id(&mut self) {
6936 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
6937 }
6938
6939 #[cfg(any(test, feature = "test-support"))]
6940 pub(crate) fn test_new(
6941 project: Entity<Project>,
6942 window: &mut Window,
6943 cx: &mut Context<Self>,
6944 ) -> Self {
6945 use node_runtime::NodeRuntime;
6946 use session::Session;
6947
6948 let client = project.read(cx).client();
6949 let user_store = project.read(cx).user_store();
6950 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
6951 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
6952 window.activate_window();
6953 let app_state = Arc::new(AppState {
6954 languages: project.read(cx).languages().clone(),
6955 workspace_store,
6956 client,
6957 user_store,
6958 fs: project.read(cx).fs().clone(),
6959 build_window_options: |_, _| Default::default(),
6960 node_runtime: NodeRuntime::unavailable(),
6961 session,
6962 });
6963 let workspace = Self::new(Default::default(), project, app_state, window, cx);
6964 workspace
6965 .active_pane
6966 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6967 workspace
6968 }
6969
6970 pub fn register_action<A: Action>(
6971 &mut self,
6972 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
6973 ) -> &mut Self {
6974 let callback = Arc::new(callback);
6975
6976 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
6977 let callback = callback.clone();
6978 div.on_action(cx.listener(move |workspace, event, window, cx| {
6979 (callback)(workspace, event, window, cx)
6980 }))
6981 }));
6982 self
6983 }
6984 pub fn register_action_renderer(
6985 &mut self,
6986 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
6987 ) -> &mut Self {
6988 self.workspace_actions.push(Box::new(callback));
6989 self
6990 }
6991
6992 fn add_workspace_actions_listeners(
6993 &self,
6994 mut div: Div,
6995 window: &mut Window,
6996 cx: &mut Context<Self>,
6997 ) -> Div {
6998 for action in self.workspace_actions.iter() {
6999 div = (action)(div, self, window, cx)
7000 }
7001 div
7002 }
7003
7004 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
7005 self.modal_layer.read(cx).has_active_modal()
7006 }
7007
7008 pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
7009 self.modal_layer
7010 .read(cx)
7011 .is_active_modal_command_palette(cx)
7012 }
7013
7014 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
7015 self.modal_layer.read(cx).active_modal()
7016 }
7017
7018 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
7019 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
7020 /// If no modal is active, the new modal will be shown.
7021 ///
7022 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
7023 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
7024 /// will not be shown.
7025 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
7026 where
7027 B: FnOnce(&mut Window, &mut Context<V>) -> V,
7028 {
7029 self.modal_layer.update(cx, |modal_layer, cx| {
7030 modal_layer.toggle_modal(window, cx, build)
7031 })
7032 }
7033
7034 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
7035 self.modal_layer
7036 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
7037 }
7038
7039 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
7040 self.toast_layer
7041 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
7042 }
7043
7044 pub fn toggle_centered_layout(
7045 &mut self,
7046 _: &ToggleCenteredLayout,
7047 _: &mut Window,
7048 cx: &mut Context<Self>,
7049 ) {
7050 self.centered_layout = !self.centered_layout;
7051 if let Some(database_id) = self.database_id() {
7052 let db = WorkspaceDb::global(cx);
7053 let centered_layout = self.centered_layout;
7054 cx.background_spawn(async move {
7055 db.set_centered_layout(database_id, centered_layout).await
7056 })
7057 .detach_and_log_err(cx);
7058 }
7059 cx.notify();
7060 }
7061
7062 fn adjust_padding(padding: Option<f32>) -> f32 {
7063 padding
7064 .unwrap_or(CenteredPaddingSettings::default().0)
7065 .clamp(
7066 CenteredPaddingSettings::MIN_PADDING,
7067 CenteredPaddingSettings::MAX_PADDING,
7068 )
7069 }
7070
7071 fn render_dock(
7072 &self,
7073 position: DockPosition,
7074 dock: &Entity<Dock>,
7075 window: &mut Window,
7076 cx: &mut App,
7077 ) -> Option<Div> {
7078 if self.zoomed_position == Some(position) {
7079 return None;
7080 }
7081
7082 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7083 let pane = panel.pane(cx)?;
7084 let follower_states = &self.follower_states;
7085 leader_border_for_pane(follower_states, &pane, window, cx)
7086 });
7087
7088 Some(
7089 div()
7090 .flex()
7091 .flex_none()
7092 .overflow_hidden()
7093 .child(dock.clone())
7094 .children(leader_border),
7095 )
7096 }
7097
7098 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7099 window
7100 .root::<MultiWorkspace>()
7101 .flatten()
7102 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7103 }
7104
7105 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7106 self.zoomed.as_ref()
7107 }
7108
7109 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7110 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7111 return;
7112 };
7113 let windows = cx.windows();
7114 let next_window =
7115 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7116 || {
7117 windows
7118 .iter()
7119 .cycle()
7120 .skip_while(|window| window.window_id() != current_window_id)
7121 .nth(1)
7122 },
7123 );
7124
7125 if let Some(window) = next_window {
7126 window
7127 .update(cx, |_, window, _| window.activate_window())
7128 .ok();
7129 }
7130 }
7131
7132 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7133 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7134 return;
7135 };
7136 let windows = cx.windows();
7137 let prev_window =
7138 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7139 || {
7140 windows
7141 .iter()
7142 .rev()
7143 .cycle()
7144 .skip_while(|window| window.window_id() != current_window_id)
7145 .nth(1)
7146 },
7147 );
7148
7149 if let Some(window) = prev_window {
7150 window
7151 .update(cx, |_, window, _| window.activate_window())
7152 .ok();
7153 }
7154 }
7155
7156 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7157 if cx.stop_active_drag(window) {
7158 } else if let Some((notification_id, _)) = self.notifications.pop() {
7159 dismiss_app_notification(¬ification_id, cx);
7160 } else {
7161 cx.propagate();
7162 }
7163 }
7164
7165 fn adjust_dock_size_by_px(
7166 &mut self,
7167 panel_size: Pixels,
7168 dock_pos: DockPosition,
7169 px: Pixels,
7170 window: &mut Window,
7171 cx: &mut Context<Self>,
7172 ) {
7173 match dock_pos {
7174 DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
7175 DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
7176 DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
7177 }
7178 }
7179
7180 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7181 let workspace_width = self.bounds.size.width;
7182 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7183
7184 self.right_dock.read_with(cx, |right_dock, cx| {
7185 let right_dock_size = right_dock
7186 .active_panel_size(window, cx)
7187 .unwrap_or(Pixels::ZERO);
7188 if right_dock_size + size > workspace_width {
7189 size = workspace_width - right_dock_size
7190 }
7191 });
7192
7193 self.left_dock.update(cx, |left_dock, cx| {
7194 if WorkspaceSettings::get_global(cx)
7195 .resize_all_panels_in_dock
7196 .contains(&DockPosition::Left)
7197 {
7198 left_dock.resize_all_panels(Some(size), window, cx);
7199 } else {
7200 left_dock.resize_active_panel(Some(size), window, cx);
7201 }
7202 });
7203 }
7204
7205 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7206 let workspace_width = self.bounds.size.width;
7207 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7208 self.left_dock.read_with(cx, |left_dock, cx| {
7209 let left_dock_size = left_dock
7210 .active_panel_size(window, cx)
7211 .unwrap_or(Pixels::ZERO);
7212 if left_dock_size + size > workspace_width {
7213 size = workspace_width - left_dock_size
7214 }
7215 });
7216 self.right_dock.update(cx, |right_dock, cx| {
7217 if WorkspaceSettings::get_global(cx)
7218 .resize_all_panels_in_dock
7219 .contains(&DockPosition::Right)
7220 {
7221 right_dock.resize_all_panels(Some(size), window, cx);
7222 } else {
7223 right_dock.resize_active_panel(Some(size), window, cx);
7224 }
7225 });
7226 }
7227
7228 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7229 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7230 self.bottom_dock.update(cx, |bottom_dock, cx| {
7231 if WorkspaceSettings::get_global(cx)
7232 .resize_all_panels_in_dock
7233 .contains(&DockPosition::Bottom)
7234 {
7235 bottom_dock.resize_all_panels(Some(size), window, cx);
7236 } else {
7237 bottom_dock.resize_active_panel(Some(size), window, cx);
7238 }
7239 });
7240 }
7241
7242 fn toggle_edit_predictions_all_files(
7243 &mut self,
7244 _: &ToggleEditPrediction,
7245 _window: &mut Window,
7246 cx: &mut Context<Self>,
7247 ) {
7248 let fs = self.project().read(cx).fs().clone();
7249 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7250 update_settings_file(fs, cx, move |file, _| {
7251 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7252 });
7253 }
7254
7255 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7256 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7257 let next_mode = match current_mode {
7258 Some(theme::ThemeAppearanceMode::Light) => theme::ThemeAppearanceMode::Dark,
7259 Some(theme::ThemeAppearanceMode::Dark) => theme::ThemeAppearanceMode::Light,
7260 Some(theme::ThemeAppearanceMode::System) | None => match cx.theme().appearance() {
7261 theme::Appearance::Light => theme::ThemeAppearanceMode::Dark,
7262 theme::Appearance::Dark => theme::ThemeAppearanceMode::Light,
7263 },
7264 };
7265
7266 let fs = self.project().read(cx).fs().clone();
7267 settings::update_settings_file(fs, cx, move |settings, _cx| {
7268 theme::set_mode(settings, next_mode);
7269 });
7270 }
7271
7272 pub fn show_worktree_trust_security_modal(
7273 &mut self,
7274 toggle: bool,
7275 window: &mut Window,
7276 cx: &mut Context<Self>,
7277 ) {
7278 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7279 if toggle {
7280 security_modal.update(cx, |security_modal, cx| {
7281 security_modal.dismiss(cx);
7282 })
7283 } else {
7284 security_modal.update(cx, |security_modal, cx| {
7285 security_modal.refresh_restricted_paths(cx);
7286 });
7287 }
7288 } else {
7289 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7290 .map(|trusted_worktrees| {
7291 trusted_worktrees
7292 .read(cx)
7293 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7294 })
7295 .unwrap_or(false);
7296 if has_restricted_worktrees {
7297 let project = self.project().read(cx);
7298 let remote_host = project
7299 .remote_connection_options(cx)
7300 .map(RemoteHostLocation::from);
7301 let worktree_store = project.worktree_store().downgrade();
7302 self.toggle_modal(window, cx, |_, cx| {
7303 SecurityModal::new(worktree_store, remote_host, cx)
7304 });
7305 }
7306 }
7307 }
7308}
7309
7310pub trait AnyActiveCall {
7311 fn entity(&self) -> AnyEntity;
7312 fn is_in_room(&self, _: &App) -> bool;
7313 fn room_id(&self, _: &App) -> Option<u64>;
7314 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7315 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7316 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7317 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7318 fn is_sharing_project(&self, _: &App) -> bool;
7319 fn has_remote_participants(&self, _: &App) -> bool;
7320 fn local_participant_is_guest(&self, _: &App) -> bool;
7321 fn client(&self, _: &App) -> Arc<Client>;
7322 fn share_on_join(&self, _: &App) -> bool;
7323 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7324 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7325 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7326 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7327 fn join_project(
7328 &self,
7329 _: u64,
7330 _: Arc<LanguageRegistry>,
7331 _: Arc<dyn Fs>,
7332 _: &mut App,
7333 ) -> Task<Result<Entity<Project>>>;
7334 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7335 fn subscribe(
7336 &self,
7337 _: &mut Window,
7338 _: &mut Context<Workspace>,
7339 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7340 ) -> Subscription;
7341 fn create_shared_screen(
7342 &self,
7343 _: PeerId,
7344 _: &Entity<Pane>,
7345 _: &mut Window,
7346 _: &mut App,
7347 ) -> Option<Entity<SharedScreen>>;
7348}
7349
7350#[derive(Clone)]
7351pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7352impl Global for GlobalAnyActiveCall {}
7353
7354impl GlobalAnyActiveCall {
7355 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7356 cx.try_global()
7357 }
7358
7359 pub(crate) fn global(cx: &App) -> &Self {
7360 cx.global()
7361 }
7362}
7363
7364pub fn merge_conflict_notification_id() -> NotificationId {
7365 struct MergeConflictNotification;
7366 NotificationId::unique::<MergeConflictNotification>()
7367}
7368
7369/// Workspace-local view of a remote participant's location.
7370#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7371pub enum ParticipantLocation {
7372 SharedProject { project_id: u64 },
7373 UnsharedProject,
7374 External,
7375}
7376
7377impl ParticipantLocation {
7378 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7379 match location
7380 .and_then(|l| l.variant)
7381 .context("participant location was not provided")?
7382 {
7383 proto::participant_location::Variant::SharedProject(project) => {
7384 Ok(Self::SharedProject {
7385 project_id: project.id,
7386 })
7387 }
7388 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7389 proto::participant_location::Variant::External(_) => Ok(Self::External),
7390 }
7391 }
7392}
7393/// Workspace-local view of a remote collaborator's state.
7394/// This is the subset of `call::RemoteParticipant` that workspace needs.
7395#[derive(Clone)]
7396pub struct RemoteCollaborator {
7397 pub user: Arc<User>,
7398 pub peer_id: PeerId,
7399 pub location: ParticipantLocation,
7400 pub participant_index: ParticipantIndex,
7401}
7402
7403pub enum ActiveCallEvent {
7404 ParticipantLocationChanged { participant_id: PeerId },
7405 RemoteVideoTracksChanged { participant_id: PeerId },
7406}
7407
7408fn leader_border_for_pane(
7409 follower_states: &HashMap<CollaboratorId, FollowerState>,
7410 pane: &Entity<Pane>,
7411 _: &Window,
7412 cx: &App,
7413) -> Option<Div> {
7414 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7415 if state.pane() == pane {
7416 Some((*leader_id, state))
7417 } else {
7418 None
7419 }
7420 })?;
7421
7422 let mut leader_color = match leader_id {
7423 CollaboratorId::PeerId(leader_peer_id) => {
7424 let leader = GlobalAnyActiveCall::try_global(cx)?
7425 .0
7426 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7427
7428 cx.theme()
7429 .players()
7430 .color_for_participant(leader.participant_index.0)
7431 .cursor
7432 }
7433 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7434 };
7435 leader_color.fade_out(0.3);
7436 Some(
7437 div()
7438 .absolute()
7439 .size_full()
7440 .left_0()
7441 .top_0()
7442 .border_2()
7443 .border_color(leader_color),
7444 )
7445}
7446
7447fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7448 ZED_WINDOW_POSITION
7449 .zip(*ZED_WINDOW_SIZE)
7450 .map(|(position, size)| Bounds {
7451 origin: position,
7452 size,
7453 })
7454}
7455
7456fn open_items(
7457 serialized_workspace: Option<SerializedWorkspace>,
7458 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7459 window: &mut Window,
7460 cx: &mut Context<Workspace>,
7461) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7462 let restored_items = serialized_workspace.map(|serialized_workspace| {
7463 Workspace::load_workspace(
7464 serialized_workspace,
7465 project_paths_to_open
7466 .iter()
7467 .map(|(_, project_path)| project_path)
7468 .cloned()
7469 .collect(),
7470 window,
7471 cx,
7472 )
7473 });
7474
7475 cx.spawn_in(window, async move |workspace, cx| {
7476 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7477
7478 if let Some(restored_items) = restored_items {
7479 let restored_items = restored_items.await?;
7480
7481 let restored_project_paths = restored_items
7482 .iter()
7483 .filter_map(|item| {
7484 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7485 .ok()
7486 .flatten()
7487 })
7488 .collect::<HashSet<_>>();
7489
7490 for restored_item in restored_items {
7491 opened_items.push(restored_item.map(Ok));
7492 }
7493
7494 project_paths_to_open
7495 .iter_mut()
7496 .for_each(|(_, project_path)| {
7497 if let Some(project_path_to_open) = project_path
7498 && restored_project_paths.contains(project_path_to_open)
7499 {
7500 *project_path = None;
7501 }
7502 });
7503 } else {
7504 for _ in 0..project_paths_to_open.len() {
7505 opened_items.push(None);
7506 }
7507 }
7508 assert!(opened_items.len() == project_paths_to_open.len());
7509
7510 let tasks =
7511 project_paths_to_open
7512 .into_iter()
7513 .enumerate()
7514 .map(|(ix, (abs_path, project_path))| {
7515 let workspace = workspace.clone();
7516 cx.spawn(async move |cx| {
7517 let file_project_path = project_path?;
7518 let abs_path_task = workspace.update(cx, |workspace, cx| {
7519 workspace.project().update(cx, |project, cx| {
7520 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7521 })
7522 });
7523
7524 // We only want to open file paths here. If one of the items
7525 // here is a directory, it was already opened further above
7526 // with a `find_or_create_worktree`.
7527 if let Ok(task) = abs_path_task
7528 && task.await.is_none_or(|p| p.is_file())
7529 {
7530 return Some((
7531 ix,
7532 workspace
7533 .update_in(cx, |workspace, window, cx| {
7534 workspace.open_path(
7535 file_project_path,
7536 None,
7537 true,
7538 window,
7539 cx,
7540 )
7541 })
7542 .log_err()?
7543 .await,
7544 ));
7545 }
7546 None
7547 })
7548 });
7549
7550 let tasks = tasks.collect::<Vec<_>>();
7551
7552 let tasks = futures::future::join_all(tasks);
7553 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7554 opened_items[ix] = Some(path_open_result);
7555 }
7556
7557 Ok(opened_items)
7558 })
7559}
7560
7561#[derive(Clone)]
7562enum ActivateInDirectionTarget {
7563 Pane(Entity<Pane>),
7564 Dock(Entity<Dock>),
7565 Sidebar(FocusHandle),
7566}
7567
7568fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7569 window
7570 .update(cx, |multi_workspace, _, cx| {
7571 let workspace = multi_workspace.workspace().clone();
7572 workspace.update(cx, |workspace, cx| {
7573 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7574 struct DatabaseFailedNotification;
7575
7576 workspace.show_notification(
7577 NotificationId::unique::<DatabaseFailedNotification>(),
7578 cx,
7579 |cx| {
7580 cx.new(|cx| {
7581 MessageNotification::new("Failed to load the database file.", cx)
7582 .primary_message("File an Issue")
7583 .primary_icon(IconName::Plus)
7584 .primary_on_click(|window, cx| {
7585 window.dispatch_action(Box::new(FileBugReport), cx)
7586 })
7587 })
7588 },
7589 );
7590 }
7591 });
7592 })
7593 .log_err();
7594}
7595
7596fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7597 if val == 0 {
7598 ThemeSettings::get_global(cx).ui_font_size(cx)
7599 } else {
7600 px(val as f32)
7601 }
7602}
7603
7604fn adjust_active_dock_size_by_px(
7605 px: Pixels,
7606 workspace: &mut Workspace,
7607 window: &mut Window,
7608 cx: &mut Context<Workspace>,
7609) {
7610 let Some(active_dock) = workspace
7611 .all_docks()
7612 .into_iter()
7613 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7614 else {
7615 return;
7616 };
7617 let dock = active_dock.read(cx);
7618 let Some(panel_size) = dock.active_panel_size(window, cx) else {
7619 return;
7620 };
7621 let dock_pos = dock.position();
7622 workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
7623}
7624
7625fn adjust_open_docks_size_by_px(
7626 px: Pixels,
7627 workspace: &mut Workspace,
7628 window: &mut Window,
7629 cx: &mut Context<Workspace>,
7630) {
7631 let docks = workspace
7632 .all_docks()
7633 .into_iter()
7634 .filter_map(|dock| {
7635 if dock.read(cx).is_open() {
7636 let dock = dock.read(cx);
7637 let panel_size = dock.active_panel_size(window, cx)?;
7638 let dock_pos = dock.position();
7639 Some((panel_size, dock_pos, px))
7640 } else {
7641 None
7642 }
7643 })
7644 .collect::<Vec<_>>();
7645
7646 docks
7647 .into_iter()
7648 .for_each(|(panel_size, dock_pos, offset)| {
7649 workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
7650 });
7651}
7652
7653impl Focusable for Workspace {
7654 fn focus_handle(&self, cx: &App) -> FocusHandle {
7655 self.active_pane.focus_handle(cx)
7656 }
7657}
7658
7659#[derive(Clone)]
7660struct DraggedDock(DockPosition);
7661
7662impl Render for DraggedDock {
7663 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7664 gpui::Empty
7665 }
7666}
7667
7668impl Render for Workspace {
7669 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7670 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7671 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7672 log::info!("Rendered first frame");
7673 }
7674
7675 let centered_layout = self.centered_layout
7676 && self.center.panes().len() == 1
7677 && self.active_item(cx).is_some();
7678 let render_padding = |size| {
7679 (size > 0.0).then(|| {
7680 div()
7681 .h_full()
7682 .w(relative(size))
7683 .bg(cx.theme().colors().editor_background)
7684 .border_color(cx.theme().colors().pane_group_border)
7685 })
7686 };
7687 let paddings = if centered_layout {
7688 let settings = WorkspaceSettings::get_global(cx).centered_layout;
7689 (
7690 render_padding(Self::adjust_padding(
7691 settings.left_padding.map(|padding| padding.0),
7692 )),
7693 render_padding(Self::adjust_padding(
7694 settings.right_padding.map(|padding| padding.0),
7695 )),
7696 )
7697 } else {
7698 (None, None)
7699 };
7700 let ui_font = theme::setup_ui_font(window, cx);
7701
7702 let theme = cx.theme().clone();
7703 let colors = theme.colors();
7704 let notification_entities = self
7705 .notifications
7706 .iter()
7707 .map(|(_, notification)| notification.entity_id())
7708 .collect::<Vec<_>>();
7709 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
7710 let sidebar_open = window
7711 .root::<MultiWorkspace>()
7712 .flatten()
7713 .is_some_and(|mw| mw.read(cx).sidebar_open());
7714
7715 div()
7716 .relative()
7717 .size_full()
7718 .flex()
7719 .flex_col()
7720 .font(ui_font)
7721 .gap_0()
7722 .justify_start()
7723 .items_start()
7724 .text_color(colors.text)
7725 .overflow_hidden()
7726 .children(self.titlebar_item.clone())
7727 .on_modifiers_changed(move |_, _, cx| {
7728 for &id in ¬ification_entities {
7729 cx.notify(id);
7730 }
7731 })
7732 .child(
7733 div()
7734 .size_full()
7735 .relative()
7736 .flex_1()
7737 .flex()
7738 .flex_col()
7739 .child(
7740 div()
7741 .id("workspace")
7742 .bg(colors.background)
7743 .relative()
7744 .flex_1()
7745 .w_full()
7746 .flex()
7747 .flex_col()
7748 .overflow_hidden()
7749 .border_t_1()
7750 .border_b_1()
7751 .border_color(colors.border)
7752 .child({
7753 let this = cx.entity();
7754 canvas(
7755 move |bounds, window, cx| {
7756 this.update(cx, |this, cx| {
7757 let bounds_changed = this.bounds != bounds;
7758 this.bounds = bounds;
7759
7760 if bounds_changed {
7761 this.left_dock.update(cx, |dock, cx| {
7762 dock.clamp_panel_size(
7763 bounds.size.width,
7764 window,
7765 cx,
7766 )
7767 });
7768
7769 this.right_dock.update(cx, |dock, cx| {
7770 dock.clamp_panel_size(
7771 bounds.size.width,
7772 window,
7773 cx,
7774 )
7775 });
7776
7777 this.bottom_dock.update(cx, |dock, cx| {
7778 dock.clamp_panel_size(
7779 bounds.size.height,
7780 window,
7781 cx,
7782 )
7783 });
7784 }
7785 })
7786 },
7787 |_, _, _, _| {},
7788 )
7789 .absolute()
7790 .size_full()
7791 })
7792 .when(self.zoomed.is_none(), |this| {
7793 this.on_drag_move(cx.listener(
7794 move |workspace,
7795 e: &DragMoveEvent<DraggedDock>,
7796 window,
7797 cx| {
7798 if workspace.previous_dock_drag_coordinates
7799 != Some(e.event.position)
7800 {
7801 workspace.previous_dock_drag_coordinates =
7802 Some(e.event.position);
7803
7804 match e.drag(cx).0 {
7805 DockPosition::Left => {
7806 workspace.resize_left_dock(
7807 e.event.position.x
7808 - workspace.bounds.left(),
7809 window,
7810 cx,
7811 );
7812 }
7813 DockPosition::Right => {
7814 workspace.resize_right_dock(
7815 workspace.bounds.right()
7816 - e.event.position.x,
7817 window,
7818 cx,
7819 );
7820 }
7821 DockPosition::Bottom => {
7822 workspace.resize_bottom_dock(
7823 workspace.bounds.bottom()
7824 - e.event.position.y,
7825 window,
7826 cx,
7827 );
7828 }
7829 };
7830 workspace.serialize_workspace(window, cx);
7831 }
7832 },
7833 ))
7834
7835 })
7836 .child({
7837 match bottom_dock_layout {
7838 BottomDockLayout::Full => div()
7839 .flex()
7840 .flex_col()
7841 .h_full()
7842 .child(
7843 div()
7844 .flex()
7845 .flex_row()
7846 .flex_1()
7847 .overflow_hidden()
7848 .children(self.render_dock(
7849 DockPosition::Left,
7850 &self.left_dock,
7851 window,
7852 cx,
7853 ))
7854
7855 .child(
7856 div()
7857 .flex()
7858 .flex_col()
7859 .flex_1()
7860 .overflow_hidden()
7861 .child(
7862 h_flex()
7863 .flex_1()
7864 .when_some(
7865 paddings.0,
7866 |this, p| {
7867 this.child(
7868 p.border_r_1(),
7869 )
7870 },
7871 )
7872 .child(self.center.render(
7873 self.zoomed.as_ref(),
7874 &PaneRenderContext {
7875 follower_states:
7876 &self.follower_states,
7877 active_call: self.active_call(),
7878 active_pane: &self.active_pane,
7879 app_state: &self.app_state,
7880 project: &self.project,
7881 workspace: &self.weak_self,
7882 },
7883 window,
7884 cx,
7885 ))
7886 .when_some(
7887 paddings.1,
7888 |this, p| {
7889 this.child(
7890 p.border_l_1(),
7891 )
7892 },
7893 ),
7894 ),
7895 )
7896
7897 .children(self.render_dock(
7898 DockPosition::Right,
7899 &self.right_dock,
7900 window,
7901 cx,
7902 )),
7903 )
7904 .child(div().w_full().children(self.render_dock(
7905 DockPosition::Bottom,
7906 &self.bottom_dock,
7907 window,
7908 cx
7909 ))),
7910
7911 BottomDockLayout::LeftAligned => div()
7912 .flex()
7913 .flex_row()
7914 .h_full()
7915 .child(
7916 div()
7917 .flex()
7918 .flex_col()
7919 .flex_1()
7920 .h_full()
7921 .child(
7922 div()
7923 .flex()
7924 .flex_row()
7925 .flex_1()
7926 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
7927
7928 .child(
7929 div()
7930 .flex()
7931 .flex_col()
7932 .flex_1()
7933 .overflow_hidden()
7934 .child(
7935 h_flex()
7936 .flex_1()
7937 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7938 .child(self.center.render(
7939 self.zoomed.as_ref(),
7940 &PaneRenderContext {
7941 follower_states:
7942 &self.follower_states,
7943 active_call: self.active_call(),
7944 active_pane: &self.active_pane,
7945 app_state: &self.app_state,
7946 project: &self.project,
7947 workspace: &self.weak_self,
7948 },
7949 window,
7950 cx,
7951 ))
7952 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7953 )
7954 )
7955
7956 )
7957 .child(
7958 div()
7959 .w_full()
7960 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7961 ),
7962 )
7963 .children(self.render_dock(
7964 DockPosition::Right,
7965 &self.right_dock,
7966 window,
7967 cx,
7968 )),
7969 BottomDockLayout::RightAligned => div()
7970 .flex()
7971 .flex_row()
7972 .h_full()
7973 .children(self.render_dock(
7974 DockPosition::Left,
7975 &self.left_dock,
7976 window,
7977 cx,
7978 ))
7979
7980 .child(
7981 div()
7982 .flex()
7983 .flex_col()
7984 .flex_1()
7985 .h_full()
7986 .child(
7987 div()
7988 .flex()
7989 .flex_row()
7990 .flex_1()
7991 .child(
7992 div()
7993 .flex()
7994 .flex_col()
7995 .flex_1()
7996 .overflow_hidden()
7997 .child(
7998 h_flex()
7999 .flex_1()
8000 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8001 .child(self.center.render(
8002 self.zoomed.as_ref(),
8003 &PaneRenderContext {
8004 follower_states:
8005 &self.follower_states,
8006 active_call: self.active_call(),
8007 active_pane: &self.active_pane,
8008 app_state: &self.app_state,
8009 project: &self.project,
8010 workspace: &self.weak_self,
8011 },
8012 window,
8013 cx,
8014 ))
8015 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8016 )
8017 )
8018
8019 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
8020 )
8021 .child(
8022 div()
8023 .w_full()
8024 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8025 ),
8026 ),
8027 BottomDockLayout::Contained => div()
8028 .flex()
8029 .flex_row()
8030 .h_full()
8031 .children(self.render_dock(
8032 DockPosition::Left,
8033 &self.left_dock,
8034 window,
8035 cx,
8036 ))
8037
8038 .child(
8039 div()
8040 .flex()
8041 .flex_col()
8042 .flex_1()
8043 .overflow_hidden()
8044 .child(
8045 h_flex()
8046 .flex_1()
8047 .when_some(paddings.0, |this, p| {
8048 this.child(p.border_r_1())
8049 })
8050 .child(self.center.render(
8051 self.zoomed.as_ref(),
8052 &PaneRenderContext {
8053 follower_states:
8054 &self.follower_states,
8055 active_call: self.active_call(),
8056 active_pane: &self.active_pane,
8057 app_state: &self.app_state,
8058 project: &self.project,
8059 workspace: &self.weak_self,
8060 },
8061 window,
8062 cx,
8063 ))
8064 .when_some(paddings.1, |this, p| {
8065 this.child(p.border_l_1())
8066 }),
8067 )
8068 .children(self.render_dock(
8069 DockPosition::Bottom,
8070 &self.bottom_dock,
8071 window,
8072 cx,
8073 )),
8074 )
8075
8076 .children(self.render_dock(
8077 DockPosition::Right,
8078 &self.right_dock,
8079 window,
8080 cx,
8081 )),
8082 }
8083 })
8084 .children(self.zoomed.as_ref().and_then(|view| {
8085 let zoomed_view = view.upgrade()?;
8086 let div = div()
8087 .occlude()
8088 .absolute()
8089 .overflow_hidden()
8090 .border_color(colors.border)
8091 .bg(colors.background)
8092 .child(zoomed_view)
8093 .inset_0()
8094 .shadow_lg();
8095
8096 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8097 return Some(div);
8098 }
8099
8100 Some(match self.zoomed_position {
8101 Some(DockPosition::Left) => div.right_2().border_r_1(),
8102 Some(DockPosition::Right) => div.left_2().border_l_1(),
8103 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8104 None => {
8105 div.top_2().bottom_2().left_2().right_2().border_1()
8106 }
8107 })
8108 }))
8109 .children(self.render_notifications(window, cx))
8110 .when(sidebar_open, |this| {
8111 this.child(deferred(
8112 div()
8113 .absolute()
8114 .left_0()
8115 .top_0()
8116 .h_full()
8117 .w_2p5()
8118 .bg(linear_gradient(
8119 90.,
8120 linear_color_stop(
8121 hsla(0.0, 0.0, 0.0, 0.05),
8122 0.,
8123 ),
8124 linear_color_stop(
8125 hsla(0.0, 0.0, 0.0, 0.0),
8126 1.,
8127 ),
8128 )),
8129 ))
8130 }),
8131 )
8132 .when(self.status_bar_visible(cx), |parent| {
8133 parent.child(self.status_bar.clone())
8134 })
8135 .child(self.toast_layer.clone()),
8136 )
8137 }
8138}
8139
8140impl WorkspaceStore {
8141 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8142 Self {
8143 workspaces: Default::default(),
8144 _subscriptions: vec![
8145 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8146 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8147 ],
8148 client,
8149 }
8150 }
8151
8152 pub fn update_followers(
8153 &self,
8154 project_id: Option<u64>,
8155 update: proto::update_followers::Variant,
8156 cx: &App,
8157 ) -> Option<()> {
8158 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8159 let room_id = active_call.0.room_id(cx)?;
8160 self.client
8161 .send(proto::UpdateFollowers {
8162 room_id,
8163 project_id,
8164 variant: Some(update),
8165 })
8166 .log_err()
8167 }
8168
8169 pub async fn handle_follow(
8170 this: Entity<Self>,
8171 envelope: TypedEnvelope<proto::Follow>,
8172 mut cx: AsyncApp,
8173 ) -> Result<proto::FollowResponse> {
8174 this.update(&mut cx, |this, cx| {
8175 let follower = Follower {
8176 project_id: envelope.payload.project_id,
8177 peer_id: envelope.original_sender_id()?,
8178 };
8179
8180 let mut response = proto::FollowResponse::default();
8181
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 handler_response =
8190 workspace.handle_follow(follower.project_id, window, cx);
8191 if let Some(active_view) = handler_response.active_view
8192 && workspace.project.read(cx).remote_id() == follower.project_id
8193 {
8194 response.active_view = Some(active_view)
8195 }
8196 });
8197 })
8198 .is_ok()
8199 });
8200
8201 Ok(response)
8202 })
8203 }
8204
8205 async fn handle_update_followers(
8206 this: Entity<Self>,
8207 envelope: TypedEnvelope<proto::UpdateFollowers>,
8208 mut cx: AsyncApp,
8209 ) -> Result<()> {
8210 let leader_id = envelope.original_sender_id()?;
8211 let update = envelope.payload;
8212
8213 this.update(&mut cx, |this, cx| {
8214 this.workspaces.retain(|(window_handle, weak_workspace)| {
8215 let Some(workspace) = weak_workspace.upgrade() else {
8216 return false;
8217 };
8218 window_handle
8219 .update(cx, |_, window, cx| {
8220 workspace.update(cx, |workspace, cx| {
8221 let project_id = workspace.project.read(cx).remote_id();
8222 if update.project_id != project_id && update.project_id.is_some() {
8223 return;
8224 }
8225 workspace.handle_update_followers(
8226 leader_id,
8227 update.clone(),
8228 window,
8229 cx,
8230 );
8231 });
8232 })
8233 .is_ok()
8234 });
8235 Ok(())
8236 })
8237 }
8238
8239 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8240 self.workspaces.iter().map(|(_, weak)| weak)
8241 }
8242
8243 pub fn workspaces_with_windows(
8244 &self,
8245 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8246 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8247 }
8248}
8249
8250impl ViewId {
8251 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8252 Ok(Self {
8253 creator: message
8254 .creator
8255 .map(CollaboratorId::PeerId)
8256 .context("creator is missing")?,
8257 id: message.id,
8258 })
8259 }
8260
8261 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8262 if let CollaboratorId::PeerId(peer_id) = self.creator {
8263 Some(proto::ViewId {
8264 creator: Some(peer_id),
8265 id: self.id,
8266 })
8267 } else {
8268 None
8269 }
8270 }
8271}
8272
8273impl FollowerState {
8274 fn pane(&self) -> &Entity<Pane> {
8275 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8276 }
8277}
8278
8279pub trait WorkspaceHandle {
8280 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8281}
8282
8283impl WorkspaceHandle for Entity<Workspace> {
8284 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8285 self.read(cx)
8286 .worktrees(cx)
8287 .flat_map(|worktree| {
8288 let worktree_id = worktree.read(cx).id();
8289 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8290 worktree_id,
8291 path: f.path.clone(),
8292 })
8293 })
8294 .collect::<Vec<_>>()
8295 }
8296}
8297
8298pub async fn last_opened_workspace_location(
8299 db: &WorkspaceDb,
8300 fs: &dyn fs::Fs,
8301) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8302 db.last_workspace(fs)
8303 .await
8304 .log_err()
8305 .flatten()
8306 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8307}
8308
8309pub async fn last_session_workspace_locations(
8310 db: &WorkspaceDb,
8311 last_session_id: &str,
8312 last_session_window_stack: Option<Vec<WindowId>>,
8313 fs: &dyn fs::Fs,
8314) -> Option<Vec<SessionWorkspace>> {
8315 db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8316 .await
8317 .log_err()
8318}
8319
8320pub struct MultiWorkspaceRestoreResult {
8321 pub window_handle: WindowHandle<MultiWorkspace>,
8322 pub errors: Vec<anyhow::Error>,
8323}
8324
8325pub async fn restore_multiworkspace(
8326 multi_workspace: SerializedMultiWorkspace,
8327 app_state: Arc<AppState>,
8328 cx: &mut AsyncApp,
8329) -> anyhow::Result<MultiWorkspaceRestoreResult> {
8330 let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
8331 let mut group_iter = workspaces.into_iter();
8332 let first = group_iter
8333 .next()
8334 .context("window group must not be empty")?;
8335
8336 let window_handle = if first.paths.is_empty() {
8337 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
8338 .await?
8339 } else {
8340 let OpenResult { window, .. } = cx
8341 .update(|cx| {
8342 Workspace::new_local(
8343 first.paths.paths().to_vec(),
8344 app_state.clone(),
8345 None,
8346 None,
8347 None,
8348 true,
8349 cx,
8350 )
8351 })
8352 .await?;
8353 window
8354 };
8355
8356 let mut errors = Vec::new();
8357
8358 for session_workspace in group_iter {
8359 let error = if session_workspace.paths.is_empty() {
8360 cx.update(|cx| {
8361 open_workspace_by_id(
8362 session_workspace.workspace_id,
8363 app_state.clone(),
8364 Some(window_handle),
8365 cx,
8366 )
8367 })
8368 .await
8369 .err()
8370 } else {
8371 cx.update(|cx| {
8372 Workspace::new_local(
8373 session_workspace.paths.paths().to_vec(),
8374 app_state.clone(),
8375 Some(window_handle),
8376 None,
8377 None,
8378 false,
8379 cx,
8380 )
8381 })
8382 .await
8383 .err()
8384 };
8385
8386 if let Some(error) = error {
8387 errors.push(error);
8388 }
8389 }
8390
8391 if let Some(target_id) = state.active_workspace_id {
8392 window_handle
8393 .update(cx, |multi_workspace, window, cx| {
8394 let target_index = multi_workspace
8395 .workspaces()
8396 .iter()
8397 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8398 if let Some(index) = target_index {
8399 multi_workspace.activate_index(index, window, cx);
8400 } else if !multi_workspace.workspaces().is_empty() {
8401 multi_workspace.activate_index(0, window, cx);
8402 }
8403 })
8404 .ok();
8405 } else {
8406 window_handle
8407 .update(cx, |multi_workspace, window, cx| {
8408 if !multi_workspace.workspaces().is_empty() {
8409 multi_workspace.activate_index(0, window, cx);
8410 }
8411 })
8412 .ok();
8413 }
8414
8415 if state.sidebar_open {
8416 window_handle
8417 .update(cx, |multi_workspace, _, cx| {
8418 multi_workspace.open_sidebar(cx);
8419 })
8420 .ok();
8421 }
8422
8423 window_handle
8424 .update(cx, |_, window, _cx| {
8425 window.activate_window();
8426 })
8427 .ok();
8428
8429 Ok(MultiWorkspaceRestoreResult {
8430 window_handle,
8431 errors,
8432 })
8433}
8434
8435actions!(
8436 collab,
8437 [
8438 /// Opens the channel notes for the current call.
8439 ///
8440 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8441 /// channel in the collab panel.
8442 ///
8443 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8444 /// can be copied via "Copy link to section" in the context menu of the channel notes
8445 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8446 OpenChannelNotes,
8447 /// Mutes your microphone.
8448 Mute,
8449 /// Deafens yourself (mute both microphone and speakers).
8450 Deafen,
8451 /// Leaves the current call.
8452 LeaveCall,
8453 /// Shares the current project with collaborators.
8454 ShareProject,
8455 /// Shares your screen with collaborators.
8456 ScreenShare,
8457 /// Copies the current room name and session id for debugging purposes.
8458 CopyRoomId,
8459 ]
8460);
8461
8462/// Opens the channel notes for a specific channel by its ID.
8463#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8464#[action(namespace = collab)]
8465#[serde(deny_unknown_fields)]
8466pub struct OpenChannelNotesById {
8467 pub channel_id: u64,
8468}
8469
8470actions!(
8471 zed,
8472 [
8473 /// Opens the Zed log file.
8474 OpenLog,
8475 /// Reveals the Zed log file in the system file manager.
8476 RevealLogInFileManager
8477 ]
8478);
8479
8480async fn join_channel_internal(
8481 channel_id: ChannelId,
8482 app_state: &Arc<AppState>,
8483 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8484 requesting_workspace: Option<WeakEntity<Workspace>>,
8485 active_call: &dyn AnyActiveCall,
8486 cx: &mut AsyncApp,
8487) -> Result<bool> {
8488 let (should_prompt, already_in_channel) = cx.update(|cx| {
8489 if !active_call.is_in_room(cx) {
8490 return (false, false);
8491 }
8492
8493 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8494 let should_prompt = active_call.is_sharing_project(cx)
8495 && active_call.has_remote_participants(cx)
8496 && !already_in_channel;
8497 (should_prompt, already_in_channel)
8498 });
8499
8500 if already_in_channel {
8501 let task = cx.update(|cx| {
8502 if let Some((project, host)) = active_call.most_active_project(cx) {
8503 Some(join_in_room_project(project, host, app_state.clone(), cx))
8504 } else {
8505 None
8506 }
8507 });
8508 if let Some(task) = task {
8509 task.await?;
8510 }
8511 return anyhow::Ok(true);
8512 }
8513
8514 if should_prompt {
8515 if let Some(multi_workspace) = requesting_window {
8516 let answer = multi_workspace
8517 .update(cx, |_, window, cx| {
8518 window.prompt(
8519 PromptLevel::Warning,
8520 "Do you want to switch channels?",
8521 Some("Leaving this call will unshare your current project."),
8522 &["Yes, Join Channel", "Cancel"],
8523 cx,
8524 )
8525 })?
8526 .await;
8527
8528 if answer == Ok(1) {
8529 return Ok(false);
8530 }
8531 } else {
8532 return Ok(false);
8533 }
8534 }
8535
8536 let client = cx.update(|cx| active_call.client(cx));
8537
8538 let mut client_status = client.status();
8539
8540 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8541 'outer: loop {
8542 let Some(status) = client_status.recv().await else {
8543 anyhow::bail!("error connecting");
8544 };
8545
8546 match status {
8547 Status::Connecting
8548 | Status::Authenticating
8549 | Status::Authenticated
8550 | Status::Reconnecting
8551 | Status::Reauthenticating
8552 | Status::Reauthenticated => continue,
8553 Status::Connected { .. } => break 'outer,
8554 Status::SignedOut | Status::AuthenticationError => {
8555 return Err(ErrorCode::SignedOut.into());
8556 }
8557 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8558 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8559 return Err(ErrorCode::Disconnected.into());
8560 }
8561 }
8562 }
8563
8564 let joined = cx
8565 .update(|cx| active_call.join_channel(channel_id, cx))
8566 .await?;
8567
8568 if !joined {
8569 return anyhow::Ok(true);
8570 }
8571
8572 cx.update(|cx| active_call.room_update_completed(cx)).await;
8573
8574 let task = cx.update(|cx| {
8575 if let Some((project, host)) = active_call.most_active_project(cx) {
8576 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8577 }
8578
8579 // If you are the first to join a channel, see if you should share your project.
8580 if !active_call.has_remote_participants(cx)
8581 && !active_call.local_participant_is_guest(cx)
8582 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8583 {
8584 let project = workspace.update(cx, |workspace, cx| {
8585 let project = workspace.project.read(cx);
8586
8587 if !active_call.share_on_join(cx) {
8588 return None;
8589 }
8590
8591 if (project.is_local() || project.is_via_remote_server())
8592 && project.visible_worktrees(cx).any(|tree| {
8593 tree.read(cx)
8594 .root_entry()
8595 .is_some_and(|entry| entry.is_dir())
8596 })
8597 {
8598 Some(workspace.project.clone())
8599 } else {
8600 None
8601 }
8602 });
8603 if let Some(project) = project {
8604 let share_task = active_call.share_project(project, cx);
8605 return Some(cx.spawn(async move |_cx| -> Result<()> {
8606 share_task.await?;
8607 Ok(())
8608 }));
8609 }
8610 }
8611
8612 None
8613 });
8614 if let Some(task) = task {
8615 task.await?;
8616 return anyhow::Ok(true);
8617 }
8618 anyhow::Ok(false)
8619}
8620
8621pub fn join_channel(
8622 channel_id: ChannelId,
8623 app_state: Arc<AppState>,
8624 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8625 requesting_workspace: Option<WeakEntity<Workspace>>,
8626 cx: &mut App,
8627) -> Task<Result<()>> {
8628 let active_call = GlobalAnyActiveCall::global(cx).clone();
8629 cx.spawn(async move |cx| {
8630 let result = join_channel_internal(
8631 channel_id,
8632 &app_state,
8633 requesting_window,
8634 requesting_workspace,
8635 &*active_call.0,
8636 cx,
8637 )
8638 .await;
8639
8640 // join channel succeeded, and opened a window
8641 if matches!(result, Ok(true)) {
8642 return anyhow::Ok(());
8643 }
8644
8645 // find an existing workspace to focus and show call controls
8646 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8647 if active_window.is_none() {
8648 // no open workspaces, make one to show the error in (blergh)
8649 let OpenResult {
8650 window: window_handle,
8651 ..
8652 } = cx
8653 .update(|cx| {
8654 Workspace::new_local(
8655 vec![],
8656 app_state.clone(),
8657 requesting_window,
8658 None,
8659 None,
8660 true,
8661 cx,
8662 )
8663 })
8664 .await?;
8665
8666 window_handle
8667 .update(cx, |_, window, _cx| {
8668 window.activate_window();
8669 })
8670 .ok();
8671
8672 if result.is_ok() {
8673 cx.update(|cx| {
8674 cx.dispatch_action(&OpenChannelNotes);
8675 });
8676 }
8677
8678 active_window = Some(window_handle);
8679 }
8680
8681 if let Err(err) = result {
8682 log::error!("failed to join channel: {}", err);
8683 if let Some(active_window) = active_window {
8684 active_window
8685 .update(cx, |_, window, cx| {
8686 let detail: SharedString = match err.error_code() {
8687 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8688 ErrorCode::UpgradeRequired => concat!(
8689 "Your are running an unsupported version of Zed. ",
8690 "Please update to continue."
8691 )
8692 .into(),
8693 ErrorCode::NoSuchChannel => concat!(
8694 "No matching channel was found. ",
8695 "Please check the link and try again."
8696 )
8697 .into(),
8698 ErrorCode::Forbidden => concat!(
8699 "This channel is private, and you do not have access. ",
8700 "Please ask someone to add you and try again."
8701 )
8702 .into(),
8703 ErrorCode::Disconnected => {
8704 "Please check your internet connection and try again.".into()
8705 }
8706 _ => format!("{}\n\nPlease try again.", err).into(),
8707 };
8708 window.prompt(
8709 PromptLevel::Critical,
8710 "Failed to join channel",
8711 Some(&detail),
8712 &["Ok"],
8713 cx,
8714 )
8715 })?
8716 .await
8717 .ok();
8718 }
8719 }
8720
8721 // return ok, we showed the error to the user.
8722 anyhow::Ok(())
8723 })
8724}
8725
8726pub async fn get_any_active_multi_workspace(
8727 app_state: Arc<AppState>,
8728 mut cx: AsyncApp,
8729) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8730 // find an existing workspace to focus and show call controls
8731 let active_window = activate_any_workspace_window(&mut cx);
8732 if active_window.is_none() {
8733 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
8734 .await?;
8735 }
8736 activate_any_workspace_window(&mut cx).context("could not open zed")
8737}
8738
8739fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
8740 cx.update(|cx| {
8741 if let Some(workspace_window) = cx
8742 .active_window()
8743 .and_then(|window| window.downcast::<MultiWorkspace>())
8744 {
8745 return Some(workspace_window);
8746 }
8747
8748 for window in cx.windows() {
8749 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
8750 workspace_window
8751 .update(cx, |_, window, _| window.activate_window())
8752 .ok();
8753 return Some(workspace_window);
8754 }
8755 }
8756 None
8757 })
8758}
8759
8760pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
8761 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
8762}
8763
8764pub fn workspace_windows_for_location(
8765 serialized_location: &SerializedWorkspaceLocation,
8766 cx: &App,
8767) -> Vec<WindowHandle<MultiWorkspace>> {
8768 cx.windows()
8769 .into_iter()
8770 .filter_map(|window| window.downcast::<MultiWorkspace>())
8771 .filter(|multi_workspace| {
8772 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
8773 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
8774 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
8775 }
8776 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
8777 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
8778 a.distro_name == b.distro_name
8779 }
8780 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
8781 a.container_id == b.container_id
8782 }
8783 #[cfg(any(test, feature = "test-support"))]
8784 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
8785 a.id == b.id
8786 }
8787 _ => false,
8788 };
8789
8790 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
8791 multi_workspace.workspaces().iter().any(|workspace| {
8792 match workspace.read(cx).workspace_location(cx) {
8793 WorkspaceLocation::Location(location, _) => {
8794 match (&location, serialized_location) {
8795 (
8796 SerializedWorkspaceLocation::Local,
8797 SerializedWorkspaceLocation::Local,
8798 ) => true,
8799 (
8800 SerializedWorkspaceLocation::Remote(a),
8801 SerializedWorkspaceLocation::Remote(b),
8802 ) => same_host(a, b),
8803 _ => false,
8804 }
8805 }
8806 _ => false,
8807 }
8808 })
8809 })
8810 })
8811 .collect()
8812}
8813
8814pub async fn find_existing_workspace(
8815 abs_paths: &[PathBuf],
8816 open_options: &OpenOptions,
8817 location: &SerializedWorkspaceLocation,
8818 cx: &mut AsyncApp,
8819) -> (
8820 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
8821 OpenVisible,
8822) {
8823 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
8824 let mut open_visible = OpenVisible::All;
8825 let mut best_match = None;
8826
8827 if open_options.open_new_workspace != Some(true) {
8828 cx.update(|cx| {
8829 for window in workspace_windows_for_location(location, cx) {
8830 if let Ok(multi_workspace) = window.read(cx) {
8831 for workspace in multi_workspace.workspaces() {
8832 let project = workspace.read(cx).project.read(cx);
8833 let m = project.visibility_for_paths(
8834 abs_paths,
8835 open_options.open_new_workspace == None,
8836 cx,
8837 );
8838 if m > best_match {
8839 existing = Some((window, workspace.clone()));
8840 best_match = m;
8841 } else if best_match.is_none()
8842 && open_options.open_new_workspace == Some(false)
8843 {
8844 existing = Some((window, workspace.clone()))
8845 }
8846 }
8847 }
8848 }
8849 });
8850
8851 let all_paths_are_files = existing
8852 .as_ref()
8853 .and_then(|(_, target_workspace)| {
8854 cx.update(|cx| {
8855 let workspace = target_workspace.read(cx);
8856 let project = workspace.project.read(cx);
8857 let path_style = workspace.path_style(cx);
8858 Some(!abs_paths.iter().any(|path| {
8859 let path = util::paths::SanitizedPath::new(path);
8860 project.worktrees(cx).any(|worktree| {
8861 let worktree = worktree.read(cx);
8862 let abs_path = worktree.abs_path();
8863 path_style
8864 .strip_prefix(path.as_ref(), abs_path.as_ref())
8865 .and_then(|rel| worktree.entry_for_path(&rel))
8866 .is_some_and(|e| e.is_dir())
8867 })
8868 }))
8869 })
8870 })
8871 .unwrap_or(false);
8872
8873 if open_options.open_new_workspace.is_none()
8874 && existing.is_some()
8875 && open_options.wait
8876 && all_paths_are_files
8877 {
8878 cx.update(|cx| {
8879 let windows = workspace_windows_for_location(location, cx);
8880 let window = cx
8881 .active_window()
8882 .and_then(|window| window.downcast::<MultiWorkspace>())
8883 .filter(|window| windows.contains(window))
8884 .or_else(|| windows.into_iter().next());
8885 if let Some(window) = window {
8886 if let Ok(multi_workspace) = window.read(cx) {
8887 let active_workspace = multi_workspace.workspace().clone();
8888 existing = Some((window, active_workspace));
8889 open_visible = OpenVisible::None;
8890 }
8891 }
8892 });
8893 }
8894 }
8895 (existing, open_visible)
8896}
8897
8898#[derive(Default, Clone)]
8899pub struct OpenOptions {
8900 pub visible: Option<OpenVisible>,
8901 pub focus: Option<bool>,
8902 pub open_new_workspace: Option<bool>,
8903 pub wait: bool,
8904 pub replace_window: Option<WindowHandle<MultiWorkspace>>,
8905 pub env: Option<HashMap<String, String>>,
8906}
8907
8908/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
8909/// or [`Workspace::open_workspace_for_paths`].
8910pub struct OpenResult {
8911 pub window: WindowHandle<MultiWorkspace>,
8912 pub workspace: Entity<Workspace>,
8913 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
8914}
8915
8916/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
8917pub fn open_workspace_by_id(
8918 workspace_id: WorkspaceId,
8919 app_state: Arc<AppState>,
8920 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8921 cx: &mut App,
8922) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
8923 let project_handle = Project::local(
8924 app_state.client.clone(),
8925 app_state.node_runtime.clone(),
8926 app_state.user_store.clone(),
8927 app_state.languages.clone(),
8928 app_state.fs.clone(),
8929 None,
8930 project::LocalProjectFlags {
8931 init_worktree_trust: true,
8932 ..project::LocalProjectFlags::default()
8933 },
8934 cx,
8935 );
8936
8937 let db = WorkspaceDb::global(cx);
8938 let kvp = db::kvp::KeyValueStore::global(cx);
8939 cx.spawn(async move |cx| {
8940 let serialized_workspace = db
8941 .workspace_for_id(workspace_id)
8942 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
8943
8944 let centered_layout = serialized_workspace.centered_layout;
8945
8946 let (window, workspace) = if let Some(window) = requesting_window {
8947 let workspace = window.update(cx, |multi_workspace, window, cx| {
8948 let workspace = cx.new(|cx| {
8949 let mut workspace = Workspace::new(
8950 Some(workspace_id),
8951 project_handle.clone(),
8952 app_state.clone(),
8953 window,
8954 cx,
8955 );
8956 workspace.centered_layout = centered_layout;
8957 workspace
8958 });
8959 multi_workspace.add_workspace(workspace.clone(), cx);
8960 workspace
8961 })?;
8962 (window, workspace)
8963 } else {
8964 let window_bounds_override = window_bounds_env_override();
8965
8966 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
8967 (Some(WindowBounds::Windowed(bounds)), None)
8968 } else if let Some(display) = serialized_workspace.display
8969 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
8970 {
8971 (Some(bounds.0), Some(display))
8972 } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
8973 (Some(bounds), Some(display))
8974 } else {
8975 (None, None)
8976 };
8977
8978 let options = cx.update(|cx| {
8979 let mut options = (app_state.build_window_options)(display, cx);
8980 options.window_bounds = window_bounds;
8981 options
8982 });
8983
8984 let window = cx.open_window(options, {
8985 let app_state = app_state.clone();
8986 let project_handle = project_handle.clone();
8987 move |window, cx| {
8988 let workspace = cx.new(|cx| {
8989 let mut workspace = Workspace::new(
8990 Some(workspace_id),
8991 project_handle,
8992 app_state,
8993 window,
8994 cx,
8995 );
8996 workspace.centered_layout = centered_layout;
8997 workspace
8998 });
8999 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9000 }
9001 })?;
9002
9003 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
9004 multi_workspace.workspace().clone()
9005 })?;
9006
9007 (window, workspace)
9008 };
9009
9010 notify_if_database_failed(window, cx);
9011
9012 // Restore items from the serialized workspace
9013 window
9014 .update(cx, |_, window, cx| {
9015 workspace.update(cx, |_workspace, cx| {
9016 open_items(Some(serialized_workspace), vec![], window, cx)
9017 })
9018 })?
9019 .await?;
9020
9021 window.update(cx, |_, window, cx| {
9022 workspace.update(cx, |workspace, cx| {
9023 workspace.serialize_workspace(window, cx);
9024 });
9025 })?;
9026
9027 Ok(window)
9028 })
9029}
9030
9031#[allow(clippy::type_complexity)]
9032pub fn open_paths(
9033 abs_paths: &[PathBuf],
9034 app_state: Arc<AppState>,
9035 open_options: OpenOptions,
9036 cx: &mut App,
9037) -> Task<anyhow::Result<OpenResult>> {
9038 let abs_paths = abs_paths.to_vec();
9039 #[cfg(target_os = "windows")]
9040 let wsl_path = abs_paths
9041 .iter()
9042 .find_map(|p| util::paths::WslPath::from_path(p));
9043
9044 cx.spawn(async move |cx| {
9045 let (mut existing, mut open_visible) = find_existing_workspace(
9046 &abs_paths,
9047 &open_options,
9048 &SerializedWorkspaceLocation::Local,
9049 cx,
9050 )
9051 .await;
9052
9053 // Fallback: if no workspace contains the paths and all paths are files,
9054 // prefer an existing local workspace window (active window first).
9055 if open_options.open_new_workspace.is_none() && existing.is_none() {
9056 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9057 let all_metadatas = futures::future::join_all(all_paths)
9058 .await
9059 .into_iter()
9060 .filter_map(|result| result.ok().flatten())
9061 .collect::<Vec<_>>();
9062
9063 if all_metadatas.iter().all(|file| !file.is_dir) {
9064 cx.update(|cx| {
9065 let windows = workspace_windows_for_location(
9066 &SerializedWorkspaceLocation::Local,
9067 cx,
9068 );
9069 let window = cx
9070 .active_window()
9071 .and_then(|window| window.downcast::<MultiWorkspace>())
9072 .filter(|window| windows.contains(window))
9073 .or_else(|| windows.into_iter().next());
9074 if let Some(window) = window {
9075 if let Ok(multi_workspace) = window.read(cx) {
9076 let active_workspace = multi_workspace.workspace().clone();
9077 existing = Some((window, active_workspace));
9078 open_visible = OpenVisible::None;
9079 }
9080 }
9081 });
9082 }
9083 }
9084
9085 let result = if let Some((existing, target_workspace)) = existing {
9086 let open_task = existing
9087 .update(cx, |multi_workspace, window, cx| {
9088 window.activate_window();
9089 multi_workspace.activate(target_workspace.clone(), cx);
9090 target_workspace.update(cx, |workspace, cx| {
9091 workspace.open_paths(
9092 abs_paths,
9093 OpenOptions {
9094 visible: Some(open_visible),
9095 ..Default::default()
9096 },
9097 None,
9098 window,
9099 cx,
9100 )
9101 })
9102 })?
9103 .await;
9104
9105 _ = existing.update(cx, |multi_workspace, _, cx| {
9106 let workspace = multi_workspace.workspace().clone();
9107 workspace.update(cx, |workspace, cx| {
9108 for item in open_task.iter().flatten() {
9109 if let Err(e) = item {
9110 workspace.show_error(&e, cx);
9111 }
9112 }
9113 });
9114 });
9115
9116 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9117 } else {
9118 let result = cx
9119 .update(move |cx| {
9120 Workspace::new_local(
9121 abs_paths,
9122 app_state.clone(),
9123 open_options.replace_window,
9124 open_options.env,
9125 None,
9126 true,
9127 cx,
9128 )
9129 })
9130 .await;
9131
9132 if let Ok(ref result) = result {
9133 result.window
9134 .update(cx, |_, window, _cx| {
9135 window.activate_window();
9136 })
9137 .log_err();
9138 }
9139
9140 result
9141 };
9142
9143 #[cfg(target_os = "windows")]
9144 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9145 && let Ok(ref result) = result
9146 {
9147 result.window
9148 .update(cx, move |multi_workspace, _window, cx| {
9149 struct OpenInWsl;
9150 let workspace = multi_workspace.workspace().clone();
9151 workspace.update(cx, |workspace, cx| {
9152 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9153 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9154 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9155 cx.new(move |cx| {
9156 MessageNotification::new(msg, cx)
9157 .primary_message("Open in WSL")
9158 .primary_icon(IconName::FolderOpen)
9159 .primary_on_click(move |window, cx| {
9160 window.dispatch_action(Box::new(remote::OpenWslPath {
9161 distro: remote::WslConnectionOptions {
9162 distro_name: distro.clone(),
9163 user: None,
9164 },
9165 paths: vec![path.clone().into()],
9166 }), cx)
9167 })
9168 })
9169 });
9170 });
9171 })
9172 .unwrap();
9173 };
9174 result
9175 })
9176}
9177
9178pub fn open_new(
9179 open_options: OpenOptions,
9180 app_state: Arc<AppState>,
9181 cx: &mut App,
9182 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9183) -> Task<anyhow::Result<()>> {
9184 let task = Workspace::new_local(
9185 Vec::new(),
9186 app_state,
9187 open_options.replace_window,
9188 open_options.env,
9189 Some(Box::new(init)),
9190 true,
9191 cx,
9192 );
9193 cx.spawn(async move |cx| {
9194 let OpenResult { window, .. } = task.await?;
9195 window
9196 .update(cx, |_, window, _cx| {
9197 window.activate_window();
9198 })
9199 .ok();
9200 Ok(())
9201 })
9202}
9203
9204pub fn create_and_open_local_file(
9205 path: &'static Path,
9206 window: &mut Window,
9207 cx: &mut Context<Workspace>,
9208 default_content: impl 'static + Send + FnOnce() -> Rope,
9209) -> Task<Result<Box<dyn ItemHandle>>> {
9210 cx.spawn_in(window, async move |workspace, cx| {
9211 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9212 if !fs.is_file(path).await {
9213 fs.create_file(path, Default::default()).await?;
9214 fs.save(path, &default_content(), Default::default())
9215 .await?;
9216 }
9217
9218 workspace
9219 .update_in(cx, |workspace, window, cx| {
9220 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9221 let path = workspace
9222 .project
9223 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9224 cx.spawn_in(window, async move |workspace, cx| {
9225 let path = path.await?;
9226 let mut items = workspace
9227 .update_in(cx, |workspace, window, cx| {
9228 workspace.open_paths(
9229 vec![path.to_path_buf()],
9230 OpenOptions {
9231 visible: Some(OpenVisible::None),
9232 ..Default::default()
9233 },
9234 None,
9235 window,
9236 cx,
9237 )
9238 })?
9239 .await;
9240 let item = items.pop().flatten();
9241 item.with_context(|| format!("path {path:?} is not a file"))?
9242 })
9243 })
9244 })?
9245 .await?
9246 .await
9247 })
9248}
9249
9250pub fn open_remote_project_with_new_connection(
9251 window: WindowHandle<MultiWorkspace>,
9252 remote_connection: Arc<dyn RemoteConnection>,
9253 cancel_rx: oneshot::Receiver<()>,
9254 delegate: Arc<dyn RemoteClientDelegate>,
9255 app_state: Arc<AppState>,
9256 paths: Vec<PathBuf>,
9257 cx: &mut App,
9258) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9259 cx.spawn(async move |cx| {
9260 let (workspace_id, serialized_workspace) =
9261 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9262 .await?;
9263
9264 let session = match cx
9265 .update(|cx| {
9266 remote::RemoteClient::new(
9267 ConnectionIdentifier::Workspace(workspace_id.0),
9268 remote_connection,
9269 cancel_rx,
9270 delegate,
9271 cx,
9272 )
9273 })
9274 .await?
9275 {
9276 Some(result) => result,
9277 None => return Ok(Vec::new()),
9278 };
9279
9280 let project = cx.update(|cx| {
9281 project::Project::remote(
9282 session,
9283 app_state.client.clone(),
9284 app_state.node_runtime.clone(),
9285 app_state.user_store.clone(),
9286 app_state.languages.clone(),
9287 app_state.fs.clone(),
9288 true,
9289 cx,
9290 )
9291 });
9292
9293 open_remote_project_inner(
9294 project,
9295 paths,
9296 workspace_id,
9297 serialized_workspace,
9298 app_state,
9299 window,
9300 cx,
9301 )
9302 .await
9303 })
9304}
9305
9306pub fn open_remote_project_with_existing_connection(
9307 connection_options: RemoteConnectionOptions,
9308 project: Entity<Project>,
9309 paths: Vec<PathBuf>,
9310 app_state: Arc<AppState>,
9311 window: WindowHandle<MultiWorkspace>,
9312 cx: &mut AsyncApp,
9313) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9314 cx.spawn(async move |cx| {
9315 let (workspace_id, serialized_workspace) =
9316 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9317
9318 open_remote_project_inner(
9319 project,
9320 paths,
9321 workspace_id,
9322 serialized_workspace,
9323 app_state,
9324 window,
9325 cx,
9326 )
9327 .await
9328 })
9329}
9330
9331async fn open_remote_project_inner(
9332 project: Entity<Project>,
9333 paths: Vec<PathBuf>,
9334 workspace_id: WorkspaceId,
9335 serialized_workspace: Option<SerializedWorkspace>,
9336 app_state: Arc<AppState>,
9337 window: WindowHandle<MultiWorkspace>,
9338 cx: &mut AsyncApp,
9339) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9340 let db = cx.update(|cx| WorkspaceDb::global(cx));
9341 let toolchains = db.toolchains(workspace_id).await?;
9342 for (toolchain, worktree_path, path) in toolchains {
9343 project
9344 .update(cx, |this, cx| {
9345 let Some(worktree_id) =
9346 this.find_worktree(&worktree_path, cx)
9347 .and_then(|(worktree, rel_path)| {
9348 if rel_path.is_empty() {
9349 Some(worktree.read(cx).id())
9350 } else {
9351 None
9352 }
9353 })
9354 else {
9355 return Task::ready(None);
9356 };
9357
9358 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9359 })
9360 .await;
9361 }
9362 let mut project_paths_to_open = vec![];
9363 let mut project_path_errors = vec![];
9364
9365 for path in paths {
9366 let result = cx
9367 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9368 .await;
9369 match result {
9370 Ok((_, project_path)) => {
9371 project_paths_to_open.push((path.clone(), Some(project_path)));
9372 }
9373 Err(error) => {
9374 project_path_errors.push(error);
9375 }
9376 };
9377 }
9378
9379 if project_paths_to_open.is_empty() {
9380 return Err(project_path_errors.pop().context("no paths given")?);
9381 }
9382
9383 let workspace = window.update(cx, |multi_workspace, window, cx| {
9384 telemetry::event!("SSH Project Opened");
9385
9386 let new_workspace = cx.new(|cx| {
9387 let mut workspace =
9388 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9389 workspace.update_history(cx);
9390
9391 if let Some(ref serialized) = serialized_workspace {
9392 workspace.centered_layout = serialized.centered_layout;
9393 }
9394
9395 workspace
9396 });
9397
9398 multi_workspace.activate(new_workspace.clone(), cx);
9399 new_workspace
9400 })?;
9401
9402 let items = window
9403 .update(cx, |_, window, cx| {
9404 window.activate_window();
9405 workspace.update(cx, |_workspace, cx| {
9406 open_items(serialized_workspace, project_paths_to_open, window, cx)
9407 })
9408 })?
9409 .await?;
9410
9411 workspace.update(cx, |workspace, cx| {
9412 for error in project_path_errors {
9413 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9414 if let Some(path) = error.error_tag("path") {
9415 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9416 }
9417 } else {
9418 workspace.show_error(&error, cx)
9419 }
9420 }
9421 });
9422
9423 Ok(items.into_iter().map(|item| item?.ok()).collect())
9424}
9425
9426fn deserialize_remote_project(
9427 connection_options: RemoteConnectionOptions,
9428 paths: Vec<PathBuf>,
9429 cx: &AsyncApp,
9430) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9431 let db = cx.update(|cx| WorkspaceDb::global(cx));
9432 cx.background_spawn(async move {
9433 let remote_connection_id = db
9434 .get_or_create_remote_connection(connection_options)
9435 .await?;
9436
9437 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9438
9439 let workspace_id = if let Some(workspace_id) =
9440 serialized_workspace.as_ref().map(|workspace| workspace.id)
9441 {
9442 workspace_id
9443 } else {
9444 db.next_id().await?
9445 };
9446
9447 Ok((workspace_id, serialized_workspace))
9448 })
9449}
9450
9451pub fn join_in_room_project(
9452 project_id: u64,
9453 follow_user_id: u64,
9454 app_state: Arc<AppState>,
9455 cx: &mut App,
9456) -> Task<Result<()>> {
9457 let windows = cx.windows();
9458 cx.spawn(async move |cx| {
9459 let existing_window_and_workspace: Option<(
9460 WindowHandle<MultiWorkspace>,
9461 Entity<Workspace>,
9462 )> = windows.into_iter().find_map(|window_handle| {
9463 window_handle
9464 .downcast::<MultiWorkspace>()
9465 .and_then(|window_handle| {
9466 window_handle
9467 .update(cx, |multi_workspace, _window, cx| {
9468 for workspace in multi_workspace.workspaces() {
9469 if workspace.read(cx).project().read(cx).remote_id()
9470 == Some(project_id)
9471 {
9472 return Some((window_handle, workspace.clone()));
9473 }
9474 }
9475 None
9476 })
9477 .unwrap_or(None)
9478 })
9479 });
9480
9481 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9482 existing_window_and_workspace
9483 {
9484 existing_window
9485 .update(cx, |multi_workspace, _, cx| {
9486 multi_workspace.activate(target_workspace, cx);
9487 })
9488 .ok();
9489 existing_window
9490 } else {
9491 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9492 let project = cx
9493 .update(|cx| {
9494 active_call.0.join_project(
9495 project_id,
9496 app_state.languages.clone(),
9497 app_state.fs.clone(),
9498 cx,
9499 )
9500 })
9501 .await?;
9502
9503 let window_bounds_override = window_bounds_env_override();
9504 cx.update(|cx| {
9505 let mut options = (app_state.build_window_options)(None, cx);
9506 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9507 cx.open_window(options, |window, cx| {
9508 let workspace = cx.new(|cx| {
9509 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9510 });
9511 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9512 })
9513 })?
9514 };
9515
9516 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9517 cx.activate(true);
9518 window.activate_window();
9519
9520 // We set the active workspace above, so this is the correct workspace.
9521 let workspace = multi_workspace.workspace().clone();
9522 workspace.update(cx, |workspace, cx| {
9523 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9524 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9525 .or_else(|| {
9526 // If we couldn't follow the given user, follow the host instead.
9527 let collaborator = workspace
9528 .project()
9529 .read(cx)
9530 .collaborators()
9531 .values()
9532 .find(|collaborator| collaborator.is_host)?;
9533 Some(collaborator.peer_id)
9534 });
9535
9536 if let Some(follow_peer_id) = follow_peer_id {
9537 workspace.follow(follow_peer_id, window, cx);
9538 }
9539 });
9540 })?;
9541
9542 anyhow::Ok(())
9543 })
9544}
9545
9546pub fn reload(cx: &mut App) {
9547 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9548 let mut workspace_windows = cx
9549 .windows()
9550 .into_iter()
9551 .filter_map(|window| window.downcast::<MultiWorkspace>())
9552 .collect::<Vec<_>>();
9553
9554 // If multiple windows have unsaved changes, and need a save prompt,
9555 // prompt in the active window before switching to a different window.
9556 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9557
9558 let mut prompt = None;
9559 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9560 prompt = window
9561 .update(cx, |_, window, cx| {
9562 window.prompt(
9563 PromptLevel::Info,
9564 "Are you sure you want to restart?",
9565 None,
9566 &["Restart", "Cancel"],
9567 cx,
9568 )
9569 })
9570 .ok();
9571 }
9572
9573 cx.spawn(async move |cx| {
9574 if let Some(prompt) = prompt {
9575 let answer = prompt.await?;
9576 if answer != 0 {
9577 return anyhow::Ok(());
9578 }
9579 }
9580
9581 // If the user cancels any save prompt, then keep the app open.
9582 for window in workspace_windows {
9583 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9584 let workspace = multi_workspace.workspace().clone();
9585 workspace.update(cx, |workspace, cx| {
9586 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9587 })
9588 }) && !should_close.await?
9589 {
9590 return anyhow::Ok(());
9591 }
9592 }
9593 cx.update(|cx| cx.restart());
9594 anyhow::Ok(())
9595 })
9596 .detach_and_log_err(cx);
9597}
9598
9599fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9600 let mut parts = value.split(',');
9601 let x: usize = parts.next()?.parse().ok()?;
9602 let y: usize = parts.next()?.parse().ok()?;
9603 Some(point(px(x as f32), px(y as f32)))
9604}
9605
9606fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9607 let mut parts = value.split(',');
9608 let width: usize = parts.next()?.parse().ok()?;
9609 let height: usize = parts.next()?.parse().ok()?;
9610 Some(size(px(width as f32), px(height as f32)))
9611}
9612
9613/// Add client-side decorations (rounded corners, shadows, resize handling) when
9614/// appropriate.
9615///
9616/// The `border_radius_tiling` parameter allows overriding which corners get
9617/// rounded, independently of the actual window tiling state. This is used
9618/// specifically for the workspace switcher sidebar: when the sidebar is open,
9619/// we want square corners on the left (so the sidebar appears flush with the
9620/// window edge) but we still need the shadow padding for proper visual
9621/// appearance. Unlike actual window tiling, this only affects border radius -
9622/// not padding or shadows.
9623pub fn client_side_decorations(
9624 element: impl IntoElement,
9625 window: &mut Window,
9626 cx: &mut App,
9627 border_radius_tiling: Tiling,
9628) -> Stateful<Div> {
9629 const BORDER_SIZE: Pixels = px(1.0);
9630 let decorations = window.window_decorations();
9631 let tiling = match decorations {
9632 Decorations::Server => Tiling::default(),
9633 Decorations::Client { tiling } => tiling,
9634 };
9635
9636 match decorations {
9637 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9638 Decorations::Server => window.set_client_inset(px(0.0)),
9639 }
9640
9641 struct GlobalResizeEdge(ResizeEdge);
9642 impl Global for GlobalResizeEdge {}
9643
9644 div()
9645 .id("window-backdrop")
9646 .bg(transparent_black())
9647 .map(|div| match decorations {
9648 Decorations::Server => div,
9649 Decorations::Client { .. } => div
9650 .when(
9651 !(tiling.top
9652 || tiling.right
9653 || border_radius_tiling.top
9654 || border_radius_tiling.right),
9655 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9656 )
9657 .when(
9658 !(tiling.top
9659 || tiling.left
9660 || border_radius_tiling.top
9661 || border_radius_tiling.left),
9662 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9663 )
9664 .when(
9665 !(tiling.bottom
9666 || tiling.right
9667 || border_radius_tiling.bottom
9668 || border_radius_tiling.right),
9669 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9670 )
9671 .when(
9672 !(tiling.bottom
9673 || tiling.left
9674 || border_radius_tiling.bottom
9675 || border_radius_tiling.left),
9676 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9677 )
9678 .when(!tiling.top, |div| {
9679 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9680 })
9681 .when(!tiling.bottom, |div| {
9682 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9683 })
9684 .when(!tiling.left, |div| {
9685 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9686 })
9687 .when(!tiling.right, |div| {
9688 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9689 })
9690 .on_mouse_move(move |e, window, cx| {
9691 let size = window.window_bounds().get_bounds().size;
9692 let pos = e.position;
9693
9694 let new_edge =
9695 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9696
9697 let edge = cx.try_global::<GlobalResizeEdge>();
9698 if new_edge != edge.map(|edge| edge.0) {
9699 window
9700 .window_handle()
9701 .update(cx, |workspace, _, cx| {
9702 cx.notify(workspace.entity_id());
9703 })
9704 .ok();
9705 }
9706 })
9707 .on_mouse_down(MouseButton::Left, move |e, window, _| {
9708 let size = window.window_bounds().get_bounds().size;
9709 let pos = e.position;
9710
9711 let edge = match resize_edge(
9712 pos,
9713 theme::CLIENT_SIDE_DECORATION_SHADOW,
9714 size,
9715 tiling,
9716 ) {
9717 Some(value) => value,
9718 None => return,
9719 };
9720
9721 window.start_window_resize(edge);
9722 }),
9723 })
9724 .size_full()
9725 .child(
9726 div()
9727 .cursor(CursorStyle::Arrow)
9728 .map(|div| match decorations {
9729 Decorations::Server => div,
9730 Decorations::Client { .. } => div
9731 .border_color(cx.theme().colors().border)
9732 .when(
9733 !(tiling.top
9734 || tiling.right
9735 || border_radius_tiling.top
9736 || border_radius_tiling.right),
9737 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9738 )
9739 .when(
9740 !(tiling.top
9741 || tiling.left
9742 || border_radius_tiling.top
9743 || border_radius_tiling.left),
9744 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9745 )
9746 .when(
9747 !(tiling.bottom
9748 || tiling.right
9749 || border_radius_tiling.bottom
9750 || border_radius_tiling.right),
9751 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9752 )
9753 .when(
9754 !(tiling.bottom
9755 || tiling.left
9756 || border_radius_tiling.bottom
9757 || border_radius_tiling.left),
9758 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9759 )
9760 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
9761 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
9762 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
9763 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
9764 .when(!tiling.is_tiled(), |div| {
9765 div.shadow(vec![gpui::BoxShadow {
9766 color: Hsla {
9767 h: 0.,
9768 s: 0.,
9769 l: 0.,
9770 a: 0.4,
9771 },
9772 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
9773 spread_radius: px(0.),
9774 offset: point(px(0.0), px(0.0)),
9775 }])
9776 }),
9777 })
9778 .on_mouse_move(|_e, _, cx| {
9779 cx.stop_propagation();
9780 })
9781 .size_full()
9782 .child(element),
9783 )
9784 .map(|div| match decorations {
9785 Decorations::Server => div,
9786 Decorations::Client { tiling, .. } => div.child(
9787 canvas(
9788 |_bounds, window, _| {
9789 window.insert_hitbox(
9790 Bounds::new(
9791 point(px(0.0), px(0.0)),
9792 window.window_bounds().get_bounds().size,
9793 ),
9794 HitboxBehavior::Normal,
9795 )
9796 },
9797 move |_bounds, hitbox, window, cx| {
9798 let mouse = window.mouse_position();
9799 let size = window.window_bounds().get_bounds().size;
9800 let Some(edge) =
9801 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
9802 else {
9803 return;
9804 };
9805 cx.set_global(GlobalResizeEdge(edge));
9806 window.set_cursor_style(
9807 match edge {
9808 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
9809 ResizeEdge::Left | ResizeEdge::Right => {
9810 CursorStyle::ResizeLeftRight
9811 }
9812 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
9813 CursorStyle::ResizeUpLeftDownRight
9814 }
9815 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
9816 CursorStyle::ResizeUpRightDownLeft
9817 }
9818 },
9819 &hitbox,
9820 );
9821 },
9822 )
9823 .size_full()
9824 .absolute(),
9825 ),
9826 })
9827}
9828
9829fn resize_edge(
9830 pos: Point<Pixels>,
9831 shadow_size: Pixels,
9832 window_size: Size<Pixels>,
9833 tiling: Tiling,
9834) -> Option<ResizeEdge> {
9835 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
9836 if bounds.contains(&pos) {
9837 return None;
9838 }
9839
9840 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
9841 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
9842 if !tiling.top && top_left_bounds.contains(&pos) {
9843 return Some(ResizeEdge::TopLeft);
9844 }
9845
9846 let top_right_bounds = Bounds::new(
9847 Point::new(window_size.width - corner_size.width, px(0.)),
9848 corner_size,
9849 );
9850 if !tiling.top && top_right_bounds.contains(&pos) {
9851 return Some(ResizeEdge::TopRight);
9852 }
9853
9854 let bottom_left_bounds = Bounds::new(
9855 Point::new(px(0.), window_size.height - corner_size.height),
9856 corner_size,
9857 );
9858 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
9859 return Some(ResizeEdge::BottomLeft);
9860 }
9861
9862 let bottom_right_bounds = Bounds::new(
9863 Point::new(
9864 window_size.width - corner_size.width,
9865 window_size.height - corner_size.height,
9866 ),
9867 corner_size,
9868 );
9869 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
9870 return Some(ResizeEdge::BottomRight);
9871 }
9872
9873 if !tiling.top && pos.y < shadow_size {
9874 Some(ResizeEdge::Top)
9875 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
9876 Some(ResizeEdge::Bottom)
9877 } else if !tiling.left && pos.x < shadow_size {
9878 Some(ResizeEdge::Left)
9879 } else if !tiling.right && pos.x > window_size.width - shadow_size {
9880 Some(ResizeEdge::Right)
9881 } else {
9882 None
9883 }
9884}
9885
9886fn join_pane_into_active(
9887 active_pane: &Entity<Pane>,
9888 pane: &Entity<Pane>,
9889 window: &mut Window,
9890 cx: &mut App,
9891) {
9892 if pane == active_pane {
9893 } else if pane.read(cx).items_len() == 0 {
9894 pane.update(cx, |_, cx| {
9895 cx.emit(pane::Event::Remove {
9896 focus_on_pane: None,
9897 });
9898 })
9899 } else {
9900 move_all_items(pane, active_pane, window, cx);
9901 }
9902}
9903
9904fn move_all_items(
9905 from_pane: &Entity<Pane>,
9906 to_pane: &Entity<Pane>,
9907 window: &mut Window,
9908 cx: &mut App,
9909) {
9910 let destination_is_different = from_pane != to_pane;
9911 let mut moved_items = 0;
9912 for (item_ix, item_handle) in from_pane
9913 .read(cx)
9914 .items()
9915 .enumerate()
9916 .map(|(ix, item)| (ix, item.clone()))
9917 .collect::<Vec<_>>()
9918 {
9919 let ix = item_ix - moved_items;
9920 if destination_is_different {
9921 // Close item from previous pane
9922 from_pane.update(cx, |source, cx| {
9923 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
9924 });
9925 moved_items += 1;
9926 }
9927
9928 // This automatically removes duplicate items in the pane
9929 to_pane.update(cx, |destination, cx| {
9930 destination.add_item(item_handle, true, true, None, window, cx);
9931 window.focus(&destination.focus_handle(cx), cx)
9932 });
9933 }
9934}
9935
9936pub fn move_item(
9937 source: &Entity<Pane>,
9938 destination: &Entity<Pane>,
9939 item_id_to_move: EntityId,
9940 destination_index: usize,
9941 activate: bool,
9942 window: &mut Window,
9943 cx: &mut App,
9944) {
9945 let Some((item_ix, item_handle)) = source
9946 .read(cx)
9947 .items()
9948 .enumerate()
9949 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
9950 .map(|(ix, item)| (ix, item.clone()))
9951 else {
9952 // Tab was closed during drag
9953 return;
9954 };
9955
9956 if source != destination {
9957 // Close item from previous pane
9958 source.update(cx, |source, cx| {
9959 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
9960 });
9961 }
9962
9963 // This automatically removes duplicate items in the pane
9964 destination.update(cx, |destination, cx| {
9965 destination.add_item_inner(
9966 item_handle,
9967 activate,
9968 activate,
9969 activate,
9970 Some(destination_index),
9971 window,
9972 cx,
9973 );
9974 if activate {
9975 window.focus(&destination.focus_handle(cx), cx)
9976 }
9977 });
9978}
9979
9980pub fn move_active_item(
9981 source: &Entity<Pane>,
9982 destination: &Entity<Pane>,
9983 focus_destination: bool,
9984 close_if_empty: bool,
9985 window: &mut Window,
9986 cx: &mut App,
9987) {
9988 if source == destination {
9989 return;
9990 }
9991 let Some(active_item) = source.read(cx).active_item() else {
9992 return;
9993 };
9994 source.update(cx, |source_pane, cx| {
9995 let item_id = active_item.item_id();
9996 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
9997 destination.update(cx, |target_pane, cx| {
9998 target_pane.add_item(
9999 active_item,
10000 focus_destination,
10001 focus_destination,
10002 Some(target_pane.items_len()),
10003 window,
10004 cx,
10005 );
10006 });
10007 });
10008}
10009
10010pub fn clone_active_item(
10011 workspace_id: Option<WorkspaceId>,
10012 source: &Entity<Pane>,
10013 destination: &Entity<Pane>,
10014 focus_destination: bool,
10015 window: &mut Window,
10016 cx: &mut App,
10017) {
10018 if source == destination {
10019 return;
10020 }
10021 let Some(active_item) = source.read(cx).active_item() else {
10022 return;
10023 };
10024 if !active_item.can_split(cx) {
10025 return;
10026 }
10027 let destination = destination.downgrade();
10028 let task = active_item.clone_on_split(workspace_id, window, cx);
10029 window
10030 .spawn(cx, async move |cx| {
10031 let Some(clone) = task.await else {
10032 return;
10033 };
10034 destination
10035 .update_in(cx, |target_pane, window, cx| {
10036 target_pane.add_item(
10037 clone,
10038 focus_destination,
10039 focus_destination,
10040 Some(target_pane.items_len()),
10041 window,
10042 cx,
10043 );
10044 })
10045 .log_err();
10046 })
10047 .detach();
10048}
10049
10050#[derive(Debug)]
10051pub struct WorkspacePosition {
10052 pub window_bounds: Option<WindowBounds>,
10053 pub display: Option<Uuid>,
10054 pub centered_layout: bool,
10055}
10056
10057pub fn remote_workspace_position_from_db(
10058 connection_options: RemoteConnectionOptions,
10059 paths_to_open: &[PathBuf],
10060 cx: &App,
10061) -> Task<Result<WorkspacePosition>> {
10062 let paths = paths_to_open.to_vec();
10063 let db = WorkspaceDb::global(cx);
10064 let kvp = db::kvp::KeyValueStore::global(cx);
10065
10066 cx.background_spawn(async move {
10067 let remote_connection_id = db
10068 .get_or_create_remote_connection(connection_options)
10069 .await
10070 .context("fetching serialized ssh project")?;
10071 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10072
10073 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10074 (Some(WindowBounds::Windowed(bounds)), None)
10075 } else {
10076 let restorable_bounds = serialized_workspace
10077 .as_ref()
10078 .and_then(|workspace| {
10079 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10080 })
10081 .or_else(|| persistence::read_default_window_bounds(&kvp));
10082
10083 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10084 (Some(serialized_bounds), Some(serialized_display))
10085 } else {
10086 (None, None)
10087 }
10088 };
10089
10090 let centered_layout = serialized_workspace
10091 .as_ref()
10092 .map(|w| w.centered_layout)
10093 .unwrap_or(false);
10094
10095 Ok(WorkspacePosition {
10096 window_bounds,
10097 display,
10098 centered_layout,
10099 })
10100 })
10101}
10102
10103pub fn with_active_or_new_workspace(
10104 cx: &mut App,
10105 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10106) {
10107 match cx
10108 .active_window()
10109 .and_then(|w| w.downcast::<MultiWorkspace>())
10110 {
10111 Some(multi_workspace) => {
10112 cx.defer(move |cx| {
10113 multi_workspace
10114 .update(cx, |multi_workspace, window, cx| {
10115 let workspace = multi_workspace.workspace().clone();
10116 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10117 })
10118 .log_err();
10119 });
10120 }
10121 None => {
10122 let app_state = AppState::global(cx);
10123 if let Some(app_state) = app_state.upgrade() {
10124 open_new(
10125 OpenOptions::default(),
10126 app_state,
10127 cx,
10128 move |workspace, window, cx| f(workspace, window, cx),
10129 )
10130 .detach_and_log_err(cx);
10131 }
10132 }
10133 }
10134}
10135
10136#[cfg(test)]
10137mod tests {
10138 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10139
10140 use super::*;
10141 use crate::{
10142 dock::{PanelEvent, test::TestPanel},
10143 item::{
10144 ItemBufferKind, ItemEvent,
10145 test::{TestItem, TestProjectItem},
10146 },
10147 };
10148 use fs::FakeFs;
10149 use gpui::{
10150 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10151 UpdateGlobal, VisualTestContext, px,
10152 };
10153 use project::{Project, ProjectEntryId};
10154 use serde_json::json;
10155 use settings::SettingsStore;
10156 use util::path;
10157 use util::rel_path::rel_path;
10158
10159 #[gpui::test]
10160 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10161 init_test(cx);
10162
10163 let fs = FakeFs::new(cx.executor());
10164 let project = Project::test(fs, [], cx).await;
10165 let (workspace, cx) =
10166 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10167
10168 // Adding an item with no ambiguity renders the tab without detail.
10169 let item1 = cx.new(|cx| {
10170 let mut item = TestItem::new(cx);
10171 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10172 item
10173 });
10174 workspace.update_in(cx, |workspace, window, cx| {
10175 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10176 });
10177 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10178
10179 // Adding an item that creates ambiguity increases the level of detail on
10180 // both tabs.
10181 let item2 = cx.new_window_entity(|_window, cx| {
10182 let mut item = TestItem::new(cx);
10183 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10184 item
10185 });
10186 workspace.update_in(cx, |workspace, window, cx| {
10187 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10188 });
10189 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10190 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10191
10192 // Adding an item that creates ambiguity increases the level of detail only
10193 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10194 // we stop at the highest detail available.
10195 let item3 = cx.new(|cx| {
10196 let mut item = TestItem::new(cx);
10197 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10198 item
10199 });
10200 workspace.update_in(cx, |workspace, window, cx| {
10201 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10202 });
10203 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10204 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10205 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10206 }
10207
10208 #[gpui::test]
10209 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10210 init_test(cx);
10211
10212 let fs = FakeFs::new(cx.executor());
10213 fs.insert_tree(
10214 "/root1",
10215 json!({
10216 "one.txt": "",
10217 "two.txt": "",
10218 }),
10219 )
10220 .await;
10221 fs.insert_tree(
10222 "/root2",
10223 json!({
10224 "three.txt": "",
10225 }),
10226 )
10227 .await;
10228
10229 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10230 let (workspace, cx) =
10231 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10232 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10233 let worktree_id = project.update(cx, |project, cx| {
10234 project.worktrees(cx).next().unwrap().read(cx).id()
10235 });
10236
10237 let item1 = cx.new(|cx| {
10238 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10239 });
10240 let item2 = cx.new(|cx| {
10241 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10242 });
10243
10244 // Add an item to an empty pane
10245 workspace.update_in(cx, |workspace, window, cx| {
10246 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10247 });
10248 project.update(cx, |project, cx| {
10249 assert_eq!(
10250 project.active_entry(),
10251 project
10252 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10253 .map(|e| e.id)
10254 );
10255 });
10256 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10257
10258 // Add a second item to a non-empty pane
10259 workspace.update_in(cx, |workspace, window, cx| {
10260 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10261 });
10262 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10263 project.update(cx, |project, cx| {
10264 assert_eq!(
10265 project.active_entry(),
10266 project
10267 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10268 .map(|e| e.id)
10269 );
10270 });
10271
10272 // Close the active item
10273 pane.update_in(cx, |pane, window, cx| {
10274 pane.close_active_item(&Default::default(), window, cx)
10275 })
10276 .await
10277 .unwrap();
10278 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10279 project.update(cx, |project, cx| {
10280 assert_eq!(
10281 project.active_entry(),
10282 project
10283 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10284 .map(|e| e.id)
10285 );
10286 });
10287
10288 // Add a project folder
10289 project
10290 .update(cx, |project, cx| {
10291 project.find_or_create_worktree("root2", true, cx)
10292 })
10293 .await
10294 .unwrap();
10295 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10296
10297 // Remove a project folder
10298 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10299 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10300 }
10301
10302 #[gpui::test]
10303 async fn test_close_window(cx: &mut TestAppContext) {
10304 init_test(cx);
10305
10306 let fs = FakeFs::new(cx.executor());
10307 fs.insert_tree("/root", json!({ "one": "" })).await;
10308
10309 let project = Project::test(fs, ["root".as_ref()], cx).await;
10310 let (workspace, cx) =
10311 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10312
10313 // When there are no dirty items, there's nothing to do.
10314 let item1 = cx.new(TestItem::new);
10315 workspace.update_in(cx, |w, window, cx| {
10316 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10317 });
10318 let task = workspace.update_in(cx, |w, window, cx| {
10319 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10320 });
10321 assert!(task.await.unwrap());
10322
10323 // When there are dirty untitled items, prompt to save each one. If the user
10324 // cancels any prompt, then abort.
10325 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10326 let item3 = cx.new(|cx| {
10327 TestItem::new(cx)
10328 .with_dirty(true)
10329 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10330 });
10331 workspace.update_in(cx, |w, window, cx| {
10332 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10333 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10334 });
10335 let task = workspace.update_in(cx, |w, window, cx| {
10336 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10337 });
10338 cx.executor().run_until_parked();
10339 cx.simulate_prompt_answer("Cancel"); // cancel save all
10340 cx.executor().run_until_parked();
10341 assert!(!cx.has_pending_prompt());
10342 assert!(!task.await.unwrap());
10343 }
10344
10345 #[gpui::test]
10346 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10347 init_test(cx);
10348
10349 let fs = FakeFs::new(cx.executor());
10350 fs.insert_tree("/root", json!({ "one": "" })).await;
10351
10352 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10353 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10354 let multi_workspace_handle =
10355 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10356 cx.run_until_parked();
10357
10358 let workspace_a = multi_workspace_handle
10359 .read_with(cx, |mw, _| mw.workspace().clone())
10360 .unwrap();
10361
10362 let workspace_b = multi_workspace_handle
10363 .update(cx, |mw, window, cx| {
10364 mw.test_add_workspace(project_b, window, cx)
10365 })
10366 .unwrap();
10367
10368 // Activate workspace A
10369 multi_workspace_handle
10370 .update(cx, |mw, window, cx| {
10371 mw.activate_index(0, window, cx);
10372 })
10373 .unwrap();
10374
10375 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10376
10377 // Workspace A has a clean item
10378 let item_a = cx.new(TestItem::new);
10379 workspace_a.update_in(cx, |w, window, cx| {
10380 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10381 });
10382
10383 // Workspace B has a dirty item
10384 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10385 workspace_b.update_in(cx, |w, window, cx| {
10386 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10387 });
10388
10389 // Verify workspace A is active
10390 multi_workspace_handle
10391 .read_with(cx, |mw, _| {
10392 assert_eq!(mw.active_workspace_index(), 0);
10393 })
10394 .unwrap();
10395
10396 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10397 multi_workspace_handle
10398 .update(cx, |mw, window, cx| {
10399 mw.close_window(&CloseWindow, window, cx);
10400 })
10401 .unwrap();
10402 cx.run_until_parked();
10403
10404 // Workspace B should now be active since it has dirty items that need attention
10405 multi_workspace_handle
10406 .read_with(cx, |mw, _| {
10407 assert_eq!(
10408 mw.active_workspace_index(),
10409 1,
10410 "workspace B should be activated when it prompts"
10411 );
10412 })
10413 .unwrap();
10414
10415 // User cancels the save prompt from workspace B
10416 cx.simulate_prompt_answer("Cancel");
10417 cx.run_until_parked();
10418
10419 // Window should still exist because workspace B's close was cancelled
10420 assert!(
10421 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10422 "window should still exist after cancelling one workspace's close"
10423 );
10424 }
10425
10426 #[gpui::test]
10427 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10428 init_test(cx);
10429
10430 // Register TestItem as a serializable item
10431 cx.update(|cx| {
10432 register_serializable_item::<TestItem>(cx);
10433 });
10434
10435 let fs = FakeFs::new(cx.executor());
10436 fs.insert_tree("/root", json!({ "one": "" })).await;
10437
10438 let project = Project::test(fs, ["root".as_ref()], cx).await;
10439 let (workspace, cx) =
10440 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10441
10442 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10443 let item1 = cx.new(|cx| {
10444 TestItem::new(cx)
10445 .with_dirty(true)
10446 .with_serialize(|| Some(Task::ready(Ok(()))))
10447 });
10448 let item2 = cx.new(|cx| {
10449 TestItem::new(cx)
10450 .with_dirty(true)
10451 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10452 .with_serialize(|| Some(Task::ready(Ok(()))))
10453 });
10454 workspace.update_in(cx, |w, window, cx| {
10455 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10456 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10457 });
10458 let task = workspace.update_in(cx, |w, window, cx| {
10459 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10460 });
10461 assert!(task.await.unwrap());
10462 }
10463
10464 #[gpui::test]
10465 async fn test_close_pane_items(cx: &mut TestAppContext) {
10466 init_test(cx);
10467
10468 let fs = FakeFs::new(cx.executor());
10469
10470 let project = Project::test(fs, None, cx).await;
10471 let (workspace, cx) =
10472 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10473
10474 let item1 = cx.new(|cx| {
10475 TestItem::new(cx)
10476 .with_dirty(true)
10477 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10478 });
10479 let item2 = cx.new(|cx| {
10480 TestItem::new(cx)
10481 .with_dirty(true)
10482 .with_conflict(true)
10483 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10484 });
10485 let item3 = cx.new(|cx| {
10486 TestItem::new(cx)
10487 .with_dirty(true)
10488 .with_conflict(true)
10489 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10490 });
10491 let item4 = cx.new(|cx| {
10492 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10493 let project_item = TestProjectItem::new_untitled(cx);
10494 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10495 project_item
10496 }])
10497 });
10498 let pane = workspace.update_in(cx, |workspace, window, cx| {
10499 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10500 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10501 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10502 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10503 workspace.active_pane().clone()
10504 });
10505
10506 let close_items = pane.update_in(cx, |pane, window, cx| {
10507 pane.activate_item(1, true, true, window, cx);
10508 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10509 let item1_id = item1.item_id();
10510 let item3_id = item3.item_id();
10511 let item4_id = item4.item_id();
10512 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10513 [item1_id, item3_id, item4_id].contains(&id)
10514 })
10515 });
10516 cx.executor().run_until_parked();
10517
10518 assert!(cx.has_pending_prompt());
10519 cx.simulate_prompt_answer("Save all");
10520
10521 cx.executor().run_until_parked();
10522
10523 // Item 1 is saved. There's a prompt to save item 3.
10524 pane.update(cx, |pane, cx| {
10525 assert_eq!(item1.read(cx).save_count, 1);
10526 assert_eq!(item1.read(cx).save_as_count, 0);
10527 assert_eq!(item1.read(cx).reload_count, 0);
10528 assert_eq!(pane.items_len(), 3);
10529 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10530 });
10531 assert!(cx.has_pending_prompt());
10532
10533 // Cancel saving item 3.
10534 cx.simulate_prompt_answer("Discard");
10535 cx.executor().run_until_parked();
10536
10537 // Item 3 is reloaded. There's a prompt to save item 4.
10538 pane.update(cx, |pane, cx| {
10539 assert_eq!(item3.read(cx).save_count, 0);
10540 assert_eq!(item3.read(cx).save_as_count, 0);
10541 assert_eq!(item3.read(cx).reload_count, 1);
10542 assert_eq!(pane.items_len(), 2);
10543 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10544 });
10545
10546 // There's a prompt for a path for item 4.
10547 cx.simulate_new_path_selection(|_| Some(Default::default()));
10548 close_items.await.unwrap();
10549
10550 // The requested items are closed.
10551 pane.update(cx, |pane, cx| {
10552 assert_eq!(item4.read(cx).save_count, 0);
10553 assert_eq!(item4.read(cx).save_as_count, 1);
10554 assert_eq!(item4.read(cx).reload_count, 0);
10555 assert_eq!(pane.items_len(), 1);
10556 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10557 });
10558 }
10559
10560 #[gpui::test]
10561 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10562 init_test(cx);
10563
10564 let fs = FakeFs::new(cx.executor());
10565 let project = Project::test(fs, [], cx).await;
10566 let (workspace, cx) =
10567 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10568
10569 // Create several workspace items with single project entries, and two
10570 // workspace items with multiple project entries.
10571 let single_entry_items = (0..=4)
10572 .map(|project_entry_id| {
10573 cx.new(|cx| {
10574 TestItem::new(cx)
10575 .with_dirty(true)
10576 .with_project_items(&[dirty_project_item(
10577 project_entry_id,
10578 &format!("{project_entry_id}.txt"),
10579 cx,
10580 )])
10581 })
10582 })
10583 .collect::<Vec<_>>();
10584 let item_2_3 = cx.new(|cx| {
10585 TestItem::new(cx)
10586 .with_dirty(true)
10587 .with_buffer_kind(ItemBufferKind::Multibuffer)
10588 .with_project_items(&[
10589 single_entry_items[2].read(cx).project_items[0].clone(),
10590 single_entry_items[3].read(cx).project_items[0].clone(),
10591 ])
10592 });
10593 let item_3_4 = cx.new(|cx| {
10594 TestItem::new(cx)
10595 .with_dirty(true)
10596 .with_buffer_kind(ItemBufferKind::Multibuffer)
10597 .with_project_items(&[
10598 single_entry_items[3].read(cx).project_items[0].clone(),
10599 single_entry_items[4].read(cx).project_items[0].clone(),
10600 ])
10601 });
10602
10603 // Create two panes that contain the following project entries:
10604 // left pane:
10605 // multi-entry items: (2, 3)
10606 // single-entry items: 0, 2, 3, 4
10607 // right pane:
10608 // single-entry items: 4, 1
10609 // multi-entry items: (3, 4)
10610 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10611 let left_pane = workspace.active_pane().clone();
10612 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10613 workspace.add_item_to_active_pane(
10614 single_entry_items[0].boxed_clone(),
10615 None,
10616 true,
10617 window,
10618 cx,
10619 );
10620 workspace.add_item_to_active_pane(
10621 single_entry_items[2].boxed_clone(),
10622 None,
10623 true,
10624 window,
10625 cx,
10626 );
10627 workspace.add_item_to_active_pane(
10628 single_entry_items[3].boxed_clone(),
10629 None,
10630 true,
10631 window,
10632 cx,
10633 );
10634 workspace.add_item_to_active_pane(
10635 single_entry_items[4].boxed_clone(),
10636 None,
10637 true,
10638 window,
10639 cx,
10640 );
10641
10642 let right_pane =
10643 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10644
10645 let boxed_clone = single_entry_items[1].boxed_clone();
10646 let right_pane = window.spawn(cx, async move |cx| {
10647 right_pane.await.inspect(|right_pane| {
10648 right_pane
10649 .update_in(cx, |pane, window, cx| {
10650 pane.add_item(boxed_clone, true, true, None, window, cx);
10651 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10652 })
10653 .unwrap();
10654 })
10655 });
10656
10657 (left_pane, right_pane)
10658 });
10659 let right_pane = right_pane.await.unwrap();
10660 cx.focus(&right_pane);
10661
10662 let close = right_pane.update_in(cx, |pane, window, cx| {
10663 pane.close_all_items(&CloseAllItems::default(), window, cx)
10664 .unwrap()
10665 });
10666 cx.executor().run_until_parked();
10667
10668 let msg = cx.pending_prompt().unwrap().0;
10669 assert!(msg.contains("1.txt"));
10670 assert!(!msg.contains("2.txt"));
10671 assert!(!msg.contains("3.txt"));
10672 assert!(!msg.contains("4.txt"));
10673
10674 // With best-effort close, cancelling item 1 keeps it open but items 4
10675 // and (3,4) still close since their entries exist in left pane.
10676 cx.simulate_prompt_answer("Cancel");
10677 close.await;
10678
10679 right_pane.read_with(cx, |pane, _| {
10680 assert_eq!(pane.items_len(), 1);
10681 });
10682
10683 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10684 left_pane
10685 .update_in(cx, |left_pane, window, cx| {
10686 left_pane.close_item_by_id(
10687 single_entry_items[3].entity_id(),
10688 SaveIntent::Skip,
10689 window,
10690 cx,
10691 )
10692 })
10693 .await
10694 .unwrap();
10695
10696 let close = left_pane.update_in(cx, |pane, window, cx| {
10697 pane.close_all_items(&CloseAllItems::default(), window, cx)
10698 .unwrap()
10699 });
10700 cx.executor().run_until_parked();
10701
10702 let details = cx.pending_prompt().unwrap().1;
10703 assert!(details.contains("0.txt"));
10704 assert!(details.contains("3.txt"));
10705 assert!(details.contains("4.txt"));
10706 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10707 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10708 // assert!(!details.contains("2.txt"));
10709
10710 cx.simulate_prompt_answer("Save all");
10711 cx.executor().run_until_parked();
10712 close.await;
10713
10714 left_pane.read_with(cx, |pane, _| {
10715 assert_eq!(pane.items_len(), 0);
10716 });
10717 }
10718
10719 #[gpui::test]
10720 async fn test_autosave(cx: &mut gpui::TestAppContext) {
10721 init_test(cx);
10722
10723 let fs = FakeFs::new(cx.executor());
10724 let project = Project::test(fs, [], cx).await;
10725 let (workspace, cx) =
10726 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10727 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10728
10729 let item = cx.new(|cx| {
10730 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10731 });
10732 let item_id = item.entity_id();
10733 workspace.update_in(cx, |workspace, window, cx| {
10734 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10735 });
10736
10737 // Autosave on window change.
10738 item.update(cx, |item, cx| {
10739 SettingsStore::update_global(cx, |settings, cx| {
10740 settings.update_user_settings(cx, |settings| {
10741 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10742 })
10743 });
10744 item.is_dirty = true;
10745 });
10746
10747 // Deactivating the window saves the file.
10748 cx.deactivate_window();
10749 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10750
10751 // Re-activating the window doesn't save the file.
10752 cx.update(|window, _| window.activate_window());
10753 cx.executor().run_until_parked();
10754 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10755
10756 // Autosave on focus change.
10757 item.update_in(cx, |item, window, cx| {
10758 cx.focus_self(window);
10759 SettingsStore::update_global(cx, |settings, cx| {
10760 settings.update_user_settings(cx, |settings| {
10761 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10762 })
10763 });
10764 item.is_dirty = true;
10765 });
10766 // Blurring the item saves the file.
10767 item.update_in(cx, |_, window, _| window.blur());
10768 cx.executor().run_until_parked();
10769 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10770
10771 // Deactivating the window still saves the file.
10772 item.update_in(cx, |item, window, cx| {
10773 cx.focus_self(window);
10774 item.is_dirty = true;
10775 });
10776 cx.deactivate_window();
10777 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10778
10779 // Autosave after delay.
10780 item.update(cx, |item, cx| {
10781 SettingsStore::update_global(cx, |settings, cx| {
10782 settings.update_user_settings(cx, |settings| {
10783 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10784 milliseconds: 500.into(),
10785 });
10786 })
10787 });
10788 item.is_dirty = true;
10789 cx.emit(ItemEvent::Edit);
10790 });
10791
10792 // Delay hasn't fully expired, so the file is still dirty and unsaved.
10793 cx.executor().advance_clock(Duration::from_millis(250));
10794 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10795
10796 // After delay expires, the file is saved.
10797 cx.executor().advance_clock(Duration::from_millis(250));
10798 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10799
10800 // Autosave after delay, should save earlier than delay if tab is closed
10801 item.update(cx, |item, cx| {
10802 item.is_dirty = true;
10803 cx.emit(ItemEvent::Edit);
10804 });
10805 cx.executor().advance_clock(Duration::from_millis(250));
10806 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10807
10808 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10809 pane.update_in(cx, |pane, window, cx| {
10810 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10811 })
10812 .await
10813 .unwrap();
10814 assert!(!cx.has_pending_prompt());
10815 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10816
10817 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10818 workspace.update_in(cx, |workspace, window, cx| {
10819 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10820 });
10821 item.update_in(cx, |item, _window, cx| {
10822 item.is_dirty = true;
10823 for project_item in &mut item.project_items {
10824 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10825 }
10826 });
10827 cx.run_until_parked();
10828 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10829
10830 // Autosave on focus change, ensuring closing the tab counts as such.
10831 item.update(cx, |item, cx| {
10832 SettingsStore::update_global(cx, |settings, cx| {
10833 settings.update_user_settings(cx, |settings| {
10834 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10835 })
10836 });
10837 item.is_dirty = true;
10838 for project_item in &mut item.project_items {
10839 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10840 }
10841 });
10842
10843 pane.update_in(cx, |pane, window, cx| {
10844 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10845 })
10846 .await
10847 .unwrap();
10848 assert!(!cx.has_pending_prompt());
10849 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10850
10851 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10852 workspace.update_in(cx, |workspace, window, cx| {
10853 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10854 });
10855 item.update_in(cx, |item, window, cx| {
10856 item.project_items[0].update(cx, |item, _| {
10857 item.entry_id = None;
10858 });
10859 item.is_dirty = true;
10860 window.blur();
10861 });
10862 cx.run_until_parked();
10863 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10864
10865 // Ensure autosave is prevented for deleted files also when closing the buffer.
10866 let _close_items = pane.update_in(cx, |pane, window, cx| {
10867 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10868 });
10869 cx.run_until_parked();
10870 assert!(cx.has_pending_prompt());
10871 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10872 }
10873
10874 #[gpui::test]
10875 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
10876 init_test(cx);
10877
10878 let fs = FakeFs::new(cx.executor());
10879 let project = Project::test(fs, [], cx).await;
10880 let (workspace, cx) =
10881 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10882
10883 // Create a multibuffer-like item with two child focus handles,
10884 // simulating individual buffer editors within a multibuffer.
10885 let item = cx.new(|cx| {
10886 TestItem::new(cx)
10887 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10888 .with_child_focus_handles(2, cx)
10889 });
10890 workspace.update_in(cx, |workspace, window, cx| {
10891 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10892 });
10893
10894 // Set autosave to OnFocusChange and focus the first child handle,
10895 // simulating the user's cursor being inside one of the multibuffer's excerpts.
10896 item.update_in(cx, |item, window, cx| {
10897 SettingsStore::update_global(cx, |settings, cx| {
10898 settings.update_user_settings(cx, |settings| {
10899 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10900 })
10901 });
10902 item.is_dirty = true;
10903 window.focus(&item.child_focus_handles[0], cx);
10904 });
10905 cx.executor().run_until_parked();
10906 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
10907
10908 // Moving focus from one child to another within the same item should
10909 // NOT trigger autosave — focus is still within the item's focus hierarchy.
10910 item.update_in(cx, |item, window, cx| {
10911 window.focus(&item.child_focus_handles[1], cx);
10912 });
10913 cx.executor().run_until_parked();
10914 item.read_with(cx, |item, _| {
10915 assert_eq!(
10916 item.save_count, 0,
10917 "Switching focus between children within the same item should not autosave"
10918 );
10919 });
10920
10921 // Blurring the item saves the file. This is the core regression scenario:
10922 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
10923 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
10924 // the leaf is always a child focus handle, so `on_blur` never detected
10925 // focus leaving the item.
10926 item.update_in(cx, |_, window, _| window.blur());
10927 cx.executor().run_until_parked();
10928 item.read_with(cx, |item, _| {
10929 assert_eq!(
10930 item.save_count, 1,
10931 "Blurring should trigger autosave when focus was on a child of the item"
10932 );
10933 });
10934
10935 // Deactivating the window should also trigger autosave when a child of
10936 // the multibuffer item currently owns focus.
10937 item.update_in(cx, |item, window, cx| {
10938 item.is_dirty = true;
10939 window.focus(&item.child_focus_handles[0], cx);
10940 });
10941 cx.executor().run_until_parked();
10942 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10943
10944 cx.deactivate_window();
10945 item.read_with(cx, |item, _| {
10946 assert_eq!(
10947 item.save_count, 2,
10948 "Deactivating window should trigger autosave when focus was on a child"
10949 );
10950 });
10951 }
10952
10953 #[gpui::test]
10954 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10955 init_test(cx);
10956
10957 let fs = FakeFs::new(cx.executor());
10958
10959 let project = Project::test(fs, [], cx).await;
10960 let (workspace, cx) =
10961 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10962
10963 let item = cx.new(|cx| {
10964 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10965 });
10966 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10967 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10968 let toolbar_notify_count = Rc::new(RefCell::new(0));
10969
10970 workspace.update_in(cx, |workspace, window, cx| {
10971 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10972 let toolbar_notification_count = toolbar_notify_count.clone();
10973 cx.observe_in(&toolbar, window, move |_, _, _, _| {
10974 *toolbar_notification_count.borrow_mut() += 1
10975 })
10976 .detach();
10977 });
10978
10979 pane.read_with(cx, |pane, _| {
10980 assert!(!pane.can_navigate_backward());
10981 assert!(!pane.can_navigate_forward());
10982 });
10983
10984 item.update_in(cx, |item, _, cx| {
10985 item.set_state("one".to_string(), cx);
10986 });
10987
10988 // Toolbar must be notified to re-render the navigation buttons
10989 assert_eq!(*toolbar_notify_count.borrow(), 1);
10990
10991 pane.read_with(cx, |pane, _| {
10992 assert!(pane.can_navigate_backward());
10993 assert!(!pane.can_navigate_forward());
10994 });
10995
10996 workspace
10997 .update_in(cx, |workspace, window, cx| {
10998 workspace.go_back(pane.downgrade(), window, cx)
10999 })
11000 .await
11001 .unwrap();
11002
11003 assert_eq!(*toolbar_notify_count.borrow(), 2);
11004 pane.read_with(cx, |pane, _| {
11005 assert!(!pane.can_navigate_backward());
11006 assert!(pane.can_navigate_forward());
11007 });
11008 }
11009
11010 #[gpui::test]
11011 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11012 init_test(cx);
11013 let fs = FakeFs::new(cx.executor());
11014 let project = Project::test(fs, [], cx).await;
11015 let (multi_workspace, cx) =
11016 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11017 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11018
11019 workspace.update_in(cx, |workspace, window, cx| {
11020 let first_item = cx.new(|cx| {
11021 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11022 });
11023 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11024 workspace.split_pane(
11025 workspace.active_pane().clone(),
11026 SplitDirection::Right,
11027 window,
11028 cx,
11029 );
11030 workspace.split_pane(
11031 workspace.active_pane().clone(),
11032 SplitDirection::Right,
11033 window,
11034 cx,
11035 );
11036 });
11037
11038 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11039 let panes = workspace.center.panes();
11040 assert!(panes.len() >= 2);
11041 (
11042 panes.first().expect("at least one pane").entity_id(),
11043 panes.last().expect("at least one pane").entity_id(),
11044 )
11045 });
11046
11047 workspace.update_in(cx, |workspace, window, cx| {
11048 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11049 });
11050 workspace.update(cx, |workspace, _| {
11051 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11052 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11053 });
11054
11055 cx.dispatch_action(ActivateLastPane);
11056
11057 workspace.update(cx, |workspace, _| {
11058 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11059 });
11060 }
11061
11062 #[gpui::test]
11063 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11064 init_test(cx);
11065 let fs = FakeFs::new(cx.executor());
11066
11067 let project = Project::test(fs, [], cx).await;
11068 let (workspace, cx) =
11069 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11070
11071 let panel = workspace.update_in(cx, |workspace, window, cx| {
11072 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11073 workspace.add_panel(panel.clone(), window, cx);
11074
11075 workspace
11076 .right_dock()
11077 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11078
11079 panel
11080 });
11081
11082 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11083 pane.update_in(cx, |pane, window, cx| {
11084 let item = cx.new(TestItem::new);
11085 pane.add_item(Box::new(item), true, true, None, window, cx);
11086 });
11087
11088 // Transfer focus from center to panel
11089 workspace.update_in(cx, |workspace, window, cx| {
11090 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11091 });
11092
11093 workspace.update_in(cx, |workspace, window, cx| {
11094 assert!(workspace.right_dock().read(cx).is_open());
11095 assert!(!panel.is_zoomed(window, cx));
11096 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11097 });
11098
11099 // Transfer focus from panel to center
11100 workspace.update_in(cx, |workspace, window, cx| {
11101 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11102 });
11103
11104 workspace.update_in(cx, |workspace, window, cx| {
11105 assert!(workspace.right_dock().read(cx).is_open());
11106 assert!(!panel.is_zoomed(window, cx));
11107 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11108 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11109 });
11110
11111 // Close the dock
11112 workspace.update_in(cx, |workspace, window, cx| {
11113 workspace.toggle_dock(DockPosition::Right, window, cx);
11114 });
11115
11116 workspace.update_in(cx, |workspace, window, cx| {
11117 assert!(!workspace.right_dock().read(cx).is_open());
11118 assert!(!panel.is_zoomed(window, cx));
11119 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11120 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11121 });
11122
11123 // Open the dock
11124 workspace.update_in(cx, |workspace, window, cx| {
11125 workspace.toggle_dock(DockPosition::Right, 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 // Focus and zoom panel
11135 panel.update_in(cx, |panel, window, cx| {
11136 cx.focus_self(window);
11137 panel.set_zoomed(true, window, cx)
11138 });
11139
11140 workspace.update_in(cx, |workspace, window, cx| {
11141 assert!(workspace.right_dock().read(cx).is_open());
11142 assert!(panel.is_zoomed(window, cx));
11143 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11144 });
11145
11146 // Transfer focus to the center closes the dock
11147 workspace.update_in(cx, |workspace, window, cx| {
11148 workspace.toggle_panel_focus::<TestPanel>(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!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11155 });
11156
11157 // Transferring focus back to the panel keeps it zoomed
11158 workspace.update_in(cx, |workspace, window, cx| {
11159 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11160 });
11161
11162 workspace.update_in(cx, |workspace, window, cx| {
11163 assert!(workspace.right_dock().read(cx).is_open());
11164 assert!(panel.is_zoomed(window, cx));
11165 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11166 });
11167
11168 // Close the dock while it is zoomed
11169 workspace.update_in(cx, |workspace, window, cx| {
11170 workspace.toggle_dock(DockPosition::Right, window, cx)
11171 });
11172
11173 workspace.update_in(cx, |workspace, window, cx| {
11174 assert!(!workspace.right_dock().read(cx).is_open());
11175 assert!(panel.is_zoomed(window, cx));
11176 assert!(workspace.zoomed.is_none());
11177 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11178 });
11179
11180 // Opening the dock, when it's zoomed, retains focus
11181 workspace.update_in(cx, |workspace, window, cx| {
11182 workspace.toggle_dock(DockPosition::Right, window, cx)
11183 });
11184
11185 workspace.update_in(cx, |workspace, window, cx| {
11186 assert!(workspace.right_dock().read(cx).is_open());
11187 assert!(panel.is_zoomed(window, cx));
11188 assert!(workspace.zoomed.is_some());
11189 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11190 });
11191
11192 // Unzoom and close the panel, zoom the active pane.
11193 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11194 workspace.update_in(cx, |workspace, window, cx| {
11195 workspace.toggle_dock(DockPosition::Right, window, cx)
11196 });
11197 pane.update_in(cx, |pane, window, cx| {
11198 pane.toggle_zoom(&Default::default(), window, cx)
11199 });
11200
11201 // Opening a dock unzooms the pane.
11202 workspace.update_in(cx, |workspace, window, cx| {
11203 workspace.toggle_dock(DockPosition::Right, window, cx)
11204 });
11205 workspace.update_in(cx, |workspace, window, cx| {
11206 let pane = pane.read(cx);
11207 assert!(!pane.is_zoomed());
11208 assert!(!pane.focus_handle(cx).is_focused(window));
11209 assert!(workspace.right_dock().read(cx).is_open());
11210 assert!(workspace.zoomed.is_none());
11211 });
11212 }
11213
11214 #[gpui::test]
11215 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11216 init_test(cx);
11217 let fs = FakeFs::new(cx.executor());
11218
11219 let project = Project::test(fs, [], cx).await;
11220 let (workspace, cx) =
11221 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11222
11223 let panel = workspace.update_in(cx, |workspace, window, cx| {
11224 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11225 workspace.add_panel(panel.clone(), window, cx);
11226 panel
11227 });
11228
11229 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11230 pane.update_in(cx, |pane, window, cx| {
11231 let item = cx.new(TestItem::new);
11232 pane.add_item(Box::new(item), true, true, None, window, cx);
11233 });
11234
11235 // Enable close_panel_on_toggle
11236 cx.update_global(|store: &mut SettingsStore, cx| {
11237 store.update_user_settings(cx, |settings| {
11238 settings.workspace.close_panel_on_toggle = Some(true);
11239 });
11240 });
11241
11242 // Panel starts closed. Toggling should open and focus it.
11243 workspace.update_in(cx, |workspace, window, cx| {
11244 assert!(!workspace.right_dock().read(cx).is_open());
11245 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11246 });
11247
11248 workspace.update_in(cx, |workspace, window, cx| {
11249 assert!(
11250 workspace.right_dock().read(cx).is_open(),
11251 "Dock should be open after toggling from center"
11252 );
11253 assert!(
11254 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11255 "Panel should be focused after toggling from center"
11256 );
11257 });
11258
11259 // Panel is open and focused. Toggling should close the panel and
11260 // return focus to the center.
11261 workspace.update_in(cx, |workspace, window, cx| {
11262 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11263 });
11264
11265 workspace.update_in(cx, |workspace, window, cx| {
11266 assert!(
11267 !workspace.right_dock().read(cx).is_open(),
11268 "Dock should be closed after toggling from focused panel"
11269 );
11270 assert!(
11271 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11272 "Panel should not be focused after toggling from focused panel"
11273 );
11274 });
11275
11276 // Open the dock and focus something else so the panel is open but not
11277 // focused. Toggling should focus the panel (not close it).
11278 workspace.update_in(cx, |workspace, window, cx| {
11279 workspace
11280 .right_dock()
11281 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11282 window.focus(&pane.read(cx).focus_handle(cx), cx);
11283 });
11284
11285 workspace.update_in(cx, |workspace, window, cx| {
11286 assert!(workspace.right_dock().read(cx).is_open());
11287 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11288 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11289 });
11290
11291 workspace.update_in(cx, |workspace, window, cx| {
11292 assert!(
11293 workspace.right_dock().read(cx).is_open(),
11294 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11295 );
11296 assert!(
11297 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11298 "Panel should be focused after toggling an open-but-unfocused panel"
11299 );
11300 });
11301
11302 // Now disable the setting and verify the original behavior: toggling
11303 // from a focused panel moves focus to center but leaves the dock open.
11304 cx.update_global(|store: &mut SettingsStore, cx| {
11305 store.update_user_settings(cx, |settings| {
11306 settings.workspace.close_panel_on_toggle = Some(false);
11307 });
11308 });
11309
11310 workspace.update_in(cx, |workspace, window, cx| {
11311 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11312 });
11313
11314 workspace.update_in(cx, |workspace, window, cx| {
11315 assert!(
11316 workspace.right_dock().read(cx).is_open(),
11317 "Dock should remain open when setting is disabled"
11318 );
11319 assert!(
11320 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11321 "Panel should not be focused after toggling with setting disabled"
11322 );
11323 });
11324 }
11325
11326 #[gpui::test]
11327 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11328 init_test(cx);
11329 let fs = FakeFs::new(cx.executor());
11330
11331 let project = Project::test(fs, [], cx).await;
11332 let (workspace, cx) =
11333 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11334
11335 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11336 workspace.active_pane().clone()
11337 });
11338
11339 // Add an item to the pane so it can be zoomed
11340 workspace.update_in(cx, |workspace, window, cx| {
11341 let item = cx.new(TestItem::new);
11342 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11343 });
11344
11345 // Initially not zoomed
11346 workspace.update_in(cx, |workspace, _window, cx| {
11347 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11348 assert!(
11349 workspace.zoomed.is_none(),
11350 "Workspace should track no zoomed pane"
11351 );
11352 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11353 });
11354
11355 // Zoom In
11356 pane.update_in(cx, |pane, window, cx| {
11357 pane.zoom_in(&crate::ZoomIn, window, cx);
11358 });
11359
11360 workspace.update_in(cx, |workspace, window, cx| {
11361 assert!(
11362 pane.read(cx).is_zoomed(),
11363 "Pane should be zoomed after ZoomIn"
11364 );
11365 assert!(
11366 workspace.zoomed.is_some(),
11367 "Workspace should track the zoomed pane"
11368 );
11369 assert!(
11370 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11371 "ZoomIn should focus the pane"
11372 );
11373 });
11374
11375 // Zoom In again is a no-op
11376 pane.update_in(cx, |pane, window, cx| {
11377 pane.zoom_in(&crate::ZoomIn, window, cx);
11378 });
11379
11380 workspace.update_in(cx, |workspace, window, cx| {
11381 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11382 assert!(
11383 workspace.zoomed.is_some(),
11384 "Workspace still tracks zoomed pane"
11385 );
11386 assert!(
11387 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11388 "Pane remains focused after repeated ZoomIn"
11389 );
11390 });
11391
11392 // Zoom Out
11393 pane.update_in(cx, |pane, window, cx| {
11394 pane.zoom_out(&crate::ZoomOut, window, cx);
11395 });
11396
11397 workspace.update_in(cx, |workspace, _window, cx| {
11398 assert!(
11399 !pane.read(cx).is_zoomed(),
11400 "Pane should unzoom after ZoomOut"
11401 );
11402 assert!(
11403 workspace.zoomed.is_none(),
11404 "Workspace clears zoom tracking after ZoomOut"
11405 );
11406 });
11407
11408 // Zoom Out again is a no-op
11409 pane.update_in(cx, |pane, window, cx| {
11410 pane.zoom_out(&crate::ZoomOut, window, cx);
11411 });
11412
11413 workspace.update_in(cx, |workspace, _window, cx| {
11414 assert!(
11415 !pane.read(cx).is_zoomed(),
11416 "Second ZoomOut keeps pane unzoomed"
11417 );
11418 assert!(
11419 workspace.zoomed.is_none(),
11420 "Workspace remains without zoomed pane"
11421 );
11422 });
11423 }
11424
11425 #[gpui::test]
11426 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11427 init_test(cx);
11428 let fs = FakeFs::new(cx.executor());
11429
11430 let project = Project::test(fs, [], cx).await;
11431 let (workspace, cx) =
11432 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11433 workspace.update_in(cx, |workspace, window, cx| {
11434 // Open two docks
11435 let left_dock = workspace.dock_at_position(DockPosition::Left);
11436 let right_dock = workspace.dock_at_position(DockPosition::Right);
11437
11438 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11439 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11440
11441 assert!(left_dock.read(cx).is_open());
11442 assert!(right_dock.read(cx).is_open());
11443 });
11444
11445 workspace.update_in(cx, |workspace, window, cx| {
11446 // Toggle all docks - should close both
11447 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11448
11449 let left_dock = workspace.dock_at_position(DockPosition::Left);
11450 let right_dock = workspace.dock_at_position(DockPosition::Right);
11451 assert!(!left_dock.read(cx).is_open());
11452 assert!(!right_dock.read(cx).is_open());
11453 });
11454
11455 workspace.update_in(cx, |workspace, window, cx| {
11456 // Toggle again - should reopen both
11457 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11458
11459 let left_dock = workspace.dock_at_position(DockPosition::Left);
11460 let right_dock = workspace.dock_at_position(DockPosition::Right);
11461 assert!(left_dock.read(cx).is_open());
11462 assert!(right_dock.read(cx).is_open());
11463 });
11464 }
11465
11466 #[gpui::test]
11467 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11468 init_test(cx);
11469 let fs = FakeFs::new(cx.executor());
11470
11471 let project = Project::test(fs, [], cx).await;
11472 let (workspace, cx) =
11473 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11474 workspace.update_in(cx, |workspace, window, cx| {
11475 // Open two docks
11476 let left_dock = workspace.dock_at_position(DockPosition::Left);
11477 let right_dock = workspace.dock_at_position(DockPosition::Right);
11478
11479 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11480 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11481
11482 assert!(left_dock.read(cx).is_open());
11483 assert!(right_dock.read(cx).is_open());
11484 });
11485
11486 workspace.update_in(cx, |workspace, window, cx| {
11487 // Close them manually
11488 workspace.toggle_dock(DockPosition::Left, window, cx);
11489 workspace.toggle_dock(DockPosition::Right, window, cx);
11490
11491 let left_dock = workspace.dock_at_position(DockPosition::Left);
11492 let right_dock = workspace.dock_at_position(DockPosition::Right);
11493 assert!(!left_dock.read(cx).is_open());
11494 assert!(!right_dock.read(cx).is_open());
11495 });
11496
11497 workspace.update_in(cx, |workspace, window, cx| {
11498 // Toggle all docks - only last closed (right dock) should reopen
11499 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11500
11501 let left_dock = workspace.dock_at_position(DockPosition::Left);
11502 let right_dock = workspace.dock_at_position(DockPosition::Right);
11503 assert!(!left_dock.read(cx).is_open());
11504 assert!(right_dock.read(cx).is_open());
11505 });
11506 }
11507
11508 #[gpui::test]
11509 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11510 init_test(cx);
11511 let fs = FakeFs::new(cx.executor());
11512 let project = Project::test(fs, [], cx).await;
11513 let (multi_workspace, cx) =
11514 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11515 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11516
11517 // Open two docks (left and right) with one panel each
11518 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11519 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11520 workspace.add_panel(left_panel.clone(), window, cx);
11521
11522 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11523 workspace.add_panel(right_panel.clone(), window, cx);
11524
11525 workspace.toggle_dock(DockPosition::Left, window, cx);
11526 workspace.toggle_dock(DockPosition::Right, window, cx);
11527
11528 // Verify initial state
11529 assert!(
11530 workspace.left_dock().read(cx).is_open(),
11531 "Left dock should be open"
11532 );
11533 assert_eq!(
11534 workspace
11535 .left_dock()
11536 .read(cx)
11537 .visible_panel()
11538 .unwrap()
11539 .panel_id(),
11540 left_panel.panel_id(),
11541 "Left panel should be visible in left dock"
11542 );
11543 assert!(
11544 workspace.right_dock().read(cx).is_open(),
11545 "Right dock should be open"
11546 );
11547 assert_eq!(
11548 workspace
11549 .right_dock()
11550 .read(cx)
11551 .visible_panel()
11552 .unwrap()
11553 .panel_id(),
11554 right_panel.panel_id(),
11555 "Right panel should be visible in right dock"
11556 );
11557 assert!(
11558 !workspace.bottom_dock().read(cx).is_open(),
11559 "Bottom dock should be closed"
11560 );
11561
11562 (left_panel, right_panel)
11563 });
11564
11565 // Focus the left panel and move it to the next position (bottom dock)
11566 workspace.update_in(cx, |workspace, window, cx| {
11567 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11568 assert!(
11569 left_panel.read(cx).focus_handle(cx).is_focused(window),
11570 "Left panel should be focused"
11571 );
11572 });
11573
11574 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11575
11576 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11577 workspace.update(cx, |workspace, cx| {
11578 assert!(
11579 !workspace.left_dock().read(cx).is_open(),
11580 "Left dock should be closed"
11581 );
11582 assert!(
11583 workspace.bottom_dock().read(cx).is_open(),
11584 "Bottom dock should now be open"
11585 );
11586 assert_eq!(
11587 left_panel.read(cx).position,
11588 DockPosition::Bottom,
11589 "Left panel should now be in the bottom dock"
11590 );
11591 assert_eq!(
11592 workspace
11593 .bottom_dock()
11594 .read(cx)
11595 .visible_panel()
11596 .unwrap()
11597 .panel_id(),
11598 left_panel.panel_id(),
11599 "Left panel should be the visible panel in the bottom dock"
11600 );
11601 });
11602
11603 // Toggle all docks off
11604 workspace.update_in(cx, |workspace, window, cx| {
11605 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11606 assert!(
11607 !workspace.left_dock().read(cx).is_open(),
11608 "Left dock should be closed"
11609 );
11610 assert!(
11611 !workspace.right_dock().read(cx).is_open(),
11612 "Right dock should be closed"
11613 );
11614 assert!(
11615 !workspace.bottom_dock().read(cx).is_open(),
11616 "Bottom dock should be closed"
11617 );
11618 });
11619
11620 // Toggle all docks back on and verify positions are restored
11621 workspace.update_in(cx, |workspace, window, cx| {
11622 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11623 assert!(
11624 !workspace.left_dock().read(cx).is_open(),
11625 "Left dock should remain closed"
11626 );
11627 assert!(
11628 workspace.right_dock().read(cx).is_open(),
11629 "Right dock should remain open"
11630 );
11631 assert!(
11632 workspace.bottom_dock().read(cx).is_open(),
11633 "Bottom dock should remain open"
11634 );
11635 assert_eq!(
11636 left_panel.read(cx).position,
11637 DockPosition::Bottom,
11638 "Left panel should remain in the bottom dock"
11639 );
11640 assert_eq!(
11641 right_panel.read(cx).position,
11642 DockPosition::Right,
11643 "Right panel should remain in the right dock"
11644 );
11645 assert_eq!(
11646 workspace
11647 .bottom_dock()
11648 .read(cx)
11649 .visible_panel()
11650 .unwrap()
11651 .panel_id(),
11652 left_panel.panel_id(),
11653 "Left panel should be the visible panel in the right dock"
11654 );
11655 });
11656 }
11657
11658 #[gpui::test]
11659 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11660 init_test(cx);
11661
11662 let fs = FakeFs::new(cx.executor());
11663
11664 let project = Project::test(fs, None, cx).await;
11665 let (workspace, cx) =
11666 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11667
11668 // Let's arrange the panes like this:
11669 //
11670 // +-----------------------+
11671 // | top |
11672 // +------+--------+-------+
11673 // | left | center | right |
11674 // +------+--------+-------+
11675 // | bottom |
11676 // +-----------------------+
11677
11678 let top_item = cx.new(|cx| {
11679 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11680 });
11681 let bottom_item = cx.new(|cx| {
11682 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11683 });
11684 let left_item = cx.new(|cx| {
11685 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11686 });
11687 let right_item = cx.new(|cx| {
11688 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11689 });
11690 let center_item = cx.new(|cx| {
11691 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11692 });
11693
11694 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11695 let top_pane_id = workspace.active_pane().entity_id();
11696 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11697 workspace.split_pane(
11698 workspace.active_pane().clone(),
11699 SplitDirection::Down,
11700 window,
11701 cx,
11702 );
11703 top_pane_id
11704 });
11705 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11706 let bottom_pane_id = workspace.active_pane().entity_id();
11707 workspace.add_item_to_active_pane(
11708 Box::new(bottom_item.clone()),
11709 None,
11710 false,
11711 window,
11712 cx,
11713 );
11714 workspace.split_pane(
11715 workspace.active_pane().clone(),
11716 SplitDirection::Up,
11717 window,
11718 cx,
11719 );
11720 bottom_pane_id
11721 });
11722 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11723 let left_pane_id = workspace.active_pane().entity_id();
11724 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11725 workspace.split_pane(
11726 workspace.active_pane().clone(),
11727 SplitDirection::Right,
11728 window,
11729 cx,
11730 );
11731 left_pane_id
11732 });
11733 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11734 let right_pane_id = workspace.active_pane().entity_id();
11735 workspace.add_item_to_active_pane(
11736 Box::new(right_item.clone()),
11737 None,
11738 false,
11739 window,
11740 cx,
11741 );
11742 workspace.split_pane(
11743 workspace.active_pane().clone(),
11744 SplitDirection::Left,
11745 window,
11746 cx,
11747 );
11748 right_pane_id
11749 });
11750 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11751 let center_pane_id = workspace.active_pane().entity_id();
11752 workspace.add_item_to_active_pane(
11753 Box::new(center_item.clone()),
11754 None,
11755 false,
11756 window,
11757 cx,
11758 );
11759 center_pane_id
11760 });
11761 cx.executor().run_until_parked();
11762
11763 workspace.update_in(cx, |workspace, window, cx| {
11764 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11765
11766 // Join into next from center pane into right
11767 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11768 });
11769
11770 workspace.update_in(cx, |workspace, window, cx| {
11771 let active_pane = workspace.active_pane();
11772 assert_eq!(right_pane_id, active_pane.entity_id());
11773 assert_eq!(2, active_pane.read(cx).items_len());
11774 let item_ids_in_pane =
11775 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11776 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11777 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11778
11779 // Join into next from right pane into bottom
11780 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11781 });
11782
11783 workspace.update_in(cx, |workspace, window, cx| {
11784 let active_pane = workspace.active_pane();
11785 assert_eq!(bottom_pane_id, active_pane.entity_id());
11786 assert_eq!(3, active_pane.read(cx).items_len());
11787 let item_ids_in_pane =
11788 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11789 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11790 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11791 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11792
11793 // Join into next from bottom pane into left
11794 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11795 });
11796
11797 workspace.update_in(cx, |workspace, window, cx| {
11798 let active_pane = workspace.active_pane();
11799 assert_eq!(left_pane_id, active_pane.entity_id());
11800 assert_eq!(4, active_pane.read(cx).items_len());
11801 let item_ids_in_pane =
11802 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11803 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11804 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11805 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11806 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11807
11808 // Join into next from left pane into top
11809 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11810 });
11811
11812 workspace.update_in(cx, |workspace, window, cx| {
11813 let active_pane = workspace.active_pane();
11814 assert_eq!(top_pane_id, active_pane.entity_id());
11815 assert_eq!(5, active_pane.read(cx).items_len());
11816 let item_ids_in_pane =
11817 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11818 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11819 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11820 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11821 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11822 assert!(item_ids_in_pane.contains(&top_item.item_id()));
11823
11824 // Single pane left: no-op
11825 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11826 });
11827
11828 workspace.update(cx, |workspace, _cx| {
11829 let active_pane = workspace.active_pane();
11830 assert_eq!(top_pane_id, active_pane.entity_id());
11831 });
11832 }
11833
11834 fn add_an_item_to_active_pane(
11835 cx: &mut VisualTestContext,
11836 workspace: &Entity<Workspace>,
11837 item_id: u64,
11838 ) -> Entity<TestItem> {
11839 let item = cx.new(|cx| {
11840 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11841 item_id,
11842 "item{item_id}.txt",
11843 cx,
11844 )])
11845 });
11846 workspace.update_in(cx, |workspace, window, cx| {
11847 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11848 });
11849 item
11850 }
11851
11852 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11853 workspace.update_in(cx, |workspace, window, cx| {
11854 workspace.split_pane(
11855 workspace.active_pane().clone(),
11856 SplitDirection::Right,
11857 window,
11858 cx,
11859 )
11860 })
11861 }
11862
11863 #[gpui::test]
11864 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11865 init_test(cx);
11866 let fs = FakeFs::new(cx.executor());
11867 let project = Project::test(fs, None, cx).await;
11868 let (workspace, cx) =
11869 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11870
11871 add_an_item_to_active_pane(cx, &workspace, 1);
11872 split_pane(cx, &workspace);
11873 add_an_item_to_active_pane(cx, &workspace, 2);
11874 split_pane(cx, &workspace); // empty pane
11875 split_pane(cx, &workspace);
11876 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11877
11878 cx.executor().run_until_parked();
11879
11880 workspace.update(cx, |workspace, cx| {
11881 let num_panes = workspace.panes().len();
11882 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11883 let active_item = workspace
11884 .active_pane()
11885 .read(cx)
11886 .active_item()
11887 .expect("item is in focus");
11888
11889 assert_eq!(num_panes, 4);
11890 assert_eq!(num_items_in_current_pane, 1);
11891 assert_eq!(active_item.item_id(), last_item.item_id());
11892 });
11893
11894 workspace.update_in(cx, |workspace, window, cx| {
11895 workspace.join_all_panes(window, cx);
11896 });
11897
11898 workspace.update(cx, |workspace, cx| {
11899 let num_panes = workspace.panes().len();
11900 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11901 let active_item = workspace
11902 .active_pane()
11903 .read(cx)
11904 .active_item()
11905 .expect("item is in focus");
11906
11907 assert_eq!(num_panes, 1);
11908 assert_eq!(num_items_in_current_pane, 3);
11909 assert_eq!(active_item.item_id(), last_item.item_id());
11910 });
11911 }
11912 struct TestModal(FocusHandle);
11913
11914 impl TestModal {
11915 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11916 Self(cx.focus_handle())
11917 }
11918 }
11919
11920 impl EventEmitter<DismissEvent> for TestModal {}
11921
11922 impl Focusable for TestModal {
11923 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11924 self.0.clone()
11925 }
11926 }
11927
11928 impl ModalView for TestModal {}
11929
11930 impl Render for TestModal {
11931 fn render(
11932 &mut self,
11933 _window: &mut Window,
11934 _cx: &mut Context<TestModal>,
11935 ) -> impl IntoElement {
11936 div().track_focus(&self.0)
11937 }
11938 }
11939
11940 #[gpui::test]
11941 async fn test_panels(cx: &mut gpui::TestAppContext) {
11942 init_test(cx);
11943 let fs = FakeFs::new(cx.executor());
11944
11945 let project = Project::test(fs, [], cx).await;
11946 let (multi_workspace, cx) =
11947 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11948 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11949
11950 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11951 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11952 workspace.add_panel(panel_1.clone(), window, cx);
11953 workspace.toggle_dock(DockPosition::Left, window, cx);
11954 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11955 workspace.add_panel(panel_2.clone(), window, cx);
11956 workspace.toggle_dock(DockPosition::Right, window, cx);
11957
11958 let left_dock = workspace.left_dock();
11959 assert_eq!(
11960 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11961 panel_1.panel_id()
11962 );
11963 assert_eq!(
11964 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11965 panel_1.size(window, cx)
11966 );
11967
11968 left_dock.update(cx, |left_dock, cx| {
11969 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11970 });
11971 assert_eq!(
11972 workspace
11973 .right_dock()
11974 .read(cx)
11975 .visible_panel()
11976 .unwrap()
11977 .panel_id(),
11978 panel_2.panel_id(),
11979 );
11980
11981 (panel_1, panel_2)
11982 });
11983
11984 // Move panel_1 to the right
11985 panel_1.update_in(cx, |panel_1, window, cx| {
11986 panel_1.set_position(DockPosition::Right, window, cx)
11987 });
11988
11989 workspace.update_in(cx, |workspace, window, cx| {
11990 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11991 // Since it was the only panel on the left, the left dock should now be closed.
11992 assert!(!workspace.left_dock().read(cx).is_open());
11993 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11994 let right_dock = workspace.right_dock();
11995 assert_eq!(
11996 right_dock.read(cx).visible_panel().unwrap().panel_id(),
11997 panel_1.panel_id()
11998 );
11999 assert_eq!(
12000 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
12001 px(1337.)
12002 );
12003
12004 // Now we move panel_2 to the left
12005 panel_2.set_position(DockPosition::Left, window, cx);
12006 });
12007
12008 workspace.update(cx, |workspace, cx| {
12009 // Since panel_2 was not visible on the right, we don't open the left dock.
12010 assert!(!workspace.left_dock().read(cx).is_open());
12011 // And the right dock is unaffected in its displaying of panel_1
12012 assert!(workspace.right_dock().read(cx).is_open());
12013 assert_eq!(
12014 workspace
12015 .right_dock()
12016 .read(cx)
12017 .visible_panel()
12018 .unwrap()
12019 .panel_id(),
12020 panel_1.panel_id(),
12021 );
12022 });
12023
12024 // Move panel_1 back to the left
12025 panel_1.update_in(cx, |panel_1, window, cx| {
12026 panel_1.set_position(DockPosition::Left, window, cx)
12027 });
12028
12029 workspace.update_in(cx, |workspace, window, cx| {
12030 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12031 let left_dock = workspace.left_dock();
12032 assert!(left_dock.read(cx).is_open());
12033 assert_eq!(
12034 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12035 panel_1.panel_id()
12036 );
12037 assert_eq!(
12038 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
12039 px(1337.)
12040 );
12041 // And the right dock should be closed as it no longer has any panels.
12042 assert!(!workspace.right_dock().read(cx).is_open());
12043
12044 // Now we move panel_1 to the bottom
12045 panel_1.set_position(DockPosition::Bottom, window, cx);
12046 });
12047
12048 workspace.update_in(cx, |workspace, window, cx| {
12049 // Since panel_1 was visible on the left, we close the left dock.
12050 assert!(!workspace.left_dock().read(cx).is_open());
12051 // The bottom dock is sized based on the panel's default size,
12052 // since the panel orientation changed from vertical to horizontal.
12053 let bottom_dock = workspace.bottom_dock();
12054 assert_eq!(
12055 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
12056 panel_1.size(window, cx),
12057 );
12058 // Close bottom dock and move panel_1 back to the left.
12059 bottom_dock.update(cx, |bottom_dock, cx| {
12060 bottom_dock.set_open(false, window, cx)
12061 });
12062 panel_1.set_position(DockPosition::Left, window, cx);
12063 });
12064
12065 // Emit activated event on panel 1
12066 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12067
12068 // Now the left dock is open and panel_1 is active and focused.
12069 workspace.update_in(cx, |workspace, window, cx| {
12070 let left_dock = workspace.left_dock();
12071 assert!(left_dock.read(cx).is_open());
12072 assert_eq!(
12073 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12074 panel_1.panel_id(),
12075 );
12076 assert!(panel_1.focus_handle(cx).is_focused(window));
12077 });
12078
12079 // Emit closed event on panel 2, which is not active
12080 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12081
12082 // Wo don't close the left dock, because panel_2 wasn't the active panel
12083 workspace.update(cx, |workspace, cx| {
12084 let left_dock = workspace.left_dock();
12085 assert!(left_dock.read(cx).is_open());
12086 assert_eq!(
12087 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12088 panel_1.panel_id(),
12089 );
12090 });
12091
12092 // Emitting a ZoomIn event shows the panel as zoomed.
12093 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12094 workspace.read_with(cx, |workspace, _| {
12095 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12096 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12097 });
12098
12099 // Move panel to another dock while it is zoomed
12100 panel_1.update_in(cx, |panel, window, cx| {
12101 panel.set_position(DockPosition::Right, window, cx)
12102 });
12103 workspace.read_with(cx, |workspace, _| {
12104 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12105
12106 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12107 });
12108
12109 // This is a helper for getting a:
12110 // - valid focus on an element,
12111 // - that isn't a part of the panes and panels system of the Workspace,
12112 // - and doesn't trigger the 'on_focus_lost' API.
12113 let focus_other_view = {
12114 let workspace = workspace.clone();
12115 move |cx: &mut VisualTestContext| {
12116 workspace.update_in(cx, |workspace, window, cx| {
12117 if workspace.active_modal::<TestModal>(cx).is_some() {
12118 workspace.toggle_modal(window, cx, TestModal::new);
12119 workspace.toggle_modal(window, cx, TestModal::new);
12120 } else {
12121 workspace.toggle_modal(window, cx, TestModal::new);
12122 }
12123 })
12124 }
12125 };
12126
12127 // If focus is transferred to another view that's not a panel or another pane, we still show
12128 // the panel as zoomed.
12129 focus_other_view(cx);
12130 workspace.read_with(cx, |workspace, _| {
12131 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12132 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12133 });
12134
12135 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12136 workspace.update_in(cx, |_workspace, window, cx| {
12137 cx.focus_self(window);
12138 });
12139 workspace.read_with(cx, |workspace, _| {
12140 assert_eq!(workspace.zoomed, None);
12141 assert_eq!(workspace.zoomed_position, None);
12142 });
12143
12144 // If focus is transferred again to another view that's not a panel or a pane, we won't
12145 // show the panel as zoomed because it wasn't zoomed before.
12146 focus_other_view(cx);
12147 workspace.read_with(cx, |workspace, _| {
12148 assert_eq!(workspace.zoomed, None);
12149 assert_eq!(workspace.zoomed_position, None);
12150 });
12151
12152 // When the panel is activated, it is zoomed again.
12153 cx.dispatch_action(ToggleRightDock);
12154 workspace.read_with(cx, |workspace, _| {
12155 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12156 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12157 });
12158
12159 // Emitting a ZoomOut event unzooms the panel.
12160 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12161 workspace.read_with(cx, |workspace, _| {
12162 assert_eq!(workspace.zoomed, None);
12163 assert_eq!(workspace.zoomed_position, None);
12164 });
12165
12166 // Emit closed event on panel 1, which is active
12167 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12168
12169 // Now the left dock is closed, because panel_1 was the active panel
12170 workspace.update(cx, |workspace, cx| {
12171 let right_dock = workspace.right_dock();
12172 assert!(!right_dock.read(cx).is_open());
12173 });
12174 }
12175
12176 #[gpui::test]
12177 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12178 init_test(cx);
12179
12180 let fs = FakeFs::new(cx.background_executor.clone());
12181 let project = Project::test(fs, [], cx).await;
12182 let (workspace, cx) =
12183 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12184 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12185
12186 let dirty_regular_buffer = cx.new(|cx| {
12187 TestItem::new(cx)
12188 .with_dirty(true)
12189 .with_label("1.txt")
12190 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12191 });
12192 let dirty_regular_buffer_2 = cx.new(|cx| {
12193 TestItem::new(cx)
12194 .with_dirty(true)
12195 .with_label("2.txt")
12196 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12197 });
12198 let dirty_multi_buffer_with_both = cx.new(|cx| {
12199 TestItem::new(cx)
12200 .with_dirty(true)
12201 .with_buffer_kind(ItemBufferKind::Multibuffer)
12202 .with_label("Fake Project Search")
12203 .with_project_items(&[
12204 dirty_regular_buffer.read(cx).project_items[0].clone(),
12205 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12206 ])
12207 });
12208 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12209 workspace.update_in(cx, |workspace, window, cx| {
12210 workspace.add_item(
12211 pane.clone(),
12212 Box::new(dirty_regular_buffer.clone()),
12213 None,
12214 false,
12215 false,
12216 window,
12217 cx,
12218 );
12219 workspace.add_item(
12220 pane.clone(),
12221 Box::new(dirty_regular_buffer_2.clone()),
12222 None,
12223 false,
12224 false,
12225 window,
12226 cx,
12227 );
12228 workspace.add_item(
12229 pane.clone(),
12230 Box::new(dirty_multi_buffer_with_both.clone()),
12231 None,
12232 false,
12233 false,
12234 window,
12235 cx,
12236 );
12237 });
12238
12239 pane.update_in(cx, |pane, window, cx| {
12240 pane.activate_item(2, true, true, window, cx);
12241 assert_eq!(
12242 pane.active_item().unwrap().item_id(),
12243 multi_buffer_with_both_files_id,
12244 "Should select the multi buffer in the pane"
12245 );
12246 });
12247 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12248 pane.close_other_items(
12249 &CloseOtherItems {
12250 save_intent: Some(SaveIntent::Save),
12251 close_pinned: true,
12252 },
12253 None,
12254 window,
12255 cx,
12256 )
12257 });
12258 cx.background_executor.run_until_parked();
12259 assert!(!cx.has_pending_prompt());
12260 close_all_but_multi_buffer_task
12261 .await
12262 .expect("Closing all buffers but the multi buffer failed");
12263 pane.update(cx, |pane, cx| {
12264 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12265 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12266 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12267 assert_eq!(pane.items_len(), 1);
12268 assert_eq!(
12269 pane.active_item().unwrap().item_id(),
12270 multi_buffer_with_both_files_id,
12271 "Should have only the multi buffer left in the pane"
12272 );
12273 assert!(
12274 dirty_multi_buffer_with_both.read(cx).is_dirty,
12275 "The multi buffer containing the unsaved buffer should still be dirty"
12276 );
12277 });
12278
12279 dirty_regular_buffer.update(cx, |buffer, cx| {
12280 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12281 });
12282
12283 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12284 pane.close_active_item(
12285 &CloseActiveItem {
12286 save_intent: Some(SaveIntent::Close),
12287 close_pinned: false,
12288 },
12289 window,
12290 cx,
12291 )
12292 });
12293 cx.background_executor.run_until_parked();
12294 assert!(
12295 cx.has_pending_prompt(),
12296 "Dirty multi buffer should prompt a save dialog"
12297 );
12298 cx.simulate_prompt_answer("Save");
12299 cx.background_executor.run_until_parked();
12300 close_multi_buffer_task
12301 .await
12302 .expect("Closing the multi buffer failed");
12303 pane.update(cx, |pane, cx| {
12304 assert_eq!(
12305 dirty_multi_buffer_with_both.read(cx).save_count,
12306 1,
12307 "Multi buffer item should get be saved"
12308 );
12309 // Test impl does not save inner items, so we do not assert them
12310 assert_eq!(
12311 pane.items_len(),
12312 0,
12313 "No more items should be left in the pane"
12314 );
12315 assert!(pane.active_item().is_none());
12316 });
12317 }
12318
12319 #[gpui::test]
12320 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
12321 cx: &mut TestAppContext,
12322 ) {
12323 init_test(cx);
12324
12325 let fs = FakeFs::new(cx.background_executor.clone());
12326 let project = Project::test(fs, [], cx).await;
12327 let (workspace, cx) =
12328 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12329 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12330
12331 let dirty_regular_buffer = cx.new(|cx| {
12332 TestItem::new(cx)
12333 .with_dirty(true)
12334 .with_label("1.txt")
12335 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12336 });
12337 let dirty_regular_buffer_2 = cx.new(|cx| {
12338 TestItem::new(cx)
12339 .with_dirty(true)
12340 .with_label("2.txt")
12341 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12342 });
12343 let clear_regular_buffer = cx.new(|cx| {
12344 TestItem::new(cx)
12345 .with_label("3.txt")
12346 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12347 });
12348
12349 let dirty_multi_buffer_with_both = cx.new(|cx| {
12350 TestItem::new(cx)
12351 .with_dirty(true)
12352 .with_buffer_kind(ItemBufferKind::Multibuffer)
12353 .with_label("Fake Project Search")
12354 .with_project_items(&[
12355 dirty_regular_buffer.read(cx).project_items[0].clone(),
12356 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12357 clear_regular_buffer.read(cx).project_items[0].clone(),
12358 ])
12359 });
12360 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12361 workspace.update_in(cx, |workspace, window, cx| {
12362 workspace.add_item(
12363 pane.clone(),
12364 Box::new(dirty_regular_buffer.clone()),
12365 None,
12366 false,
12367 false,
12368 window,
12369 cx,
12370 );
12371 workspace.add_item(
12372 pane.clone(),
12373 Box::new(dirty_multi_buffer_with_both.clone()),
12374 None,
12375 false,
12376 false,
12377 window,
12378 cx,
12379 );
12380 });
12381
12382 pane.update_in(cx, |pane, window, cx| {
12383 pane.activate_item(1, true, true, window, cx);
12384 assert_eq!(
12385 pane.active_item().unwrap().item_id(),
12386 multi_buffer_with_both_files_id,
12387 "Should select the multi buffer in the pane"
12388 );
12389 });
12390 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12391 pane.close_active_item(
12392 &CloseActiveItem {
12393 save_intent: None,
12394 close_pinned: false,
12395 },
12396 window,
12397 cx,
12398 )
12399 });
12400 cx.background_executor.run_until_parked();
12401 assert!(
12402 cx.has_pending_prompt(),
12403 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
12404 );
12405 }
12406
12407 /// Tests that when `close_on_file_delete` is enabled, files are automatically
12408 /// closed when they are deleted from disk.
12409 #[gpui::test]
12410 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
12411 init_test(cx);
12412
12413 // Enable the close_on_disk_deletion setting
12414 cx.update_global(|store: &mut SettingsStore, cx| {
12415 store.update_user_settings(cx, |settings| {
12416 settings.workspace.close_on_file_delete = Some(true);
12417 });
12418 });
12419
12420 let fs = FakeFs::new(cx.background_executor.clone());
12421 let project = Project::test(fs, [], cx).await;
12422 let (workspace, cx) =
12423 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12424 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12425
12426 // Create a test item that simulates a file
12427 let item = cx.new(|cx| {
12428 TestItem::new(cx)
12429 .with_label("test.txt")
12430 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12431 });
12432
12433 // Add item to workspace
12434 workspace.update_in(cx, |workspace, window, cx| {
12435 workspace.add_item(
12436 pane.clone(),
12437 Box::new(item.clone()),
12438 None,
12439 false,
12440 false,
12441 window,
12442 cx,
12443 );
12444 });
12445
12446 // Verify the item is in the pane
12447 pane.read_with(cx, |pane, _| {
12448 assert_eq!(pane.items().count(), 1);
12449 });
12450
12451 // Simulate file deletion by setting the item's deleted state
12452 item.update(cx, |item, _| {
12453 item.set_has_deleted_file(true);
12454 });
12455
12456 // Emit UpdateTab event to trigger the close behavior
12457 cx.run_until_parked();
12458 item.update(cx, |_, cx| {
12459 cx.emit(ItemEvent::UpdateTab);
12460 });
12461
12462 // Allow the close operation to complete
12463 cx.run_until_parked();
12464
12465 // Verify the item was automatically closed
12466 pane.read_with(cx, |pane, _| {
12467 assert_eq!(
12468 pane.items().count(),
12469 0,
12470 "Item should be automatically closed when file is deleted"
12471 );
12472 });
12473 }
12474
12475 /// Tests that when `close_on_file_delete` is disabled (default), files remain
12476 /// open with a strikethrough when they are deleted from disk.
12477 #[gpui::test]
12478 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12479 init_test(cx);
12480
12481 // Ensure close_on_disk_deletion is disabled (default)
12482 cx.update_global(|store: &mut SettingsStore, cx| {
12483 store.update_user_settings(cx, |settings| {
12484 settings.workspace.close_on_file_delete = Some(false);
12485 });
12486 });
12487
12488 let fs = FakeFs::new(cx.background_executor.clone());
12489 let project = Project::test(fs, [], cx).await;
12490 let (workspace, cx) =
12491 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12492 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12493
12494 // Create a test item that simulates a file
12495 let item = cx.new(|cx| {
12496 TestItem::new(cx)
12497 .with_label("test.txt")
12498 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12499 });
12500
12501 // Add item to workspace
12502 workspace.update_in(cx, |workspace, window, cx| {
12503 workspace.add_item(
12504 pane.clone(),
12505 Box::new(item.clone()),
12506 None,
12507 false,
12508 false,
12509 window,
12510 cx,
12511 );
12512 });
12513
12514 // Verify the item is in the pane
12515 pane.read_with(cx, |pane, _| {
12516 assert_eq!(pane.items().count(), 1);
12517 });
12518
12519 // Simulate file deletion
12520 item.update(cx, |item, _| {
12521 item.set_has_deleted_file(true);
12522 });
12523
12524 // Emit UpdateTab event
12525 cx.run_until_parked();
12526 item.update(cx, |_, cx| {
12527 cx.emit(ItemEvent::UpdateTab);
12528 });
12529
12530 // Allow any potential close operation to complete
12531 cx.run_until_parked();
12532
12533 // Verify the item remains open (with strikethrough)
12534 pane.read_with(cx, |pane, _| {
12535 assert_eq!(
12536 pane.items().count(),
12537 1,
12538 "Item should remain open when close_on_disk_deletion is disabled"
12539 );
12540 });
12541
12542 // Verify the item shows as deleted
12543 item.read_with(cx, |item, _| {
12544 assert!(
12545 item.has_deleted_file,
12546 "Item should be marked as having deleted file"
12547 );
12548 });
12549 }
12550
12551 /// Tests that dirty files are not automatically closed when deleted from disk,
12552 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12553 /// unsaved changes without being prompted.
12554 #[gpui::test]
12555 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12556 init_test(cx);
12557
12558 // Enable the close_on_file_delete setting
12559 cx.update_global(|store: &mut SettingsStore, cx| {
12560 store.update_user_settings(cx, |settings| {
12561 settings.workspace.close_on_file_delete = Some(true);
12562 });
12563 });
12564
12565 let fs = FakeFs::new(cx.background_executor.clone());
12566 let project = Project::test(fs, [], cx).await;
12567 let (workspace, cx) =
12568 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12569 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12570
12571 // Create a dirty test item
12572 let item = cx.new(|cx| {
12573 TestItem::new(cx)
12574 .with_dirty(true)
12575 .with_label("test.txt")
12576 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12577 });
12578
12579 // Add item to workspace
12580 workspace.update_in(cx, |workspace, window, cx| {
12581 workspace.add_item(
12582 pane.clone(),
12583 Box::new(item.clone()),
12584 None,
12585 false,
12586 false,
12587 window,
12588 cx,
12589 );
12590 });
12591
12592 // Simulate file deletion
12593 item.update(cx, |item, _| {
12594 item.set_has_deleted_file(true);
12595 });
12596
12597 // Emit UpdateTab event to trigger the close behavior
12598 cx.run_until_parked();
12599 item.update(cx, |_, cx| {
12600 cx.emit(ItemEvent::UpdateTab);
12601 });
12602
12603 // Allow any potential close operation to complete
12604 cx.run_until_parked();
12605
12606 // Verify the item remains open (dirty files are not auto-closed)
12607 pane.read_with(cx, |pane, _| {
12608 assert_eq!(
12609 pane.items().count(),
12610 1,
12611 "Dirty items should not be automatically closed even when file is deleted"
12612 );
12613 });
12614
12615 // Verify the item is marked as deleted and still dirty
12616 item.read_with(cx, |item, _| {
12617 assert!(
12618 item.has_deleted_file,
12619 "Item should be marked as having deleted file"
12620 );
12621 assert!(item.is_dirty, "Item should still be dirty");
12622 });
12623 }
12624
12625 /// Tests that navigation history is cleaned up when files are auto-closed
12626 /// due to deletion from disk.
12627 #[gpui::test]
12628 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12629 init_test(cx);
12630
12631 // Enable the close_on_file_delete setting
12632 cx.update_global(|store: &mut SettingsStore, cx| {
12633 store.update_user_settings(cx, |settings| {
12634 settings.workspace.close_on_file_delete = Some(true);
12635 });
12636 });
12637
12638 let fs = FakeFs::new(cx.background_executor.clone());
12639 let project = Project::test(fs, [], cx).await;
12640 let (workspace, cx) =
12641 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12642 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12643
12644 // Create test items
12645 let item1 = cx.new(|cx| {
12646 TestItem::new(cx)
12647 .with_label("test1.txt")
12648 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12649 });
12650 let item1_id = item1.item_id();
12651
12652 let item2 = cx.new(|cx| {
12653 TestItem::new(cx)
12654 .with_label("test2.txt")
12655 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12656 });
12657
12658 // Add items to workspace
12659 workspace.update_in(cx, |workspace, window, cx| {
12660 workspace.add_item(
12661 pane.clone(),
12662 Box::new(item1.clone()),
12663 None,
12664 false,
12665 false,
12666 window,
12667 cx,
12668 );
12669 workspace.add_item(
12670 pane.clone(),
12671 Box::new(item2.clone()),
12672 None,
12673 false,
12674 false,
12675 window,
12676 cx,
12677 );
12678 });
12679
12680 // Activate item1 to ensure it gets navigation entries
12681 pane.update_in(cx, |pane, window, cx| {
12682 pane.activate_item(0, true, true, window, cx);
12683 });
12684
12685 // Switch to item2 and back to create navigation history
12686 pane.update_in(cx, |pane, window, cx| {
12687 pane.activate_item(1, true, true, window, cx);
12688 });
12689 cx.run_until_parked();
12690
12691 pane.update_in(cx, |pane, window, cx| {
12692 pane.activate_item(0, true, true, window, cx);
12693 });
12694 cx.run_until_parked();
12695
12696 // Simulate file deletion for item1
12697 item1.update(cx, |item, _| {
12698 item.set_has_deleted_file(true);
12699 });
12700
12701 // Emit UpdateTab event to trigger the close behavior
12702 item1.update(cx, |_, cx| {
12703 cx.emit(ItemEvent::UpdateTab);
12704 });
12705 cx.run_until_parked();
12706
12707 // Verify item1 was closed
12708 pane.read_with(cx, |pane, _| {
12709 assert_eq!(
12710 pane.items().count(),
12711 1,
12712 "Should have 1 item remaining after auto-close"
12713 );
12714 });
12715
12716 // Check navigation history after close
12717 let has_item = pane.read_with(cx, |pane, cx| {
12718 let mut has_item = false;
12719 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12720 if entry.item.id() == item1_id {
12721 has_item = true;
12722 }
12723 });
12724 has_item
12725 });
12726
12727 assert!(
12728 !has_item,
12729 "Navigation history should not contain closed item entries"
12730 );
12731 }
12732
12733 #[gpui::test]
12734 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12735 cx: &mut TestAppContext,
12736 ) {
12737 init_test(cx);
12738
12739 let fs = FakeFs::new(cx.background_executor.clone());
12740 let project = Project::test(fs, [], cx).await;
12741 let (workspace, cx) =
12742 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12743 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12744
12745 let dirty_regular_buffer = cx.new(|cx| {
12746 TestItem::new(cx)
12747 .with_dirty(true)
12748 .with_label("1.txt")
12749 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12750 });
12751 let dirty_regular_buffer_2 = cx.new(|cx| {
12752 TestItem::new(cx)
12753 .with_dirty(true)
12754 .with_label("2.txt")
12755 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12756 });
12757 let clear_regular_buffer = cx.new(|cx| {
12758 TestItem::new(cx)
12759 .with_label("3.txt")
12760 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12761 });
12762
12763 let dirty_multi_buffer = cx.new(|cx| {
12764 TestItem::new(cx)
12765 .with_dirty(true)
12766 .with_buffer_kind(ItemBufferKind::Multibuffer)
12767 .with_label("Fake Project Search")
12768 .with_project_items(&[
12769 dirty_regular_buffer.read(cx).project_items[0].clone(),
12770 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12771 clear_regular_buffer.read(cx).project_items[0].clone(),
12772 ])
12773 });
12774 workspace.update_in(cx, |workspace, window, cx| {
12775 workspace.add_item(
12776 pane.clone(),
12777 Box::new(dirty_regular_buffer.clone()),
12778 None,
12779 false,
12780 false,
12781 window,
12782 cx,
12783 );
12784 workspace.add_item(
12785 pane.clone(),
12786 Box::new(dirty_regular_buffer_2.clone()),
12787 None,
12788 false,
12789 false,
12790 window,
12791 cx,
12792 );
12793 workspace.add_item(
12794 pane.clone(),
12795 Box::new(dirty_multi_buffer.clone()),
12796 None,
12797 false,
12798 false,
12799 window,
12800 cx,
12801 );
12802 });
12803
12804 pane.update_in(cx, |pane, window, cx| {
12805 pane.activate_item(2, true, true, window, cx);
12806 assert_eq!(
12807 pane.active_item().unwrap().item_id(),
12808 dirty_multi_buffer.item_id(),
12809 "Should select the multi buffer in the pane"
12810 );
12811 });
12812 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12813 pane.close_active_item(
12814 &CloseActiveItem {
12815 save_intent: None,
12816 close_pinned: false,
12817 },
12818 window,
12819 cx,
12820 )
12821 });
12822 cx.background_executor.run_until_parked();
12823 assert!(
12824 !cx.has_pending_prompt(),
12825 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12826 );
12827 close_multi_buffer_task
12828 .await
12829 .expect("Closing multi buffer failed");
12830 pane.update(cx, |pane, cx| {
12831 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12832 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12833 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12834 assert_eq!(
12835 pane.items()
12836 .map(|item| item.item_id())
12837 .sorted()
12838 .collect::<Vec<_>>(),
12839 vec![
12840 dirty_regular_buffer.item_id(),
12841 dirty_regular_buffer_2.item_id(),
12842 ],
12843 "Should have no multi buffer left in the pane"
12844 );
12845 assert!(dirty_regular_buffer.read(cx).is_dirty);
12846 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12847 });
12848 }
12849
12850 #[gpui::test]
12851 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12852 init_test(cx);
12853 let fs = FakeFs::new(cx.executor());
12854 let project = Project::test(fs, [], cx).await;
12855 let (multi_workspace, cx) =
12856 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12857 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12858
12859 // Add a new panel to the right dock, opening the dock and setting the
12860 // focus to the new panel.
12861 let panel = workspace.update_in(cx, |workspace, window, cx| {
12862 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12863 workspace.add_panel(panel.clone(), window, cx);
12864
12865 workspace
12866 .right_dock()
12867 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12868
12869 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12870
12871 panel
12872 });
12873
12874 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12875 // panel to the next valid position which, in this case, is the left
12876 // dock.
12877 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12878 workspace.update(cx, |workspace, cx| {
12879 assert!(workspace.left_dock().read(cx).is_open());
12880 assert_eq!(panel.read(cx).position, DockPosition::Left);
12881 });
12882
12883 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12884 // panel to the next valid position which, in this case, is the bottom
12885 // dock.
12886 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12887 workspace.update(cx, |workspace, cx| {
12888 assert!(workspace.bottom_dock().read(cx).is_open());
12889 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12890 });
12891
12892 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12893 // around moving the panel to its initial position, the right dock.
12894 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12895 workspace.update(cx, |workspace, cx| {
12896 assert!(workspace.right_dock().read(cx).is_open());
12897 assert_eq!(panel.read(cx).position, DockPosition::Right);
12898 });
12899
12900 // Remove focus from the panel, ensuring that, if the panel is not
12901 // focused, the `MoveFocusedPanelToNextPosition` action does not update
12902 // the panel's position, so the panel is still in the right dock.
12903 workspace.update_in(cx, |workspace, window, cx| {
12904 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12905 });
12906
12907 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12908 workspace.update(cx, |workspace, cx| {
12909 assert!(workspace.right_dock().read(cx).is_open());
12910 assert_eq!(panel.read(cx).position, DockPosition::Right);
12911 });
12912 }
12913
12914 #[gpui::test]
12915 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12916 init_test(cx);
12917
12918 let fs = FakeFs::new(cx.executor());
12919 let project = Project::test(fs, [], cx).await;
12920 let (workspace, cx) =
12921 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12922
12923 let item_1 = cx.new(|cx| {
12924 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12925 });
12926 workspace.update_in(cx, |workspace, window, cx| {
12927 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12928 workspace.move_item_to_pane_in_direction(
12929 &MoveItemToPaneInDirection {
12930 direction: SplitDirection::Right,
12931 focus: true,
12932 clone: false,
12933 },
12934 window,
12935 cx,
12936 );
12937 workspace.move_item_to_pane_at_index(
12938 &MoveItemToPane {
12939 destination: 3,
12940 focus: true,
12941 clone: false,
12942 },
12943 window,
12944 cx,
12945 );
12946
12947 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12948 assert_eq!(
12949 pane_items_paths(&workspace.active_pane, cx),
12950 vec!["first.txt".to_string()],
12951 "Single item was not moved anywhere"
12952 );
12953 });
12954
12955 let item_2 = cx.new(|cx| {
12956 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12957 });
12958 workspace.update_in(cx, |workspace, window, cx| {
12959 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12960 assert_eq!(
12961 pane_items_paths(&workspace.panes[0], cx),
12962 vec!["first.txt".to_string(), "second.txt".to_string()],
12963 );
12964 workspace.move_item_to_pane_in_direction(
12965 &MoveItemToPaneInDirection {
12966 direction: SplitDirection::Right,
12967 focus: true,
12968 clone: false,
12969 },
12970 window,
12971 cx,
12972 );
12973
12974 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12975 assert_eq!(
12976 pane_items_paths(&workspace.panes[0], cx),
12977 vec!["first.txt".to_string()],
12978 "After moving, one item should be left in the original pane"
12979 );
12980 assert_eq!(
12981 pane_items_paths(&workspace.panes[1], cx),
12982 vec!["second.txt".to_string()],
12983 "New item should have been moved to the new pane"
12984 );
12985 });
12986
12987 let item_3 = cx.new(|cx| {
12988 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12989 });
12990 workspace.update_in(cx, |workspace, window, cx| {
12991 let original_pane = workspace.panes[0].clone();
12992 workspace.set_active_pane(&original_pane, window, cx);
12993 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12994 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12995 assert_eq!(
12996 pane_items_paths(&workspace.active_pane, cx),
12997 vec!["first.txt".to_string(), "third.txt".to_string()],
12998 "New pane should be ready to move one item out"
12999 );
13000
13001 workspace.move_item_to_pane_at_index(
13002 &MoveItemToPane {
13003 destination: 3,
13004 focus: true,
13005 clone: false,
13006 },
13007 window,
13008 cx,
13009 );
13010 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13011 assert_eq!(
13012 pane_items_paths(&workspace.active_pane, cx),
13013 vec!["first.txt".to_string()],
13014 "After moving, one item should be left in the original pane"
13015 );
13016 assert_eq!(
13017 pane_items_paths(&workspace.panes[1], cx),
13018 vec!["second.txt".to_string()],
13019 "Previously created pane should be unchanged"
13020 );
13021 assert_eq!(
13022 pane_items_paths(&workspace.panes[2], cx),
13023 vec!["third.txt".to_string()],
13024 "New item should have been moved to the new pane"
13025 );
13026 });
13027 }
13028
13029 #[gpui::test]
13030 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13031 init_test(cx);
13032
13033 let fs = FakeFs::new(cx.executor());
13034 let project = Project::test(fs, [], cx).await;
13035 let (workspace, cx) =
13036 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13037
13038 let item_1 = cx.new(|cx| {
13039 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13040 });
13041 workspace.update_in(cx, |workspace, window, cx| {
13042 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13043 workspace.move_item_to_pane_in_direction(
13044 &MoveItemToPaneInDirection {
13045 direction: SplitDirection::Right,
13046 focus: true,
13047 clone: true,
13048 },
13049 window,
13050 cx,
13051 );
13052 });
13053 cx.run_until_parked();
13054 workspace.update_in(cx, |workspace, window, cx| {
13055 workspace.move_item_to_pane_at_index(
13056 &MoveItemToPane {
13057 destination: 3,
13058 focus: true,
13059 clone: true,
13060 },
13061 window,
13062 cx,
13063 );
13064 });
13065 cx.run_until_parked();
13066
13067 workspace.update(cx, |workspace, cx| {
13068 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13069 for pane in workspace.panes() {
13070 assert_eq!(
13071 pane_items_paths(pane, cx),
13072 vec!["first.txt".to_string()],
13073 "Single item exists in all panes"
13074 );
13075 }
13076 });
13077
13078 // verify that the active pane has been updated after waiting for the
13079 // pane focus event to fire and resolve
13080 workspace.read_with(cx, |workspace, _app| {
13081 assert_eq!(
13082 workspace.active_pane(),
13083 &workspace.panes[2],
13084 "The third pane should be the active one: {:?}",
13085 workspace.panes
13086 );
13087 })
13088 }
13089
13090 #[gpui::test]
13091 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13092 init_test(cx);
13093
13094 let fs = FakeFs::new(cx.executor());
13095 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13096
13097 let project = Project::test(fs, ["root".as_ref()], cx).await;
13098 let (workspace, cx) =
13099 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13100
13101 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13102 // Add item to pane A with project path
13103 let item_a = cx.new(|cx| {
13104 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13105 });
13106 workspace.update_in(cx, |workspace, window, cx| {
13107 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13108 });
13109
13110 // Split to create pane B
13111 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13112 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13113 });
13114
13115 // Add item with SAME project path to pane B, and pin it
13116 let item_b = cx.new(|cx| {
13117 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13118 });
13119 pane_b.update_in(cx, |pane, window, cx| {
13120 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13121 pane.set_pinned_count(1);
13122 });
13123
13124 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13125 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13126
13127 // close_pinned: false should only close the unpinned copy
13128 workspace.update_in(cx, |workspace, window, cx| {
13129 workspace.close_item_in_all_panes(
13130 &CloseItemInAllPanes {
13131 save_intent: Some(SaveIntent::Close),
13132 close_pinned: false,
13133 },
13134 window,
13135 cx,
13136 )
13137 });
13138 cx.executor().run_until_parked();
13139
13140 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13141 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13142 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13143 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13144
13145 // Split again, seeing as closing the previous item also closed its
13146 // pane, so only pane remains, which does not allow us to properly test
13147 // that both items close when `close_pinned: true`.
13148 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13149 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13150 });
13151
13152 // Add an item with the same project path to pane C so that
13153 // close_item_in_all_panes can determine what to close across all panes
13154 // (it reads the active item from the active pane, and split_pane
13155 // creates an empty pane).
13156 let item_c = cx.new(|cx| {
13157 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13158 });
13159 pane_c.update_in(cx, |pane, window, cx| {
13160 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13161 });
13162
13163 // close_pinned: true should close the pinned copy too
13164 workspace.update_in(cx, |workspace, window, cx| {
13165 let panes_count = workspace.panes().len();
13166 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13167
13168 workspace.close_item_in_all_panes(
13169 &CloseItemInAllPanes {
13170 save_intent: Some(SaveIntent::Close),
13171 close_pinned: true,
13172 },
13173 window,
13174 cx,
13175 )
13176 });
13177 cx.executor().run_until_parked();
13178
13179 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13180 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13181 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13182 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13183 }
13184
13185 mod register_project_item_tests {
13186
13187 use super::*;
13188
13189 // View
13190 struct TestPngItemView {
13191 focus_handle: FocusHandle,
13192 }
13193 // Model
13194 struct TestPngItem {}
13195
13196 impl project::ProjectItem for TestPngItem {
13197 fn try_open(
13198 _project: &Entity<Project>,
13199 path: &ProjectPath,
13200 cx: &mut App,
13201 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13202 if path.path.extension().unwrap() == "png" {
13203 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13204 } else {
13205 None
13206 }
13207 }
13208
13209 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13210 None
13211 }
13212
13213 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13214 None
13215 }
13216
13217 fn is_dirty(&self) -> bool {
13218 false
13219 }
13220 }
13221
13222 impl Item for TestPngItemView {
13223 type Event = ();
13224 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13225 "".into()
13226 }
13227 }
13228 impl EventEmitter<()> for TestPngItemView {}
13229 impl Focusable for TestPngItemView {
13230 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13231 self.focus_handle.clone()
13232 }
13233 }
13234
13235 impl Render for TestPngItemView {
13236 fn render(
13237 &mut self,
13238 _window: &mut Window,
13239 _cx: &mut Context<Self>,
13240 ) -> impl IntoElement {
13241 Empty
13242 }
13243 }
13244
13245 impl ProjectItem for TestPngItemView {
13246 type Item = TestPngItem;
13247
13248 fn for_project_item(
13249 _project: Entity<Project>,
13250 _pane: Option<&Pane>,
13251 _item: Entity<Self::Item>,
13252 _: &mut Window,
13253 cx: &mut Context<Self>,
13254 ) -> Self
13255 where
13256 Self: Sized,
13257 {
13258 Self {
13259 focus_handle: cx.focus_handle(),
13260 }
13261 }
13262 }
13263
13264 // View
13265 struct TestIpynbItemView {
13266 focus_handle: FocusHandle,
13267 }
13268 // Model
13269 struct TestIpynbItem {}
13270
13271 impl project::ProjectItem for TestIpynbItem {
13272 fn try_open(
13273 _project: &Entity<Project>,
13274 path: &ProjectPath,
13275 cx: &mut App,
13276 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13277 if path.path.extension().unwrap() == "ipynb" {
13278 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13279 } else {
13280 None
13281 }
13282 }
13283
13284 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13285 None
13286 }
13287
13288 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13289 None
13290 }
13291
13292 fn is_dirty(&self) -> bool {
13293 false
13294 }
13295 }
13296
13297 impl Item for TestIpynbItemView {
13298 type Event = ();
13299 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13300 "".into()
13301 }
13302 }
13303 impl EventEmitter<()> for TestIpynbItemView {}
13304 impl Focusable for TestIpynbItemView {
13305 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13306 self.focus_handle.clone()
13307 }
13308 }
13309
13310 impl Render for TestIpynbItemView {
13311 fn render(
13312 &mut self,
13313 _window: &mut Window,
13314 _cx: &mut Context<Self>,
13315 ) -> impl IntoElement {
13316 Empty
13317 }
13318 }
13319
13320 impl ProjectItem for TestIpynbItemView {
13321 type Item = TestIpynbItem;
13322
13323 fn for_project_item(
13324 _project: Entity<Project>,
13325 _pane: Option<&Pane>,
13326 _item: Entity<Self::Item>,
13327 _: &mut Window,
13328 cx: &mut Context<Self>,
13329 ) -> Self
13330 where
13331 Self: Sized,
13332 {
13333 Self {
13334 focus_handle: cx.focus_handle(),
13335 }
13336 }
13337 }
13338
13339 struct TestAlternatePngItemView {
13340 focus_handle: FocusHandle,
13341 }
13342
13343 impl Item for TestAlternatePngItemView {
13344 type Event = ();
13345 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13346 "".into()
13347 }
13348 }
13349
13350 impl EventEmitter<()> for TestAlternatePngItemView {}
13351 impl Focusable for TestAlternatePngItemView {
13352 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13353 self.focus_handle.clone()
13354 }
13355 }
13356
13357 impl Render for TestAlternatePngItemView {
13358 fn render(
13359 &mut self,
13360 _window: &mut Window,
13361 _cx: &mut Context<Self>,
13362 ) -> impl IntoElement {
13363 Empty
13364 }
13365 }
13366
13367 impl ProjectItem for TestAlternatePngItemView {
13368 type Item = TestPngItem;
13369
13370 fn for_project_item(
13371 _project: Entity<Project>,
13372 _pane: Option<&Pane>,
13373 _item: Entity<Self::Item>,
13374 _: &mut Window,
13375 cx: &mut Context<Self>,
13376 ) -> Self
13377 where
13378 Self: Sized,
13379 {
13380 Self {
13381 focus_handle: cx.focus_handle(),
13382 }
13383 }
13384 }
13385
13386 #[gpui::test]
13387 async fn test_register_project_item(cx: &mut TestAppContext) {
13388 init_test(cx);
13389
13390 cx.update(|cx| {
13391 register_project_item::<TestPngItemView>(cx);
13392 register_project_item::<TestIpynbItemView>(cx);
13393 });
13394
13395 let fs = FakeFs::new(cx.executor());
13396 fs.insert_tree(
13397 "/root1",
13398 json!({
13399 "one.png": "BINARYDATAHERE",
13400 "two.ipynb": "{ totally a notebook }",
13401 "three.txt": "editing text, sure why not?"
13402 }),
13403 )
13404 .await;
13405
13406 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13407 let (workspace, cx) =
13408 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13409
13410 let worktree_id = project.update(cx, |project, cx| {
13411 project.worktrees(cx).next().unwrap().read(cx).id()
13412 });
13413
13414 let handle = workspace
13415 .update_in(cx, |workspace, window, cx| {
13416 let project_path = (worktree_id, rel_path("one.png"));
13417 workspace.open_path(project_path, None, true, window, cx)
13418 })
13419 .await
13420 .unwrap();
13421
13422 // Now we can check if the handle we got back errored or not
13423 assert_eq!(
13424 handle.to_any_view().entity_type(),
13425 TypeId::of::<TestPngItemView>()
13426 );
13427
13428 let handle = workspace
13429 .update_in(cx, |workspace, window, cx| {
13430 let project_path = (worktree_id, rel_path("two.ipynb"));
13431 workspace.open_path(project_path, None, true, window, cx)
13432 })
13433 .await
13434 .unwrap();
13435
13436 assert_eq!(
13437 handle.to_any_view().entity_type(),
13438 TypeId::of::<TestIpynbItemView>()
13439 );
13440
13441 let handle = workspace
13442 .update_in(cx, |workspace, window, cx| {
13443 let project_path = (worktree_id, rel_path("three.txt"));
13444 workspace.open_path(project_path, None, true, window, cx)
13445 })
13446 .await;
13447 assert!(handle.is_err());
13448 }
13449
13450 #[gpui::test]
13451 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
13452 init_test(cx);
13453
13454 cx.update(|cx| {
13455 register_project_item::<TestPngItemView>(cx);
13456 register_project_item::<TestAlternatePngItemView>(cx);
13457 });
13458
13459 let fs = FakeFs::new(cx.executor());
13460 fs.insert_tree(
13461 "/root1",
13462 json!({
13463 "one.png": "BINARYDATAHERE",
13464 "two.ipynb": "{ totally a notebook }",
13465 "three.txt": "editing text, sure why not?"
13466 }),
13467 )
13468 .await;
13469 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13470 let (workspace, cx) =
13471 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13472 let worktree_id = project.update(cx, |project, cx| {
13473 project.worktrees(cx).next().unwrap().read(cx).id()
13474 });
13475
13476 let handle = workspace
13477 .update_in(cx, |workspace, window, cx| {
13478 let project_path = (worktree_id, rel_path("one.png"));
13479 workspace.open_path(project_path, None, true, window, cx)
13480 })
13481 .await
13482 .unwrap();
13483
13484 // This _must_ be the second item registered
13485 assert_eq!(
13486 handle.to_any_view().entity_type(),
13487 TypeId::of::<TestAlternatePngItemView>()
13488 );
13489
13490 let handle = workspace
13491 .update_in(cx, |workspace, window, cx| {
13492 let project_path = (worktree_id, rel_path("three.txt"));
13493 workspace.open_path(project_path, None, true, window, cx)
13494 })
13495 .await;
13496 assert!(handle.is_err());
13497 }
13498 }
13499
13500 #[gpui::test]
13501 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13502 init_test(cx);
13503
13504 let fs = FakeFs::new(cx.executor());
13505 let project = Project::test(fs, [], cx).await;
13506 let (workspace, _cx) =
13507 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13508
13509 // Test with status bar shown (default)
13510 workspace.read_with(cx, |workspace, cx| {
13511 let visible = workspace.status_bar_visible(cx);
13512 assert!(visible, "Status bar should be visible by default");
13513 });
13514
13515 // Test with status bar hidden
13516 cx.update_global(|store: &mut SettingsStore, cx| {
13517 store.update_user_settings(cx, |settings| {
13518 settings.status_bar.get_or_insert_default().show = Some(false);
13519 });
13520 });
13521
13522 workspace.read_with(cx, |workspace, cx| {
13523 let visible = workspace.status_bar_visible(cx);
13524 assert!(!visible, "Status bar should be hidden when show is false");
13525 });
13526
13527 // Test with status bar shown explicitly
13528 cx.update_global(|store: &mut SettingsStore, cx| {
13529 store.update_user_settings(cx, |settings| {
13530 settings.status_bar.get_or_insert_default().show = Some(true);
13531 });
13532 });
13533
13534 workspace.read_with(cx, |workspace, cx| {
13535 let visible = workspace.status_bar_visible(cx);
13536 assert!(visible, "Status bar should be visible when show is true");
13537 });
13538 }
13539
13540 #[gpui::test]
13541 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13542 init_test(cx);
13543
13544 let fs = FakeFs::new(cx.executor());
13545 let project = Project::test(fs, [], cx).await;
13546 let (multi_workspace, cx) =
13547 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13548 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13549 let panel = workspace.update_in(cx, |workspace, window, cx| {
13550 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13551 workspace.add_panel(panel.clone(), window, cx);
13552
13553 workspace
13554 .right_dock()
13555 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13556
13557 panel
13558 });
13559
13560 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13561 let item_a = cx.new(TestItem::new);
13562 let item_b = cx.new(TestItem::new);
13563 let item_a_id = item_a.entity_id();
13564 let item_b_id = item_b.entity_id();
13565
13566 pane.update_in(cx, |pane, window, cx| {
13567 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13568 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13569 });
13570
13571 pane.read_with(cx, |pane, _| {
13572 assert_eq!(pane.items_len(), 2);
13573 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13574 });
13575
13576 workspace.update_in(cx, |workspace, window, cx| {
13577 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13578 });
13579
13580 workspace.update_in(cx, |_, window, cx| {
13581 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13582 });
13583
13584 // Assert that the `pane::CloseActiveItem` action is handled at the
13585 // workspace level when one of the dock panels is focused and, in that
13586 // case, the center pane's active item is closed but the focus is not
13587 // moved.
13588 cx.dispatch_action(pane::CloseActiveItem::default());
13589 cx.run_until_parked();
13590
13591 pane.read_with(cx, |pane, _| {
13592 assert_eq!(pane.items_len(), 1);
13593 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13594 });
13595
13596 workspace.update_in(cx, |workspace, window, cx| {
13597 assert!(workspace.right_dock().read(cx).is_open());
13598 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13599 });
13600 }
13601
13602 #[gpui::test]
13603 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13604 init_test(cx);
13605 let fs = FakeFs::new(cx.executor());
13606
13607 let project_a = Project::test(fs.clone(), [], cx).await;
13608 let project_b = Project::test(fs, [], cx).await;
13609
13610 let multi_workspace_handle =
13611 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13612 cx.run_until_parked();
13613
13614 let workspace_a = multi_workspace_handle
13615 .read_with(cx, |mw, _| mw.workspace().clone())
13616 .unwrap();
13617
13618 let _workspace_b = multi_workspace_handle
13619 .update(cx, |mw, window, cx| {
13620 mw.test_add_workspace(project_b, window, cx)
13621 })
13622 .unwrap();
13623
13624 // Switch to workspace A
13625 multi_workspace_handle
13626 .update(cx, |mw, window, cx| {
13627 mw.activate_index(0, window, cx);
13628 })
13629 .unwrap();
13630
13631 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13632
13633 // Add a panel to workspace A's right dock and open the dock
13634 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13635 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13636 workspace.add_panel(panel.clone(), window, cx);
13637 workspace
13638 .right_dock()
13639 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13640 panel
13641 });
13642
13643 // Focus the panel through the workspace (matching existing test pattern)
13644 workspace_a.update_in(cx, |workspace, window, cx| {
13645 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13646 });
13647
13648 // Zoom the panel
13649 panel.update_in(cx, |panel, window, cx| {
13650 panel.set_zoomed(true, window, cx);
13651 });
13652
13653 // Verify the panel is zoomed and the dock is open
13654 workspace_a.update_in(cx, |workspace, window, cx| {
13655 assert!(
13656 workspace.right_dock().read(cx).is_open(),
13657 "dock should be open before switch"
13658 );
13659 assert!(
13660 panel.is_zoomed(window, cx),
13661 "panel should be zoomed before switch"
13662 );
13663 assert!(
13664 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13665 "panel should be focused before switch"
13666 );
13667 });
13668
13669 // Switch to workspace B
13670 multi_workspace_handle
13671 .update(cx, |mw, window, cx| {
13672 mw.activate_index(1, window, cx);
13673 })
13674 .unwrap();
13675 cx.run_until_parked();
13676
13677 // Switch back to workspace A
13678 multi_workspace_handle
13679 .update(cx, |mw, window, cx| {
13680 mw.activate_index(0, window, cx);
13681 })
13682 .unwrap();
13683 cx.run_until_parked();
13684
13685 // Verify the panel is still zoomed and the dock is still open
13686 workspace_a.update_in(cx, |workspace, window, cx| {
13687 assert!(
13688 workspace.right_dock().read(cx).is_open(),
13689 "dock should still be open after switching back"
13690 );
13691 assert!(
13692 panel.is_zoomed(window, cx),
13693 "panel should still be zoomed after switching back"
13694 );
13695 });
13696 }
13697
13698 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13699 pane.read(cx)
13700 .items()
13701 .flat_map(|item| {
13702 item.project_paths(cx)
13703 .into_iter()
13704 .map(|path| path.path.display(PathStyle::local()).into_owned())
13705 })
13706 .collect()
13707 }
13708
13709 pub fn init_test(cx: &mut TestAppContext) {
13710 cx.update(|cx| {
13711 let settings_store = SettingsStore::test(cx);
13712 cx.set_global(settings_store);
13713 cx.set_global(db::AppDatabase::test_new());
13714 theme::init(theme::LoadThemes::JustBase, cx);
13715 });
13716 }
13717
13718 #[gpui::test]
13719 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
13720 use settings::{ThemeName, ThemeSelection};
13721 use theme::SystemAppearance;
13722 use zed_actions::theme::ToggleMode;
13723
13724 init_test(cx);
13725
13726 let fs = FakeFs::new(cx.executor());
13727 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
13728
13729 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
13730 .await;
13731
13732 // Build a test project and workspace view so the test can invoke
13733 // the workspace action handler the same way the UI would.
13734 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
13735 let (workspace, cx) =
13736 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13737
13738 // Seed the settings file with a plain static light theme so the
13739 // first toggle always starts from a known persisted state.
13740 workspace.update_in(cx, |_workspace, _window, cx| {
13741 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
13742 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
13743 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
13744 });
13745 });
13746 cx.executor().advance_clock(Duration::from_millis(200));
13747 cx.run_until_parked();
13748
13749 // Confirm the initial persisted settings contain the static theme
13750 // we just wrote before any toggling happens.
13751 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13752 assert!(settings_text.contains(r#""theme": "One Light""#));
13753
13754 // Toggle once. This should migrate the persisted theme settings
13755 // into light/dark slots and enable system mode.
13756 workspace.update_in(cx, |workspace, window, cx| {
13757 workspace.toggle_theme_mode(&ToggleMode, window, cx);
13758 });
13759 cx.executor().advance_clock(Duration::from_millis(200));
13760 cx.run_until_parked();
13761
13762 // 1. Static -> Dynamic
13763 // this assertion checks theme changed from static to dynamic.
13764 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13765 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
13766 assert_eq!(
13767 parsed["theme"],
13768 serde_json::json!({
13769 "mode": "system",
13770 "light": "One Light",
13771 "dark": "One Dark"
13772 })
13773 );
13774
13775 // 2. Toggle again, suppose it will change the mode to light
13776 workspace.update_in(cx, |workspace, window, cx| {
13777 workspace.toggle_theme_mode(&ToggleMode, window, cx);
13778 });
13779 cx.executor().advance_clock(Duration::from_millis(200));
13780 cx.run_until_parked();
13781
13782 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13783 assert!(settings_text.contains(r#""mode": "light""#));
13784 }
13785
13786 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13787 let item = TestProjectItem::new(id, path, cx);
13788 item.update(cx, |item, _| {
13789 item.is_dirty = true;
13790 });
13791 item
13792 }
13793
13794 #[gpui::test]
13795 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13796 cx: &mut gpui::TestAppContext,
13797 ) {
13798 init_test(cx);
13799 let fs = FakeFs::new(cx.executor());
13800
13801 let project = Project::test(fs, [], cx).await;
13802 let (workspace, cx) =
13803 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13804
13805 let panel = workspace.update_in(cx, |workspace, window, cx| {
13806 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13807 workspace.add_panel(panel.clone(), window, cx);
13808 workspace
13809 .right_dock()
13810 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13811 panel
13812 });
13813
13814 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13815 pane.update_in(cx, |pane, window, cx| {
13816 let item = cx.new(TestItem::new);
13817 pane.add_item(Box::new(item), true, true, None, window, cx);
13818 });
13819
13820 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13821 // mirrors the real-world flow and avoids side effects from directly
13822 // focusing the panel while the center pane is active.
13823 workspace.update_in(cx, |workspace, window, cx| {
13824 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13825 });
13826
13827 panel.update_in(cx, |panel, window, cx| {
13828 panel.set_zoomed(true, window, cx);
13829 });
13830
13831 workspace.update_in(cx, |workspace, window, cx| {
13832 assert!(workspace.right_dock().read(cx).is_open());
13833 assert!(panel.is_zoomed(window, cx));
13834 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13835 });
13836
13837 // Simulate a spurious pane::Event::Focus on the center pane while the
13838 // panel still has focus. This mirrors what happens during macOS window
13839 // activation: the center pane fires a focus event even though actual
13840 // focus remains on the dock panel.
13841 pane.update_in(cx, |_, _, cx| {
13842 cx.emit(pane::Event::Focus);
13843 });
13844
13845 // The dock must remain open because the panel had focus at the time the
13846 // event was processed. Before the fix, dock_to_preserve was None for
13847 // panels that don't implement pane(), causing the dock to close.
13848 workspace.update_in(cx, |workspace, window, cx| {
13849 assert!(
13850 workspace.right_dock().read(cx).is_open(),
13851 "Dock should stay open when its zoomed panel (without pane()) still has focus"
13852 );
13853 assert!(panel.is_zoomed(window, cx));
13854 });
13855 }
13856}