1pub mod dock;
2pub mod history_manager;
3pub mod invalid_item_view;
4pub mod item;
5mod modal_layer;
6mod multi_workspace;
7pub mod notifications;
8pub mod pane;
9pub mod pane_group;
10pub mod path_list {
11 pub use util::path_list::{PathList, SerializedPathList};
12}
13mod persistence;
14pub mod searchable;
15mod security_modal;
16pub mod shared_screen;
17use db::smol::future::yield_now;
18pub use shared_screen::SharedScreen;
19mod status_bar;
20pub mod tasks;
21mod theme_preview;
22mod toast_layer;
23mod toolbar;
24pub mod welcome;
25mod workspace_settings;
26
27pub use crate::notifications::NotificationFrame;
28pub use dock::Panel;
29pub use multi_workspace::{
30 CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace,
31 MultiWorkspaceEvent, NextWorkspace, PreviousWorkspace, Sidebar, SidebarHandle,
32 ToggleWorkspaceSidebar,
33};
34pub use path_list::{PathList, SerializedPathList};
35pub use toast_layer::{ToastAction, ToastLayer, ToastView};
36
37use anyhow::{Context as _, Result, anyhow};
38use client::{
39 ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
40 proto::{self, ErrorCode, PanelId, PeerId},
41};
42use collections::{HashMap, HashSet, hash_map};
43use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
44use fs::Fs;
45use futures::{
46 Future, FutureExt, StreamExt,
47 channel::{
48 mpsc::{self, UnboundedReceiver, UnboundedSender},
49 oneshot,
50 },
51 future::{Shared, try_join_all},
52};
53use gpui::{
54 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
55 Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
56 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
57 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
58 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
59 WindowOptions, actions, canvas, point, relative, size, transparent_black,
60};
61pub use history_manager::*;
62pub use item::{
63 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
64 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
65};
66use itertools::Itertools;
67use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
68pub use modal_layer::*;
69use node_runtime::NodeRuntime;
70use notifications::{
71 DetachAndPromptErr, Notifications, dismiss_app_notification,
72 simple_message_notification::MessageNotification,
73};
74pub use pane::*;
75pub use pane_group::{
76 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
77 SplitDirection,
78};
79use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
80pub use persistence::{
81 WorkspaceDb, delete_unloaded_items,
82 model::{
83 DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
84 SessionWorkspace,
85 },
86 read_serialized_multi_workspaces, resolve_worktree_workspaces,
87};
88use postage::stream::Stream;
89use project::{
90 DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
91 WorktreeSettings,
92 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
93 project_settings::ProjectSettings,
94 toolchain_store::ToolchainStoreEvent,
95 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
96};
97use remote::{
98 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
99 remote_client::ConnectionIdentifier,
100};
101use schemars::JsonSchema;
102use serde::Deserialize;
103use session::AppSession;
104use settings::{
105 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
106};
107
108use sqlez::{
109 bindable::{Bind, Column, StaticColumnCount},
110 statement::Statement,
111};
112use status_bar::StatusBar;
113pub use status_bar::StatusItemView;
114use std::{
115 any::TypeId,
116 borrow::Cow,
117 cell::RefCell,
118 cmp,
119 collections::VecDeque,
120 env,
121 hash::Hash,
122 path::{Path, PathBuf},
123 process::ExitStatus,
124 rc::Rc,
125 sync::{
126 Arc, LazyLock, Weak,
127 atomic::{AtomicBool, AtomicUsize},
128 },
129 time::Duration,
130};
131use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
132use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
133pub use toolbar::{
134 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
135};
136pub use ui;
137use ui::{Window, prelude::*};
138use util::{
139 ResultExt, TryFutureExt,
140 paths::{PathStyle, SanitizedPath},
141 rel_path::RelPath,
142 serde::default_true,
143};
144use uuid::Uuid;
145pub use workspace_settings::{
146 AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
147 WorkspaceSettings,
148};
149use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
150
151use crate::{item::ItemBufferKind, notifications::NotificationId};
152use crate::{
153 persistence::{
154 SerializedAxis,
155 model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
156 },
157 security_modal::SecurityModal,
158};
159
160pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
161
162static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
163 env::var("ZED_WINDOW_SIZE")
164 .ok()
165 .as_deref()
166 .and_then(parse_pixel_size_env_var)
167});
168
169static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
170 env::var("ZED_WINDOW_POSITION")
171 .ok()
172 .as_deref()
173 .and_then(parse_pixel_position_env_var)
174});
175
176pub trait TerminalProvider {
177 fn spawn(
178 &self,
179 task: SpawnInTerminal,
180 window: &mut Window,
181 cx: &mut App,
182 ) -> Task<Option<Result<ExitStatus>>>;
183}
184
185pub trait DebuggerProvider {
186 // `active_buffer` is used to resolve build task's name against language-specific tasks.
187 fn start_session(
188 &self,
189 definition: DebugScenario,
190 task_context: SharedTaskContext,
191 active_buffer: Option<Entity<Buffer>>,
192 worktree_id: Option<WorktreeId>,
193 window: &mut Window,
194 cx: &mut App,
195 );
196
197 fn spawn_task_or_modal(
198 &self,
199 workspace: &mut Workspace,
200 action: &Spawn,
201 window: &mut Window,
202 cx: &mut Context<Workspace>,
203 );
204
205 fn task_scheduled(&self, cx: &mut App);
206 fn debug_scenario_scheduled(&self, cx: &mut App);
207 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
208
209 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
210}
211
212/// Opens a file or directory.
213#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
214#[action(namespace = workspace)]
215pub struct Open {
216 /// When true, opens in a new window. When false, adds to the current
217 /// window as a new workspace (multi-workspace).
218 #[serde(default = "Open::default_create_new_window")]
219 pub create_new_window: bool,
220}
221
222impl Open {
223 pub const DEFAULT: Self = Self {
224 create_new_window: true,
225 };
226
227 /// Used by `#[serde(default)]` on the `create_new_window` field so that
228 /// the serde default and `Open::DEFAULT` stay in sync.
229 fn default_create_new_window() -> bool {
230 Self::DEFAULT.create_new_window
231 }
232}
233
234impl Default for Open {
235 fn default() -> Self {
236 Self::DEFAULT
237 }
238}
239
240actions!(
241 workspace,
242 [
243 /// Activates the next pane in the workspace.
244 ActivateNextPane,
245 /// Activates the previous pane in the workspace.
246 ActivatePreviousPane,
247 /// Activates the last pane in the workspace.
248 ActivateLastPane,
249 /// Switches to the next window.
250 ActivateNextWindow,
251 /// Switches to the previous window.
252 ActivatePreviousWindow,
253 /// Adds a folder to the current project.
254 AddFolderToProject,
255 /// Clears all notifications.
256 ClearAllNotifications,
257 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
258 ClearNavigationHistory,
259 /// Closes the active dock.
260 CloseActiveDock,
261 /// Closes all docks.
262 CloseAllDocks,
263 /// Toggles all docks.
264 ToggleAllDocks,
265 /// Closes the current window.
266 CloseWindow,
267 /// Closes the current project.
268 CloseProject,
269 /// Opens the feedback dialog.
270 Feedback,
271 /// Follows the next collaborator in the session.
272 FollowNextCollaborator,
273 /// Moves the focused panel to the next position.
274 MoveFocusedPanelToNextPosition,
275 /// Creates a new file.
276 NewFile,
277 /// Creates a new file in a vertical split.
278 NewFileSplitVertical,
279 /// Creates a new file in a horizontal split.
280 NewFileSplitHorizontal,
281 /// Opens a new search.
282 NewSearch,
283 /// Opens a new window.
284 NewWindow,
285 /// Opens multiple files.
286 OpenFiles,
287 /// Opens the current location in terminal.
288 OpenInTerminal,
289 /// Opens the component preview.
290 OpenComponentPreview,
291 /// Reloads the active item.
292 ReloadActiveItem,
293 /// Resets the active dock to its default size.
294 ResetActiveDockSize,
295 /// Resets all open docks to their default sizes.
296 ResetOpenDocksSize,
297 /// Reloads the application
298 Reload,
299 /// Saves the current file with a new name.
300 SaveAs,
301 /// Saves without formatting.
302 SaveWithoutFormat,
303 /// Shuts down all debug adapters.
304 ShutdownDebugAdapters,
305 /// Suppresses the current notification.
306 SuppressNotification,
307 /// Toggles the bottom dock.
308 ToggleBottomDock,
309 /// Toggles centered layout mode.
310 ToggleCenteredLayout,
311 /// Toggles edit prediction feature globally for all files.
312 ToggleEditPrediction,
313 /// Toggles the left dock.
314 ToggleLeftDock,
315 /// Toggles the right dock.
316 ToggleRightDock,
317 /// Toggles zoom on the active pane.
318 ToggleZoom,
319 /// Toggles read-only mode for the active item (if supported by that item).
320 ToggleReadOnlyFile,
321 /// Zooms in on the active pane.
322 ZoomIn,
323 /// Zooms out of the active pane.
324 ZoomOut,
325 /// If any worktrees are in restricted mode, shows a modal with possible actions.
326 /// If the modal is shown already, closes it without trusting any worktree.
327 ToggleWorktreeSecurity,
328 /// Clears all trusted worktrees, placing them in restricted mode on next open.
329 /// Requires restart to take effect on already opened projects.
330 ClearTrustedWorktrees,
331 /// Stops following a collaborator.
332 Unfollow,
333 /// Restores the banner.
334 RestoreBanner,
335 /// Toggles expansion of the selected item.
336 ToggleExpandItem,
337 ]
338);
339
340/// Activates a specific pane by its index.
341#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
342#[action(namespace = workspace)]
343pub struct ActivatePane(pub usize);
344
345/// Moves an item to a specific pane by index.
346#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
347#[action(namespace = workspace)]
348#[serde(deny_unknown_fields)]
349pub struct MoveItemToPane {
350 #[serde(default = "default_1")]
351 pub destination: usize,
352 #[serde(default = "default_true")]
353 pub focus: bool,
354 #[serde(default)]
355 pub clone: bool,
356}
357
358fn default_1() -> usize {
359 1
360}
361
362/// Moves an item to a pane in the specified direction.
363#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
364#[action(namespace = workspace)]
365#[serde(deny_unknown_fields)]
366pub struct MoveItemToPaneInDirection {
367 #[serde(default = "default_right")]
368 pub direction: SplitDirection,
369 #[serde(default = "default_true")]
370 pub focus: bool,
371 #[serde(default)]
372 pub clone: bool,
373}
374
375/// Creates a new file in a split of the desired direction.
376#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
377#[action(namespace = workspace)]
378#[serde(deny_unknown_fields)]
379pub struct NewFileSplit(pub SplitDirection);
380
381fn default_right() -> SplitDirection {
382 SplitDirection::Right
383}
384
385/// Saves all open files in the workspace.
386#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
387#[action(namespace = workspace)]
388#[serde(deny_unknown_fields)]
389pub struct SaveAll {
390 #[serde(default)]
391 pub save_intent: Option<SaveIntent>,
392}
393
394/// Saves the current file with the specified options.
395#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
396#[action(namespace = workspace)]
397#[serde(deny_unknown_fields)]
398pub struct Save {
399 #[serde(default)]
400 pub save_intent: Option<SaveIntent>,
401}
402
403/// Moves Focus to the central panes in the workspace.
404#[derive(Clone, Debug, PartialEq, Eq, Action)]
405#[action(namespace = workspace)]
406pub struct FocusCenterPane;
407
408/// Closes all items and panes in the workspace.
409#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
410#[action(namespace = workspace)]
411#[serde(deny_unknown_fields)]
412pub struct CloseAllItemsAndPanes {
413 #[serde(default)]
414 pub save_intent: Option<SaveIntent>,
415}
416
417/// Closes all inactive tabs and panes in the workspace.
418#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
419#[action(namespace = workspace)]
420#[serde(deny_unknown_fields)]
421pub struct CloseInactiveTabsAndPanes {
422 #[serde(default)]
423 pub save_intent: Option<SaveIntent>,
424}
425
426/// Closes the active item across all panes.
427#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
428#[action(namespace = workspace)]
429#[serde(deny_unknown_fields)]
430pub struct CloseItemInAllPanes {
431 #[serde(default)]
432 pub save_intent: Option<SaveIntent>,
433 #[serde(default)]
434 pub close_pinned: bool,
435}
436
437/// Sends a sequence of keystrokes to the active element.
438#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
439#[action(namespace = workspace)]
440pub struct SendKeystrokes(pub String);
441
442actions!(
443 project_symbols,
444 [
445 /// Toggles the project symbols search.
446 #[action(name = "Toggle")]
447 ToggleProjectSymbols
448 ]
449);
450
451/// Toggles the file finder interface.
452#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
453#[action(namespace = file_finder, name = "Toggle")]
454#[serde(deny_unknown_fields)]
455pub struct ToggleFileFinder {
456 #[serde(default)]
457 pub separate_history: bool,
458}
459
460/// Opens a new terminal in the center.
461#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
462#[action(namespace = workspace)]
463#[serde(deny_unknown_fields)]
464pub struct NewCenterTerminal {
465 /// If true, creates a local terminal even in remote projects.
466 #[serde(default)]
467 pub local: bool,
468}
469
470/// Opens a new terminal.
471#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
472#[action(namespace = workspace)]
473#[serde(deny_unknown_fields)]
474pub struct NewTerminal {
475 /// If true, creates a local terminal even in remote projects.
476 #[serde(default)]
477 pub local: bool,
478}
479
480/// Increases size of a currently focused dock by a given amount of pixels.
481#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
482#[action(namespace = workspace)]
483#[serde(deny_unknown_fields)]
484pub struct IncreaseActiveDockSize {
485 /// For 0px parameter, uses UI font size value.
486 #[serde(default)]
487 pub px: u32,
488}
489
490/// Decreases size of a currently focused dock by a given amount of pixels.
491#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
492#[action(namespace = workspace)]
493#[serde(deny_unknown_fields)]
494pub struct DecreaseActiveDockSize {
495 /// For 0px parameter, uses UI font size value.
496 #[serde(default)]
497 pub px: u32,
498}
499
500/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
501#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
502#[action(namespace = workspace)]
503#[serde(deny_unknown_fields)]
504pub struct IncreaseOpenDocksSize {
505 /// For 0px parameter, uses UI font size value.
506 #[serde(default)]
507 pub px: u32,
508}
509
510/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
511#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
512#[action(namespace = workspace)]
513#[serde(deny_unknown_fields)]
514pub struct DecreaseOpenDocksSize {
515 /// For 0px parameter, uses UI font size value.
516 #[serde(default)]
517 pub px: u32,
518}
519
520actions!(
521 workspace,
522 [
523 /// Activates the pane to the left.
524 ActivatePaneLeft,
525 /// Activates the pane to the right.
526 ActivatePaneRight,
527 /// Activates the pane above.
528 ActivatePaneUp,
529 /// Activates the pane below.
530 ActivatePaneDown,
531 /// Swaps the current pane with the one to the left.
532 SwapPaneLeft,
533 /// Swaps the current pane with the one to the right.
534 SwapPaneRight,
535 /// Swaps the current pane with the one above.
536 SwapPaneUp,
537 /// Swaps the current pane with the one below.
538 SwapPaneDown,
539 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
540 SwapPaneAdjacent,
541 /// Move the current pane to be at the far left.
542 MovePaneLeft,
543 /// Move the current pane to be at the far right.
544 MovePaneRight,
545 /// Move the current pane to be at the very top.
546 MovePaneUp,
547 /// Move the current pane to be at the very bottom.
548 MovePaneDown,
549 ]
550);
551
552#[derive(PartialEq, Eq, Debug)]
553pub enum CloseIntent {
554 /// Quit the program entirely.
555 Quit,
556 /// Close a window.
557 CloseWindow,
558 /// Replace the workspace in an existing window.
559 ReplaceWindow,
560}
561
562#[derive(Clone)]
563pub struct Toast {
564 id: NotificationId,
565 msg: Cow<'static, str>,
566 autohide: bool,
567 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
568}
569
570impl Toast {
571 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
572 Toast {
573 id,
574 msg: msg.into(),
575 on_click: None,
576 autohide: false,
577 }
578 }
579
580 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
581 where
582 M: Into<Cow<'static, str>>,
583 F: Fn(&mut Window, &mut App) + 'static,
584 {
585 self.on_click = Some((message.into(), Arc::new(on_click)));
586 self
587 }
588
589 pub fn autohide(mut self) -> Self {
590 self.autohide = true;
591 self
592 }
593}
594
595impl PartialEq for Toast {
596 fn eq(&self, other: &Self) -> bool {
597 self.id == other.id
598 && self.msg == other.msg
599 && self.on_click.is_some() == other.on_click.is_some()
600 }
601}
602
603/// Opens a new terminal with the specified working directory.
604#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
605#[action(namespace = workspace)]
606#[serde(deny_unknown_fields)]
607pub struct OpenTerminal {
608 pub working_directory: PathBuf,
609 /// If true, creates a local terminal even in remote projects.
610 #[serde(default)]
611 pub local: bool,
612}
613
614#[derive(
615 Clone,
616 Copy,
617 Debug,
618 Default,
619 Hash,
620 PartialEq,
621 Eq,
622 PartialOrd,
623 Ord,
624 serde::Serialize,
625 serde::Deserialize,
626)]
627pub struct WorkspaceId(i64);
628
629impl WorkspaceId {
630 pub fn from_i64(value: i64) -> Self {
631 Self(value)
632 }
633}
634
635impl StaticColumnCount for WorkspaceId {}
636impl Bind for WorkspaceId {
637 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
638 self.0.bind(statement, start_index)
639 }
640}
641impl Column for WorkspaceId {
642 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
643 i64::column(statement, start_index)
644 .map(|(i, next_index)| (Self(i), next_index))
645 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
646 }
647}
648impl From<WorkspaceId> for i64 {
649 fn from(val: WorkspaceId) -> Self {
650 val.0
651 }
652}
653
654fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
655 if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
656 workspace_window
657 .update(cx, |multi_workspace, window, cx| {
658 let workspace = multi_workspace.workspace().clone();
659 workspace.update(cx, |workspace, cx| {
660 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
661 });
662 })
663 .ok();
664 } else {
665 let task = Workspace::new_local(Vec::new(), app_state.clone(), None, None, None, true, cx);
666 cx.spawn(async move |cx| {
667 let OpenResult { window, .. } = task.await?;
668 window.update(cx, |multi_workspace, window, cx| {
669 window.activate_window();
670 let workspace = multi_workspace.workspace().clone();
671 workspace.update(cx, |workspace, cx| {
672 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
673 });
674 })?;
675 anyhow::Ok(())
676 })
677 .detach_and_log_err(cx);
678 }
679}
680
681pub fn prompt_for_open_path_and_open(
682 workspace: &mut Workspace,
683 app_state: Arc<AppState>,
684 options: PathPromptOptions,
685 create_new_window: bool,
686 window: &mut Window,
687 cx: &mut Context<Workspace>,
688) {
689 let paths = workspace.prompt_for_open_path(
690 options,
691 DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
692 window,
693 cx,
694 );
695 let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
696 cx.spawn_in(window, async move |this, cx| {
697 let Some(paths) = paths.await.log_err().flatten() else {
698 return;
699 };
700 if !create_new_window {
701 if let Some(handle) = multi_workspace_handle {
702 if let Some(task) = handle
703 .update(cx, |multi_workspace, window, cx| {
704 multi_workspace.open_project(paths, window, cx)
705 })
706 .log_err()
707 {
708 task.await.log_err();
709 }
710 return;
711 }
712 }
713 if let Some(task) = this
714 .update_in(cx, |this, window, cx| {
715 this.open_workspace_for_paths(false, paths, window, cx)
716 })
717 .log_err()
718 {
719 task.await.log_err();
720 }
721 })
722 .detach();
723}
724
725pub fn init(app_state: Arc<AppState>, cx: &mut App) {
726 component::init();
727 theme_preview::init(cx);
728 toast_layer::init(cx);
729 history_manager::init(app_state.fs.clone(), cx);
730
731 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
732 .on_action(|_: &Reload, cx| reload(cx))
733 .on_action({
734 let app_state = Arc::downgrade(&app_state);
735 move |_: &Open, cx: &mut App| {
736 if let Some(app_state) = app_state.upgrade() {
737 prompt_and_open_paths(
738 app_state,
739 PathPromptOptions {
740 files: true,
741 directories: true,
742 multiple: true,
743 prompt: None,
744 },
745 cx,
746 );
747 }
748 }
749 })
750 .on_action({
751 let app_state = Arc::downgrade(&app_state);
752 move |_: &OpenFiles, cx: &mut App| {
753 let directories = cx.can_select_mixed_files_and_dirs();
754 if let Some(app_state) = app_state.upgrade() {
755 prompt_and_open_paths(
756 app_state,
757 PathPromptOptions {
758 files: true,
759 directories,
760 multiple: true,
761 prompt: None,
762 },
763 cx,
764 );
765 }
766 }
767 });
768}
769
770type BuildProjectItemFn =
771 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
772
773type BuildProjectItemForPathFn =
774 fn(
775 &Entity<Project>,
776 &ProjectPath,
777 &mut Window,
778 &mut App,
779 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
780
781#[derive(Clone, Default)]
782struct ProjectItemRegistry {
783 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
784 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
785}
786
787impl ProjectItemRegistry {
788 fn register<T: ProjectItem>(&mut self) {
789 self.build_project_item_fns_by_type.insert(
790 TypeId::of::<T::Item>(),
791 |item, project, pane, window, cx| {
792 let item = item.downcast().unwrap();
793 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
794 as Box<dyn ItemHandle>
795 },
796 );
797 self.build_project_item_for_path_fns
798 .push(|project, project_path, window, cx| {
799 let project_path = project_path.clone();
800 let is_file = project
801 .read(cx)
802 .entry_for_path(&project_path, cx)
803 .is_some_and(|entry| entry.is_file());
804 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
805 let is_local = project.read(cx).is_local();
806 let project_item =
807 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
808 let project = project.clone();
809 Some(window.spawn(cx, async move |cx| {
810 match project_item.await.with_context(|| {
811 format!(
812 "opening project path {:?}",
813 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
814 )
815 }) {
816 Ok(project_item) => {
817 let project_item = project_item;
818 let project_entry_id: Option<ProjectEntryId> =
819 project_item.read_with(cx, project::ProjectItem::entry_id);
820 let build_workspace_item = Box::new(
821 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
822 Box::new(cx.new(|cx| {
823 T::for_project_item(
824 project,
825 Some(pane),
826 project_item,
827 window,
828 cx,
829 )
830 })) as Box<dyn ItemHandle>
831 },
832 ) as Box<_>;
833 Ok((project_entry_id, build_workspace_item))
834 }
835 Err(e) => {
836 log::warn!("Failed to open a project item: {e:#}");
837 if e.error_code() == ErrorCode::Internal {
838 if let Some(abs_path) =
839 entry_abs_path.as_deref().filter(|_| is_file)
840 {
841 if let Some(broken_project_item_view) =
842 cx.update(|window, cx| {
843 T::for_broken_project_item(
844 abs_path, is_local, &e, window, cx,
845 )
846 })?
847 {
848 let build_workspace_item = Box::new(
849 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
850 cx.new(|_| broken_project_item_view).boxed_clone()
851 },
852 )
853 as Box<_>;
854 return Ok((None, build_workspace_item));
855 }
856 }
857 }
858 Err(e)
859 }
860 }
861 }))
862 });
863 }
864
865 fn open_path(
866 &self,
867 project: &Entity<Project>,
868 path: &ProjectPath,
869 window: &mut Window,
870 cx: &mut App,
871 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
872 let Some(open_project_item) = self
873 .build_project_item_for_path_fns
874 .iter()
875 .rev()
876 .find_map(|open_project_item| open_project_item(project, path, window, cx))
877 else {
878 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
879 };
880 open_project_item
881 }
882
883 fn build_item<T: project::ProjectItem>(
884 &self,
885 item: Entity<T>,
886 project: Entity<Project>,
887 pane: Option<&Pane>,
888 window: &mut Window,
889 cx: &mut App,
890 ) -> Option<Box<dyn ItemHandle>> {
891 let build = self
892 .build_project_item_fns_by_type
893 .get(&TypeId::of::<T>())?;
894 Some(build(item.into_any(), project, pane, window, cx))
895 }
896}
897
898type WorkspaceItemBuilder =
899 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
900
901impl Global for ProjectItemRegistry {}
902
903/// Registers a [ProjectItem] for the app. When opening a file, all the registered
904/// items will get a chance to open the file, starting from the project item that
905/// was added last.
906pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
907 cx.default_global::<ProjectItemRegistry>().register::<I>();
908}
909
910#[derive(Default)]
911pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
912
913struct FollowableViewDescriptor {
914 from_state_proto: fn(
915 Entity<Workspace>,
916 ViewId,
917 &mut Option<proto::view::Variant>,
918 &mut Window,
919 &mut App,
920 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
921 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
922}
923
924impl Global for FollowableViewRegistry {}
925
926impl FollowableViewRegistry {
927 pub fn register<I: FollowableItem>(cx: &mut App) {
928 cx.default_global::<Self>().0.insert(
929 TypeId::of::<I>(),
930 FollowableViewDescriptor {
931 from_state_proto: |workspace, id, state, window, cx| {
932 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
933 cx.foreground_executor()
934 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
935 })
936 },
937 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
938 },
939 );
940 }
941
942 pub fn from_state_proto(
943 workspace: Entity<Workspace>,
944 view_id: ViewId,
945 mut state: Option<proto::view::Variant>,
946 window: &mut Window,
947 cx: &mut App,
948 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
949 cx.update_default_global(|this: &mut Self, cx| {
950 this.0.values().find_map(|descriptor| {
951 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
952 })
953 })
954 }
955
956 pub fn to_followable_view(
957 view: impl Into<AnyView>,
958 cx: &App,
959 ) -> Option<Box<dyn FollowableItemHandle>> {
960 let this = cx.try_global::<Self>()?;
961 let view = view.into();
962 let descriptor = this.0.get(&view.entity_type())?;
963 Some((descriptor.to_followable_view)(&view))
964 }
965}
966
967#[derive(Copy, Clone)]
968struct SerializableItemDescriptor {
969 deserialize: fn(
970 Entity<Project>,
971 WeakEntity<Workspace>,
972 WorkspaceId,
973 ItemId,
974 &mut Window,
975 &mut Context<Pane>,
976 ) -> Task<Result<Box<dyn ItemHandle>>>,
977 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
978 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
979}
980
981#[derive(Default)]
982struct SerializableItemRegistry {
983 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
984 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
985}
986
987impl Global for SerializableItemRegistry {}
988
989impl SerializableItemRegistry {
990 fn deserialize(
991 item_kind: &str,
992 project: Entity<Project>,
993 workspace: WeakEntity<Workspace>,
994 workspace_id: WorkspaceId,
995 item_item: ItemId,
996 window: &mut Window,
997 cx: &mut Context<Pane>,
998 ) -> Task<Result<Box<dyn ItemHandle>>> {
999 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1000 return Task::ready(Err(anyhow!(
1001 "cannot deserialize {}, descriptor not found",
1002 item_kind
1003 )));
1004 };
1005
1006 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
1007 }
1008
1009 fn cleanup(
1010 item_kind: &str,
1011 workspace_id: WorkspaceId,
1012 loaded_items: Vec<ItemId>,
1013 window: &mut Window,
1014 cx: &mut App,
1015 ) -> Task<Result<()>> {
1016 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1017 return Task::ready(Err(anyhow!(
1018 "cannot cleanup {}, descriptor not found",
1019 item_kind
1020 )));
1021 };
1022
1023 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
1024 }
1025
1026 fn view_to_serializable_item_handle(
1027 view: AnyView,
1028 cx: &App,
1029 ) -> Option<Box<dyn SerializableItemHandle>> {
1030 let this = cx.try_global::<Self>()?;
1031 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
1032 Some((descriptor.view_to_serializable_item)(view))
1033 }
1034
1035 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
1036 let this = cx.try_global::<Self>()?;
1037 this.descriptors_by_kind.get(item_kind).copied()
1038 }
1039}
1040
1041pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
1042 let serialized_item_kind = I::serialized_item_kind();
1043
1044 let registry = cx.default_global::<SerializableItemRegistry>();
1045 let descriptor = SerializableItemDescriptor {
1046 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
1047 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
1048 cx.foreground_executor()
1049 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
1050 },
1051 cleanup: |workspace_id, loaded_items, window, cx| {
1052 I::cleanup(workspace_id, loaded_items, window, cx)
1053 },
1054 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
1055 };
1056 registry
1057 .descriptors_by_kind
1058 .insert(Arc::from(serialized_item_kind), descriptor);
1059 registry
1060 .descriptors_by_type
1061 .insert(TypeId::of::<I>(), descriptor);
1062}
1063
1064pub struct AppState {
1065 pub languages: Arc<LanguageRegistry>,
1066 pub client: Arc<Client>,
1067 pub user_store: Entity<UserStore>,
1068 pub workspace_store: Entity<WorkspaceStore>,
1069 pub fs: Arc<dyn fs::Fs>,
1070 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1071 pub node_runtime: NodeRuntime,
1072 pub session: Entity<AppSession>,
1073}
1074
1075struct GlobalAppState(Weak<AppState>);
1076
1077impl Global for GlobalAppState {}
1078
1079pub struct WorkspaceStore {
1080 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1081 client: Arc<Client>,
1082 _subscriptions: Vec<client::Subscription>,
1083}
1084
1085#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1086pub enum CollaboratorId {
1087 PeerId(PeerId),
1088 Agent,
1089}
1090
1091impl From<PeerId> for CollaboratorId {
1092 fn from(peer_id: PeerId) -> Self {
1093 CollaboratorId::PeerId(peer_id)
1094 }
1095}
1096
1097impl From<&PeerId> for CollaboratorId {
1098 fn from(peer_id: &PeerId) -> Self {
1099 CollaboratorId::PeerId(*peer_id)
1100 }
1101}
1102
1103#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1104struct Follower {
1105 project_id: Option<u64>,
1106 peer_id: PeerId,
1107}
1108
1109impl AppState {
1110 #[track_caller]
1111 pub fn global(cx: &App) -> Weak<Self> {
1112 cx.global::<GlobalAppState>().0.clone()
1113 }
1114 pub fn try_global(cx: &App) -> Option<Weak<Self>> {
1115 cx.try_global::<GlobalAppState>()
1116 .map(|state| state.0.clone())
1117 }
1118 pub fn set_global(state: Weak<AppState>, cx: &mut App) {
1119 cx.set_global(GlobalAppState(state));
1120 }
1121
1122 #[cfg(any(test, feature = "test-support"))]
1123 pub fn test(cx: &mut App) -> Arc<Self> {
1124 use fs::Fs;
1125 use node_runtime::NodeRuntime;
1126 use session::Session;
1127 use settings::SettingsStore;
1128
1129 if !cx.has_global::<SettingsStore>() {
1130 let settings_store = SettingsStore::test(cx);
1131 cx.set_global(settings_store);
1132 }
1133
1134 let fs = fs::FakeFs::new(cx.background_executor().clone());
1135 <dyn Fs>::set_global(fs.clone(), cx);
1136 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1137 let clock = Arc::new(clock::FakeSystemClock::new());
1138 let http_client = http_client::FakeHttpClient::with_404_response();
1139 let client = Client::new(clock, http_client, cx);
1140 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1141 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1142 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1143
1144 theme::init(theme::LoadThemes::JustBase, cx);
1145 client::init(&client, cx);
1146
1147 Arc::new(Self {
1148 client,
1149 fs,
1150 languages,
1151 user_store,
1152 workspace_store,
1153 node_runtime: NodeRuntime::unavailable(),
1154 build_window_options: |_, _| Default::default(),
1155 session,
1156 })
1157 }
1158}
1159
1160struct DelayedDebouncedEditAction {
1161 task: Option<Task<()>>,
1162 cancel_channel: Option<oneshot::Sender<()>>,
1163}
1164
1165impl DelayedDebouncedEditAction {
1166 fn new() -> DelayedDebouncedEditAction {
1167 DelayedDebouncedEditAction {
1168 task: None,
1169 cancel_channel: None,
1170 }
1171 }
1172
1173 fn fire_new<F>(
1174 &mut self,
1175 delay: Duration,
1176 window: &mut Window,
1177 cx: &mut Context<Workspace>,
1178 func: F,
1179 ) where
1180 F: 'static
1181 + Send
1182 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1183 {
1184 if let Some(channel) = self.cancel_channel.take() {
1185 _ = channel.send(());
1186 }
1187
1188 let (sender, mut receiver) = oneshot::channel::<()>();
1189 self.cancel_channel = Some(sender);
1190
1191 let previous_task = self.task.take();
1192 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1193 let mut timer = cx.background_executor().timer(delay).fuse();
1194 if let Some(previous_task) = previous_task {
1195 previous_task.await;
1196 }
1197
1198 futures::select_biased! {
1199 _ = receiver => return,
1200 _ = timer => {}
1201 }
1202
1203 if let Some(result) = workspace
1204 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1205 .log_err()
1206 {
1207 result.await.log_err();
1208 }
1209 }));
1210 }
1211}
1212
1213pub enum Event {
1214 PaneAdded(Entity<Pane>),
1215 PaneRemoved,
1216 ItemAdded {
1217 item: Box<dyn ItemHandle>,
1218 },
1219 ActiveItemChanged,
1220 ItemRemoved {
1221 item_id: EntityId,
1222 },
1223 UserSavedItem {
1224 pane: WeakEntity<Pane>,
1225 item: Box<dyn WeakItemHandle>,
1226 save_intent: SaveIntent,
1227 },
1228 ContactRequestedJoin(u64),
1229 WorkspaceCreated(WeakEntity<Workspace>),
1230 OpenBundledFile {
1231 text: Cow<'static, str>,
1232 title: &'static str,
1233 language: &'static str,
1234 },
1235 ZoomChanged,
1236 ModalOpened,
1237 Activate,
1238 PanelAdded(AnyView),
1239}
1240
1241#[derive(Debug, Clone)]
1242pub enum OpenVisible {
1243 All,
1244 None,
1245 OnlyFiles,
1246 OnlyDirectories,
1247}
1248
1249enum WorkspaceLocation {
1250 // Valid local paths or SSH project to serialize
1251 Location(SerializedWorkspaceLocation, PathList),
1252 // No valid location found hence clear session id
1253 DetachFromSession,
1254 // No valid location found to serialize
1255 None,
1256}
1257
1258type PromptForNewPath = Box<
1259 dyn Fn(
1260 &mut Workspace,
1261 DirectoryLister,
1262 Option<String>,
1263 &mut Window,
1264 &mut Context<Workspace>,
1265 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1266>;
1267
1268type PromptForOpenPath = Box<
1269 dyn Fn(
1270 &mut Workspace,
1271 DirectoryLister,
1272 &mut Window,
1273 &mut Context<Workspace>,
1274 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1275>;
1276
1277#[derive(Default)]
1278struct DispatchingKeystrokes {
1279 dispatched: HashSet<Vec<Keystroke>>,
1280 queue: VecDeque<Keystroke>,
1281 task: Option<Shared<Task<()>>>,
1282}
1283
1284/// Collects everything project-related for a certain window opened.
1285/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1286///
1287/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1288/// The `Workspace` owns everybody's state and serves as a default, "global context",
1289/// that can be used to register a global action to be triggered from any place in the window.
1290pub struct Workspace {
1291 weak_self: WeakEntity<Self>,
1292 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1293 zoomed: Option<AnyWeakView>,
1294 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1295 zoomed_position: Option<DockPosition>,
1296 center: PaneGroup,
1297 left_dock: Entity<Dock>,
1298 bottom_dock: Entity<Dock>,
1299 right_dock: Entity<Dock>,
1300 panes: Vec<Entity<Pane>>,
1301 active_worktree_override: Option<WorktreeId>,
1302 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1303 active_pane: Entity<Pane>,
1304 last_active_center_pane: Option<WeakEntity<Pane>>,
1305 last_active_view_id: Option<proto::ViewId>,
1306 status_bar: Entity<StatusBar>,
1307 pub(crate) modal_layer: Entity<ModalLayer>,
1308 toast_layer: Entity<ToastLayer>,
1309 titlebar_item: Option<AnyView>,
1310 notifications: Notifications,
1311 suppressed_notifications: HashSet<NotificationId>,
1312 project: Entity<Project>,
1313 follower_states: HashMap<CollaboratorId, FollowerState>,
1314 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1315 window_edited: bool,
1316 last_window_title: Option<String>,
1317 dirty_items: HashMap<EntityId, Subscription>,
1318 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1319 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1320 database_id: Option<WorkspaceId>,
1321 app_state: Arc<AppState>,
1322 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1323 _subscriptions: Vec<Subscription>,
1324 _apply_leader_updates: Task<Result<()>>,
1325 _observe_current_user: Task<Result<()>>,
1326 _schedule_serialize_workspace: Option<Task<()>>,
1327 _serialize_workspace_task: Option<Task<()>>,
1328 _schedule_serialize_ssh_paths: Option<Task<()>>,
1329 pane_history_timestamp: Arc<AtomicUsize>,
1330 bounds: Bounds<Pixels>,
1331 pub centered_layout: bool,
1332 bounds_save_task_queued: Option<Task<()>>,
1333 on_prompt_for_new_path: Option<PromptForNewPath>,
1334 on_prompt_for_open_path: Option<PromptForOpenPath>,
1335 terminal_provider: Option<Box<dyn TerminalProvider>>,
1336 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1337 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1338 _items_serializer: Task<Result<()>>,
1339 session_id: Option<String>,
1340 scheduled_tasks: Vec<Task<()>>,
1341 last_open_dock_positions: Vec<DockPosition>,
1342 removing: bool,
1343 _panels_task: Option<Task<Result<()>>>,
1344 sidebar_focus_handle: Option<FocusHandle>,
1345}
1346
1347impl EventEmitter<Event> for Workspace {}
1348
1349#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1350pub struct ViewId {
1351 pub creator: CollaboratorId,
1352 pub id: u64,
1353}
1354
1355pub struct FollowerState {
1356 center_pane: Entity<Pane>,
1357 dock_pane: Option<Entity<Pane>>,
1358 active_view_id: Option<ViewId>,
1359 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1360}
1361
1362struct FollowerView {
1363 view: Box<dyn FollowableItemHandle>,
1364 location: Option<proto::PanelId>,
1365}
1366
1367impl Workspace {
1368 pub fn new(
1369 workspace_id: Option<WorkspaceId>,
1370 project: Entity<Project>,
1371 app_state: Arc<AppState>,
1372 window: &mut Window,
1373 cx: &mut Context<Self>,
1374 ) -> Self {
1375 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1376 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1377 if let TrustedWorktreesEvent::Trusted(..) = e {
1378 // Do not persist auto trusted worktrees
1379 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1380 worktrees_store.update(cx, |worktrees_store, cx| {
1381 worktrees_store.schedule_serialization(
1382 cx,
1383 |new_trusted_worktrees, cx| {
1384 let timeout =
1385 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1386 let db = WorkspaceDb::global(cx);
1387 cx.background_spawn(async move {
1388 timeout.await;
1389 db.save_trusted_worktrees(new_trusted_worktrees)
1390 .await
1391 .log_err();
1392 })
1393 },
1394 )
1395 });
1396 }
1397 }
1398 })
1399 .detach();
1400
1401 cx.observe_global::<SettingsStore>(|_, cx| {
1402 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1403 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1404 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1405 trusted_worktrees.auto_trust_all(cx);
1406 })
1407 }
1408 }
1409 })
1410 .detach();
1411 }
1412
1413 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1414 match event {
1415 project::Event::RemoteIdChanged(_) => {
1416 this.update_window_title(window, cx);
1417 }
1418
1419 project::Event::CollaboratorLeft(peer_id) => {
1420 this.collaborator_left(*peer_id, window, cx);
1421 }
1422
1423 &project::Event::WorktreeRemoved(_) => {
1424 this.update_window_title(window, cx);
1425 this.serialize_workspace(window, cx);
1426 this.update_history(cx);
1427 }
1428
1429 &project::Event::WorktreeAdded(id) => {
1430 this.update_window_title(window, cx);
1431 if this
1432 .project()
1433 .read(cx)
1434 .worktree_for_id(id, cx)
1435 .is_some_and(|wt| wt.read(cx).is_visible())
1436 {
1437 this.serialize_workspace(window, cx);
1438 this.update_history(cx);
1439 }
1440 }
1441 project::Event::WorktreeUpdatedEntries(..) => {
1442 this.update_window_title(window, cx);
1443 this.serialize_workspace(window, cx);
1444 }
1445
1446 project::Event::DisconnectedFromHost => {
1447 this.update_window_edited(window, cx);
1448 let leaders_to_unfollow =
1449 this.follower_states.keys().copied().collect::<Vec<_>>();
1450 for leader_id in leaders_to_unfollow {
1451 this.unfollow(leader_id, window, cx);
1452 }
1453 }
1454
1455 project::Event::DisconnectedFromRemote {
1456 server_not_running: _,
1457 } => {
1458 this.update_window_edited(window, cx);
1459 }
1460
1461 project::Event::Closed => {
1462 window.remove_window();
1463 }
1464
1465 project::Event::DeletedEntry(_, entry_id) => {
1466 for pane in this.panes.iter() {
1467 pane.update(cx, |pane, cx| {
1468 pane.handle_deleted_project_item(*entry_id, window, cx)
1469 });
1470 }
1471 }
1472
1473 project::Event::Toast {
1474 notification_id,
1475 message,
1476 link,
1477 } => this.show_notification(
1478 NotificationId::named(notification_id.clone()),
1479 cx,
1480 |cx| {
1481 let mut notification = MessageNotification::new(message.clone(), cx);
1482 if let Some(link) = link {
1483 notification = notification
1484 .more_info_message(link.label)
1485 .more_info_url(link.url);
1486 }
1487
1488 cx.new(|_| notification)
1489 },
1490 ),
1491
1492 project::Event::HideToast { notification_id } => {
1493 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1494 }
1495
1496 project::Event::LanguageServerPrompt(request) => {
1497 struct LanguageServerPrompt;
1498
1499 this.show_notification(
1500 NotificationId::composite::<LanguageServerPrompt>(request.id),
1501 cx,
1502 |cx| {
1503 cx.new(|cx| {
1504 notifications::LanguageServerPrompt::new(request.clone(), cx)
1505 })
1506 },
1507 );
1508 }
1509
1510 project::Event::AgentLocationChanged => {
1511 this.handle_agent_location_changed(window, cx)
1512 }
1513
1514 _ => {}
1515 }
1516 cx.notify()
1517 })
1518 .detach();
1519
1520 cx.subscribe_in(
1521 &project.read(cx).breakpoint_store(),
1522 window,
1523 |workspace, _, event, window, cx| match event {
1524 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1525 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1526 workspace.serialize_workspace(window, cx);
1527 }
1528 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1529 },
1530 )
1531 .detach();
1532 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1533 cx.subscribe_in(
1534 &toolchain_store,
1535 window,
1536 |workspace, _, event, window, cx| match event {
1537 ToolchainStoreEvent::CustomToolchainsModified => {
1538 workspace.serialize_workspace(window, cx);
1539 }
1540 _ => {}
1541 },
1542 )
1543 .detach();
1544 }
1545
1546 cx.on_focus_lost(window, |this, window, cx| {
1547 let focus_handle = this.focus_handle(cx);
1548 window.focus(&focus_handle, cx);
1549 })
1550 .detach();
1551
1552 let weak_handle = cx.entity().downgrade();
1553 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1554
1555 let center_pane = cx.new(|cx| {
1556 let mut center_pane = Pane::new(
1557 weak_handle.clone(),
1558 project.clone(),
1559 pane_history_timestamp.clone(),
1560 None,
1561 NewFile.boxed_clone(),
1562 true,
1563 window,
1564 cx,
1565 );
1566 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1567 center_pane.set_should_display_welcome_page(true);
1568 center_pane
1569 });
1570 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1571 .detach();
1572
1573 window.focus(¢er_pane.focus_handle(cx), cx);
1574
1575 cx.emit(Event::PaneAdded(center_pane.clone()));
1576
1577 let any_window_handle = window.window_handle();
1578 app_state.workspace_store.update(cx, |store, _| {
1579 store
1580 .workspaces
1581 .insert((any_window_handle, weak_handle.clone()));
1582 });
1583
1584 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1585 let mut connection_status = app_state.client.status();
1586 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1587 current_user.next().await;
1588 connection_status.next().await;
1589 let mut stream =
1590 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1591
1592 while stream.recv().await.is_some() {
1593 this.update(cx, |_, cx| cx.notify())?;
1594 }
1595 anyhow::Ok(())
1596 });
1597
1598 // All leader updates are enqueued and then processed in a single task, so
1599 // that each asynchronous operation can be run in order.
1600 let (leader_updates_tx, mut leader_updates_rx) =
1601 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1602 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1603 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1604 Self::process_leader_update(&this, leader_id, update, cx)
1605 .await
1606 .log_err();
1607 }
1608
1609 Ok(())
1610 });
1611
1612 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1613 let modal_layer = cx.new(|_| ModalLayer::new());
1614 let toast_layer = cx.new(|_| ToastLayer::new());
1615 cx.subscribe(
1616 &modal_layer,
1617 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1618 cx.emit(Event::ModalOpened);
1619 },
1620 )
1621 .detach();
1622
1623 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1624 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1625 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1626 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1627 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1628 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1629 let status_bar = cx.new(|cx| {
1630 let mut status_bar = StatusBar::new(¢er_pane.clone(), window, cx);
1631 status_bar.add_left_item(left_dock_buttons, window, cx);
1632 status_bar.add_right_item(right_dock_buttons, window, cx);
1633 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1634 status_bar
1635 });
1636
1637 let session_id = app_state.session.read(cx).id().to_owned();
1638
1639 let mut active_call = None;
1640 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1641 let subscriptions =
1642 vec![
1643 call.0
1644 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1645 ];
1646 active_call = Some((call, subscriptions));
1647 }
1648
1649 let (serializable_items_tx, serializable_items_rx) =
1650 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1651 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1652 Self::serialize_items(&this, serializable_items_rx, cx).await
1653 });
1654
1655 let subscriptions = vec![
1656 cx.observe_window_activation(window, Self::on_window_activation_changed),
1657 cx.observe_window_bounds(window, move |this, window, cx| {
1658 if this.bounds_save_task_queued.is_some() {
1659 return;
1660 }
1661 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1662 cx.background_executor()
1663 .timer(Duration::from_millis(100))
1664 .await;
1665 this.update_in(cx, |this, window, cx| {
1666 this.save_window_bounds(window, cx).detach();
1667 this.bounds_save_task_queued.take();
1668 })
1669 .ok();
1670 }));
1671 cx.notify();
1672 }),
1673 cx.observe_window_appearance(window, |_, window, cx| {
1674 let window_appearance = window.appearance();
1675
1676 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1677
1678 GlobalTheme::reload_theme(cx);
1679 GlobalTheme::reload_icon_theme(cx);
1680 }),
1681 cx.on_release({
1682 let weak_handle = weak_handle.clone();
1683 move |this, cx| {
1684 this.app_state.workspace_store.update(cx, move |store, _| {
1685 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1686 })
1687 }
1688 }),
1689 ];
1690
1691 cx.defer_in(window, move |this, window, cx| {
1692 this.update_window_title(window, cx);
1693 this.show_initial_notifications(cx);
1694 });
1695
1696 let mut center = PaneGroup::new(center_pane.clone());
1697 center.set_is_center(true);
1698 center.mark_positions(cx);
1699
1700 Workspace {
1701 weak_self: weak_handle.clone(),
1702 zoomed: None,
1703 zoomed_position: None,
1704 previous_dock_drag_coordinates: None,
1705 center,
1706 panes: vec![center_pane.clone()],
1707 panes_by_item: Default::default(),
1708 active_pane: center_pane.clone(),
1709 last_active_center_pane: Some(center_pane.downgrade()),
1710 last_active_view_id: None,
1711 status_bar,
1712 modal_layer,
1713 toast_layer,
1714 titlebar_item: None,
1715 active_worktree_override: None,
1716 notifications: Notifications::default(),
1717 suppressed_notifications: HashSet::default(),
1718 left_dock,
1719 bottom_dock,
1720 right_dock,
1721 _panels_task: None,
1722 project: project.clone(),
1723 follower_states: Default::default(),
1724 last_leaders_by_pane: Default::default(),
1725 dispatching_keystrokes: Default::default(),
1726 window_edited: false,
1727 last_window_title: None,
1728 dirty_items: Default::default(),
1729 active_call,
1730 database_id: workspace_id,
1731 app_state,
1732 _observe_current_user,
1733 _apply_leader_updates,
1734 _schedule_serialize_workspace: None,
1735 _serialize_workspace_task: None,
1736 _schedule_serialize_ssh_paths: None,
1737 leader_updates_tx,
1738 _subscriptions: subscriptions,
1739 pane_history_timestamp,
1740 workspace_actions: Default::default(),
1741 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1742 bounds: Default::default(),
1743 centered_layout: false,
1744 bounds_save_task_queued: None,
1745 on_prompt_for_new_path: None,
1746 on_prompt_for_open_path: None,
1747 terminal_provider: None,
1748 debugger_provider: None,
1749 serializable_items_tx,
1750 _items_serializer,
1751 session_id: Some(session_id),
1752
1753 scheduled_tasks: Vec::new(),
1754 last_open_dock_positions: Vec::new(),
1755 removing: false,
1756 sidebar_focus_handle: None,
1757 }
1758 }
1759
1760 pub fn new_local(
1761 abs_paths: Vec<PathBuf>,
1762 app_state: Arc<AppState>,
1763 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1764 env: Option<HashMap<String, String>>,
1765 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1766 activate: bool,
1767 cx: &mut App,
1768 ) -> Task<anyhow::Result<OpenResult>> {
1769 let project_handle = Project::local(
1770 app_state.client.clone(),
1771 app_state.node_runtime.clone(),
1772 app_state.user_store.clone(),
1773 app_state.languages.clone(),
1774 app_state.fs.clone(),
1775 env,
1776 Default::default(),
1777 cx,
1778 );
1779
1780 let db = WorkspaceDb::global(cx);
1781 let kvp = db::kvp::KeyValueStore::global(cx);
1782 cx.spawn(async move |cx| {
1783 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1784 for path in abs_paths.into_iter() {
1785 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1786 paths_to_open.push(canonical)
1787 } else {
1788 paths_to_open.push(path)
1789 }
1790 }
1791
1792 let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
1793
1794 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1795 paths_to_open = paths.ordered_paths().cloned().collect();
1796 if !paths.is_lexicographically_ordered() {
1797 project_handle.update(cx, |project, cx| {
1798 project.set_worktrees_reordered(true, cx);
1799 });
1800 }
1801 }
1802
1803 // Get project paths for all of the abs_paths
1804 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1805 Vec::with_capacity(paths_to_open.len());
1806
1807 for path in paths_to_open.into_iter() {
1808 if let Some((_, project_entry)) = cx
1809 .update(|cx| {
1810 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1811 })
1812 .await
1813 .log_err()
1814 {
1815 project_paths.push((path, Some(project_entry)));
1816 } else {
1817 project_paths.push((path, None));
1818 }
1819 }
1820
1821 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1822 serialized_workspace.id
1823 } else {
1824 db.next_id().await.unwrap_or_else(|_| Default::default())
1825 };
1826
1827 let toolchains = db.toolchains(workspace_id).await?;
1828
1829 for (toolchain, worktree_path, path) in toolchains {
1830 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1831 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1832 this.find_worktree(&worktree_path, cx)
1833 .and_then(|(worktree, rel_path)| {
1834 if rel_path.is_empty() {
1835 Some(worktree.read(cx).id())
1836 } else {
1837 None
1838 }
1839 })
1840 }) else {
1841 // We did not find a worktree with a given path, but that's whatever.
1842 continue;
1843 };
1844 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1845 continue;
1846 }
1847
1848 project_handle
1849 .update(cx, |this, cx| {
1850 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1851 })
1852 .await;
1853 }
1854 if let Some(workspace) = serialized_workspace.as_ref() {
1855 project_handle.update(cx, |this, cx| {
1856 for (scope, toolchains) in &workspace.user_toolchains {
1857 for toolchain in toolchains {
1858 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1859 }
1860 }
1861 });
1862 }
1863
1864 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1865 if let Some(window) = requesting_window {
1866 let centered_layout = serialized_workspace
1867 .as_ref()
1868 .map(|w| w.centered_layout)
1869 .unwrap_or(false);
1870
1871 let workspace = window.update(cx, |multi_workspace, window, cx| {
1872 let workspace = cx.new(|cx| {
1873 let mut workspace = Workspace::new(
1874 Some(workspace_id),
1875 project_handle.clone(),
1876 app_state.clone(),
1877 window,
1878 cx,
1879 );
1880
1881 workspace.centered_layout = centered_layout;
1882
1883 // Call init callback to add items before window renders
1884 if let Some(init) = init {
1885 init(&mut workspace, window, cx);
1886 }
1887
1888 workspace
1889 });
1890 if activate {
1891 multi_workspace.activate(workspace.clone(), cx);
1892 } else {
1893 multi_workspace.add_workspace(workspace.clone(), cx);
1894 }
1895 workspace
1896 })?;
1897 (window, workspace)
1898 } else {
1899 let window_bounds_override = window_bounds_env_override();
1900
1901 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1902 (Some(WindowBounds::Windowed(bounds)), None)
1903 } else if let Some(workspace) = serialized_workspace.as_ref()
1904 && let Some(display) = workspace.display
1905 && let Some(bounds) = workspace.window_bounds.as_ref()
1906 {
1907 // Reopening an existing workspace - restore its saved bounds
1908 (Some(bounds.0), Some(display))
1909 } else if let Some((display, bounds)) =
1910 persistence::read_default_window_bounds(&kvp)
1911 {
1912 // New or empty workspace - use the last known window bounds
1913 (Some(bounds), Some(display))
1914 } else {
1915 // New window - let GPUI's default_bounds() handle cascading
1916 (None, None)
1917 };
1918
1919 // Use the serialized workspace to construct the new window
1920 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1921 options.window_bounds = window_bounds;
1922 let centered_layout = serialized_workspace
1923 .as_ref()
1924 .map(|w| w.centered_layout)
1925 .unwrap_or(false);
1926 let window = cx.open_window(options, {
1927 let app_state = app_state.clone();
1928 let project_handle = project_handle.clone();
1929 move |window, cx| {
1930 let workspace = cx.new(|cx| {
1931 let mut workspace = Workspace::new(
1932 Some(workspace_id),
1933 project_handle,
1934 app_state,
1935 window,
1936 cx,
1937 );
1938 workspace.centered_layout = centered_layout;
1939
1940 // Call init callback to add items before window renders
1941 if let Some(init) = init {
1942 init(&mut workspace, window, cx);
1943 }
1944
1945 workspace
1946 });
1947 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1948 }
1949 })?;
1950 let workspace =
1951 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
1952 multi_workspace.workspace().clone()
1953 })?;
1954 (window, workspace)
1955 };
1956
1957 notify_if_database_failed(window, cx);
1958 // Check if this is an empty workspace (no paths to open)
1959 // An empty workspace is one where project_paths is empty
1960 let is_empty_workspace = project_paths.is_empty();
1961 // Check if serialized workspace has paths before it's moved
1962 let serialized_workspace_has_paths = serialized_workspace
1963 .as_ref()
1964 .map(|ws| !ws.paths.is_empty())
1965 .unwrap_or(false);
1966
1967 let opened_items = window
1968 .update(cx, |_, window, cx| {
1969 workspace.update(cx, |_workspace: &mut Workspace, cx| {
1970 open_items(serialized_workspace, project_paths, window, cx)
1971 })
1972 })?
1973 .await
1974 .unwrap_or_default();
1975
1976 // Restore default dock state for empty workspaces
1977 // Only restore if:
1978 // 1. This is an empty workspace (no paths), AND
1979 // 2. The serialized workspace either doesn't exist or has no paths
1980 if is_empty_workspace && !serialized_workspace_has_paths {
1981 if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
1982 window
1983 .update(cx, |_, window, cx| {
1984 workspace.update(cx, |workspace, cx| {
1985 for (dock, serialized_dock) in [
1986 (&workspace.right_dock, &default_docks.right),
1987 (&workspace.left_dock, &default_docks.left),
1988 (&workspace.bottom_dock, &default_docks.bottom),
1989 ] {
1990 dock.update(cx, |dock, cx| {
1991 dock.serialized_dock = Some(serialized_dock.clone());
1992 dock.restore_state(window, cx);
1993 });
1994 }
1995 cx.notify();
1996 });
1997 })
1998 .log_err();
1999 }
2000 }
2001
2002 window
2003 .update(cx, |_, _window, cx| {
2004 workspace.update(cx, |this: &mut Workspace, cx| {
2005 this.update_history(cx);
2006 });
2007 })
2008 .log_err();
2009 Ok(OpenResult {
2010 window,
2011 workspace,
2012 opened_items,
2013 })
2014 })
2015 }
2016
2017 pub fn weak_handle(&self) -> WeakEntity<Self> {
2018 self.weak_self.clone()
2019 }
2020
2021 pub fn left_dock(&self) -> &Entity<Dock> {
2022 &self.left_dock
2023 }
2024
2025 pub fn bottom_dock(&self) -> &Entity<Dock> {
2026 &self.bottom_dock
2027 }
2028
2029 pub fn set_bottom_dock_layout(
2030 &mut self,
2031 layout: BottomDockLayout,
2032 window: &mut Window,
2033 cx: &mut Context<Self>,
2034 ) {
2035 let fs = self.project().read(cx).fs();
2036 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2037 content.workspace.bottom_dock_layout = Some(layout);
2038 });
2039
2040 cx.notify();
2041 self.serialize_workspace(window, cx);
2042 }
2043
2044 pub fn right_dock(&self) -> &Entity<Dock> {
2045 &self.right_dock
2046 }
2047
2048 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2049 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2050 }
2051
2052 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2053 let left_dock = self.left_dock.read(cx);
2054 let left_visible = left_dock.is_open();
2055 let left_active_panel = left_dock
2056 .active_panel()
2057 .map(|panel| panel.persistent_name().to_string());
2058 // `zoomed_position` is kept in sync with individual panel zoom state
2059 // by the dock code in `Dock::new` and `Dock::add_panel`.
2060 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2061
2062 let right_dock = self.right_dock.read(cx);
2063 let right_visible = right_dock.is_open();
2064 let right_active_panel = right_dock
2065 .active_panel()
2066 .map(|panel| panel.persistent_name().to_string());
2067 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2068
2069 let bottom_dock = self.bottom_dock.read(cx);
2070 let bottom_visible = bottom_dock.is_open();
2071 let bottom_active_panel = bottom_dock
2072 .active_panel()
2073 .map(|panel| panel.persistent_name().to_string());
2074 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2075
2076 DockStructure {
2077 left: DockData {
2078 visible: left_visible,
2079 active_panel: left_active_panel,
2080 zoom: left_dock_zoom,
2081 },
2082 right: DockData {
2083 visible: right_visible,
2084 active_panel: right_active_panel,
2085 zoom: right_dock_zoom,
2086 },
2087 bottom: DockData {
2088 visible: bottom_visible,
2089 active_panel: bottom_active_panel,
2090 zoom: bottom_dock_zoom,
2091 },
2092 }
2093 }
2094
2095 pub fn set_dock_structure(
2096 &self,
2097 docks: DockStructure,
2098 window: &mut Window,
2099 cx: &mut Context<Self>,
2100 ) {
2101 for (dock, data) in [
2102 (&self.left_dock, docks.left),
2103 (&self.bottom_dock, docks.bottom),
2104 (&self.right_dock, docks.right),
2105 ] {
2106 dock.update(cx, |dock, cx| {
2107 dock.serialized_dock = Some(data);
2108 dock.restore_state(window, cx);
2109 });
2110 }
2111 }
2112
2113 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2114 self.items(cx)
2115 .filter_map(|item| {
2116 let project_path = item.project_path(cx)?;
2117 self.project.read(cx).absolute_path(&project_path, cx)
2118 })
2119 .collect()
2120 }
2121
2122 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2123 match position {
2124 DockPosition::Left => &self.left_dock,
2125 DockPosition::Bottom => &self.bottom_dock,
2126 DockPosition::Right => &self.right_dock,
2127 }
2128 }
2129
2130 pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
2131 self.all_docks().into_iter().find_map(|dock| {
2132 let dock = dock.read(cx);
2133 let panel = dock.panel::<T>()?;
2134 dock.stored_panel_size_state(&panel)
2135 })
2136 }
2137
2138 pub fn persisted_panel_size_state(
2139 &self,
2140 panel_key: &'static str,
2141 cx: &App,
2142 ) -> Option<dock::PanelSizeState> {
2143 dock::Dock::load_persisted_size_state(self, panel_key, cx)
2144 }
2145
2146 pub fn persist_panel_size_state(
2147 &self,
2148 panel_key: &str,
2149 size_state: dock::PanelSizeState,
2150 cx: &mut App,
2151 ) {
2152 let Some(workspace_id) = self
2153 .database_id()
2154 .map(|id| i64::from(id).to_string())
2155 .or(self.session_id())
2156 else {
2157 return;
2158 };
2159
2160 let kvp = db::kvp::KeyValueStore::global(cx);
2161 let panel_key = panel_key.to_string();
2162 cx.background_spawn(async move {
2163 let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
2164 scope
2165 .write(
2166 format!("{workspace_id}:{panel_key}"),
2167 serde_json::to_string(&size_state)?,
2168 )
2169 .await
2170 })
2171 .detach_and_log_err(cx);
2172 }
2173
2174 pub fn set_panel_size_state<T: Panel>(
2175 &mut self,
2176 size_state: dock::PanelSizeState,
2177 window: &mut Window,
2178 cx: &mut Context<Self>,
2179 ) -> bool {
2180 let Some(panel) = self.panel::<T>(cx) else {
2181 return false;
2182 };
2183
2184 let dock = self.dock_at_position(panel.position(window, cx));
2185 let did_set = dock.update(cx, |dock, cx| {
2186 dock.set_panel_size_state(&panel, size_state, cx)
2187 });
2188
2189 if did_set {
2190 self.persist_panel_size_state(T::panel_key(), size_state, cx);
2191 }
2192
2193 did_set
2194 }
2195
2196 pub fn flexible_dock_size(
2197 &self,
2198 position: DockPosition,
2199 ratio: f32,
2200 window: &Window,
2201 cx: &App,
2202 ) -> Option<Pixels> {
2203 if position.axis() != Axis::Horizontal {
2204 return None;
2205 }
2206
2207 let available_width = self.available_width_for_horizontal_dock(position, window, cx)?;
2208 Some((available_width * ratio.clamp(0.0, 1.0)).max(RESIZE_HANDLE_SIZE))
2209 }
2210
2211 pub fn resolved_dock_panel_size(
2212 &self,
2213 dock: &Dock,
2214 panel: &dyn PanelHandle,
2215 window: &Window,
2216 cx: &App,
2217 ) -> Pixels {
2218 let size_state = dock.stored_panel_size_state(panel).unwrap_or_default();
2219 dock::resolve_panel_size(size_state, panel, dock.position(), self, window, cx)
2220 }
2221
2222 pub fn flexible_dock_ratio_for_size(
2223 &self,
2224 position: DockPosition,
2225 size: Pixels,
2226 window: &Window,
2227 cx: &App,
2228 ) -> Option<f32> {
2229 if position.axis() != Axis::Horizontal {
2230 return None;
2231 }
2232
2233 let available_width = self.available_width_for_horizontal_dock(position, window, cx)?;
2234 let available_width = available_width.max(RESIZE_HANDLE_SIZE);
2235 Some((size / available_width).clamp(0.0, 1.0))
2236 }
2237
2238 fn available_width_for_horizontal_dock(
2239 &self,
2240 position: DockPosition,
2241 window: &Window,
2242 cx: &App,
2243 ) -> Option<Pixels> {
2244 let workspace_width = self.bounds.size.width;
2245 if workspace_width <= Pixels::ZERO {
2246 return None;
2247 }
2248
2249 let opposite_position = match position {
2250 DockPosition::Left => DockPosition::Right,
2251 DockPosition::Right => DockPosition::Left,
2252 DockPosition::Bottom => return None,
2253 };
2254
2255 let opposite_width = self
2256 .dock_at_position(opposite_position)
2257 .read(cx)
2258 .stored_active_panel_size(window, cx)
2259 .unwrap_or(Pixels::ZERO);
2260
2261 Some((workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE))
2262 }
2263
2264 pub fn default_flexible_dock_ratio(&self, position: DockPosition) -> Option<f32> {
2265 if position.axis() != Axis::Horizontal {
2266 return None;
2267 }
2268
2269 let pane = self.last_active_center_pane.clone()?.upgrade()?;
2270 let pane_fraction = self.center.width_fraction_for_pane(&pane).unwrap_or(1.0);
2271 Some((pane_fraction / (1.0 + pane_fraction)).clamp(0.0, 1.0))
2272 }
2273
2274 pub fn is_edited(&self) -> bool {
2275 self.window_edited
2276 }
2277
2278 pub fn add_panel<T: Panel>(
2279 &mut self,
2280 panel: Entity<T>,
2281 window: &mut Window,
2282 cx: &mut Context<Self>,
2283 ) {
2284 let focus_handle = panel.panel_focus_handle(cx);
2285 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2286 .detach();
2287
2288 let dock_position = panel.position(window, cx);
2289 let dock = self.dock_at_position(dock_position);
2290 let any_panel = panel.to_any();
2291 let persisted_size_state =
2292 self.persisted_panel_size_state(T::panel_key(), cx)
2293 .or_else(|| {
2294 load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
2295 let state = dock::PanelSizeState {
2296 size: Some(size),
2297 flexible_size_ratio: None,
2298 };
2299 self.persist_panel_size_state(T::panel_key(), state, cx);
2300 state
2301 })
2302 });
2303
2304 dock.update(cx, |dock, cx| {
2305 let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
2306 if let Some(size_state) = persisted_size_state {
2307 dock.set_panel_size_state(&panel, size_state, cx);
2308 }
2309 index
2310 });
2311
2312 cx.emit(Event::PanelAdded(any_panel));
2313 }
2314
2315 pub fn remove_panel<T: Panel>(
2316 &mut self,
2317 panel: &Entity<T>,
2318 window: &mut Window,
2319 cx: &mut Context<Self>,
2320 ) {
2321 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2322 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2323 }
2324 }
2325
2326 pub fn status_bar(&self) -> &Entity<StatusBar> {
2327 &self.status_bar
2328 }
2329
2330 pub fn set_workspace_sidebar_open(
2331 &self,
2332 open: bool,
2333 has_notifications: bool,
2334 show_toggle: bool,
2335 cx: &mut App,
2336 ) {
2337 self.status_bar.update(cx, |status_bar, cx| {
2338 status_bar.set_workspace_sidebar_open(open, cx);
2339 status_bar.set_sidebar_has_notifications(has_notifications, cx);
2340 status_bar.set_show_sidebar_toggle(show_toggle, cx);
2341 });
2342 }
2343
2344 pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
2345 self.sidebar_focus_handle = handle;
2346 }
2347
2348 pub fn status_bar_visible(&self, cx: &App) -> bool {
2349 StatusBarSettings::get_global(cx).show
2350 }
2351
2352 pub fn app_state(&self) -> &Arc<AppState> {
2353 &self.app_state
2354 }
2355
2356 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2357 self._panels_task = Some(task);
2358 }
2359
2360 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2361 self._panels_task.take()
2362 }
2363
2364 pub fn user_store(&self) -> &Entity<UserStore> {
2365 &self.app_state.user_store
2366 }
2367
2368 pub fn project(&self) -> &Entity<Project> {
2369 &self.project
2370 }
2371
2372 pub fn path_style(&self, cx: &App) -> PathStyle {
2373 self.project.read(cx).path_style(cx)
2374 }
2375
2376 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2377 let mut history: HashMap<EntityId, usize> = HashMap::default();
2378
2379 for pane_handle in &self.panes {
2380 let pane = pane_handle.read(cx);
2381
2382 for entry in pane.activation_history() {
2383 history.insert(
2384 entry.entity_id,
2385 history
2386 .get(&entry.entity_id)
2387 .cloned()
2388 .unwrap_or(0)
2389 .max(entry.timestamp),
2390 );
2391 }
2392 }
2393
2394 history
2395 }
2396
2397 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2398 let mut recent_item: Option<Entity<T>> = None;
2399 let mut recent_timestamp = 0;
2400 for pane_handle in &self.panes {
2401 let pane = pane_handle.read(cx);
2402 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2403 pane.items().map(|item| (item.item_id(), item)).collect();
2404 for entry in pane.activation_history() {
2405 if entry.timestamp > recent_timestamp
2406 && let Some(&item) = item_map.get(&entry.entity_id)
2407 && let Some(typed_item) = item.act_as::<T>(cx)
2408 {
2409 recent_timestamp = entry.timestamp;
2410 recent_item = Some(typed_item);
2411 }
2412 }
2413 }
2414 recent_item
2415 }
2416
2417 pub fn recent_navigation_history_iter(
2418 &self,
2419 cx: &App,
2420 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2421 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2422 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2423
2424 for pane in &self.panes {
2425 let pane = pane.read(cx);
2426
2427 pane.nav_history()
2428 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2429 if let Some(fs_path) = &fs_path {
2430 abs_paths_opened
2431 .entry(fs_path.clone())
2432 .or_default()
2433 .insert(project_path.clone());
2434 }
2435 let timestamp = entry.timestamp;
2436 match history.entry(project_path) {
2437 hash_map::Entry::Occupied(mut entry) => {
2438 let (_, old_timestamp) = entry.get();
2439 if ×tamp > old_timestamp {
2440 entry.insert((fs_path, timestamp));
2441 }
2442 }
2443 hash_map::Entry::Vacant(entry) => {
2444 entry.insert((fs_path, timestamp));
2445 }
2446 }
2447 });
2448
2449 if let Some(item) = pane.active_item()
2450 && let Some(project_path) = item.project_path(cx)
2451 {
2452 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2453
2454 if let Some(fs_path) = &fs_path {
2455 abs_paths_opened
2456 .entry(fs_path.clone())
2457 .or_default()
2458 .insert(project_path.clone());
2459 }
2460
2461 history.insert(project_path, (fs_path, std::usize::MAX));
2462 }
2463 }
2464
2465 history
2466 .into_iter()
2467 .sorted_by_key(|(_, (_, order))| *order)
2468 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2469 .rev()
2470 .filter(move |(history_path, abs_path)| {
2471 let latest_project_path_opened = abs_path
2472 .as_ref()
2473 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2474 .and_then(|project_paths| {
2475 project_paths
2476 .iter()
2477 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2478 });
2479
2480 latest_project_path_opened.is_none_or(|path| path == history_path)
2481 })
2482 }
2483
2484 pub fn recent_navigation_history(
2485 &self,
2486 limit: Option<usize>,
2487 cx: &App,
2488 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2489 self.recent_navigation_history_iter(cx)
2490 .take(limit.unwrap_or(usize::MAX))
2491 .collect()
2492 }
2493
2494 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2495 for pane in &self.panes {
2496 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2497 }
2498 }
2499
2500 fn navigate_history(
2501 &mut self,
2502 pane: WeakEntity<Pane>,
2503 mode: NavigationMode,
2504 window: &mut Window,
2505 cx: &mut Context<Workspace>,
2506 ) -> Task<Result<()>> {
2507 self.navigate_history_impl(
2508 pane,
2509 mode,
2510 window,
2511 &mut |history, cx| history.pop(mode, cx),
2512 cx,
2513 )
2514 }
2515
2516 fn navigate_tag_history(
2517 &mut self,
2518 pane: WeakEntity<Pane>,
2519 mode: TagNavigationMode,
2520 window: &mut Window,
2521 cx: &mut Context<Workspace>,
2522 ) -> Task<Result<()>> {
2523 self.navigate_history_impl(
2524 pane,
2525 NavigationMode::Normal,
2526 window,
2527 &mut |history, _cx| history.pop_tag(mode),
2528 cx,
2529 )
2530 }
2531
2532 fn navigate_history_impl(
2533 &mut self,
2534 pane: WeakEntity<Pane>,
2535 mode: NavigationMode,
2536 window: &mut Window,
2537 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2538 cx: &mut Context<Workspace>,
2539 ) -> Task<Result<()>> {
2540 let to_load = if let Some(pane) = pane.upgrade() {
2541 pane.update(cx, |pane, cx| {
2542 window.focus(&pane.focus_handle(cx), cx);
2543 loop {
2544 // Retrieve the weak item handle from the history.
2545 let entry = cb(pane.nav_history_mut(), cx)?;
2546
2547 // If the item is still present in this pane, then activate it.
2548 if let Some(index) = entry
2549 .item
2550 .upgrade()
2551 .and_then(|v| pane.index_for_item(v.as_ref()))
2552 {
2553 let prev_active_item_index = pane.active_item_index();
2554 pane.nav_history_mut().set_mode(mode);
2555 pane.activate_item(index, true, true, window, cx);
2556 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2557
2558 let mut navigated = prev_active_item_index != pane.active_item_index();
2559 if let Some(data) = entry.data {
2560 navigated |= pane.active_item()?.navigate(data, window, cx);
2561 }
2562
2563 if navigated {
2564 break None;
2565 }
2566 } else {
2567 // If the item is no longer present in this pane, then retrieve its
2568 // path info in order to reopen it.
2569 break pane
2570 .nav_history()
2571 .path_for_item(entry.item.id())
2572 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2573 }
2574 }
2575 })
2576 } else {
2577 None
2578 };
2579
2580 if let Some((project_path, abs_path, entry)) = to_load {
2581 // If the item was no longer present, then load it again from its previous path, first try the local path
2582 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2583
2584 cx.spawn_in(window, async move |workspace, cx| {
2585 let open_by_project_path = open_by_project_path.await;
2586 let mut navigated = false;
2587 match open_by_project_path
2588 .with_context(|| format!("Navigating to {project_path:?}"))
2589 {
2590 Ok((project_entry_id, build_item)) => {
2591 let prev_active_item_id = pane.update(cx, |pane, _| {
2592 pane.nav_history_mut().set_mode(mode);
2593 pane.active_item().map(|p| p.item_id())
2594 })?;
2595
2596 pane.update_in(cx, |pane, window, cx| {
2597 let item = pane.open_item(
2598 project_entry_id,
2599 project_path,
2600 true,
2601 entry.is_preview,
2602 true,
2603 None,
2604 window, cx,
2605 build_item,
2606 );
2607 navigated |= Some(item.item_id()) != prev_active_item_id;
2608 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2609 if let Some(data) = entry.data {
2610 navigated |= item.navigate(data, window, cx);
2611 }
2612 })?;
2613 }
2614 Err(open_by_project_path_e) => {
2615 // Fall back to opening by abs path, in case an external file was opened and closed,
2616 // and its worktree is now dropped
2617 if let Some(abs_path) = abs_path {
2618 let prev_active_item_id = pane.update(cx, |pane, _| {
2619 pane.nav_history_mut().set_mode(mode);
2620 pane.active_item().map(|p| p.item_id())
2621 })?;
2622 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2623 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2624 })?;
2625 match open_by_abs_path
2626 .await
2627 .with_context(|| format!("Navigating to {abs_path:?}"))
2628 {
2629 Ok(item) => {
2630 pane.update_in(cx, |pane, window, cx| {
2631 navigated |= Some(item.item_id()) != prev_active_item_id;
2632 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2633 if let Some(data) = entry.data {
2634 navigated |= item.navigate(data, window, cx);
2635 }
2636 })?;
2637 }
2638 Err(open_by_abs_path_e) => {
2639 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2640 }
2641 }
2642 }
2643 }
2644 }
2645
2646 if !navigated {
2647 workspace
2648 .update_in(cx, |workspace, window, cx| {
2649 Self::navigate_history(workspace, pane, mode, window, cx)
2650 })?
2651 .await?;
2652 }
2653
2654 Ok(())
2655 })
2656 } else {
2657 Task::ready(Ok(()))
2658 }
2659 }
2660
2661 pub fn go_back(
2662 &mut self,
2663 pane: WeakEntity<Pane>,
2664 window: &mut Window,
2665 cx: &mut Context<Workspace>,
2666 ) -> Task<Result<()>> {
2667 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2668 }
2669
2670 pub fn go_forward(
2671 &mut self,
2672 pane: WeakEntity<Pane>,
2673 window: &mut Window,
2674 cx: &mut Context<Workspace>,
2675 ) -> Task<Result<()>> {
2676 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2677 }
2678
2679 pub fn reopen_closed_item(
2680 &mut self,
2681 window: &mut Window,
2682 cx: &mut Context<Workspace>,
2683 ) -> Task<Result<()>> {
2684 self.navigate_history(
2685 self.active_pane().downgrade(),
2686 NavigationMode::ReopeningClosedItem,
2687 window,
2688 cx,
2689 )
2690 }
2691
2692 pub fn client(&self) -> &Arc<Client> {
2693 &self.app_state.client
2694 }
2695
2696 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2697 self.titlebar_item = Some(item);
2698 cx.notify();
2699 }
2700
2701 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2702 self.on_prompt_for_new_path = Some(prompt)
2703 }
2704
2705 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2706 self.on_prompt_for_open_path = Some(prompt)
2707 }
2708
2709 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2710 self.terminal_provider = Some(Box::new(provider));
2711 }
2712
2713 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2714 self.debugger_provider = Some(Arc::new(provider));
2715 }
2716
2717 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2718 self.debugger_provider.clone()
2719 }
2720
2721 pub fn prompt_for_open_path(
2722 &mut self,
2723 path_prompt_options: PathPromptOptions,
2724 lister: DirectoryLister,
2725 window: &mut Window,
2726 cx: &mut Context<Self>,
2727 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2728 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2729 let prompt = self.on_prompt_for_open_path.take().unwrap();
2730 let rx = prompt(self, lister, window, cx);
2731 self.on_prompt_for_open_path = Some(prompt);
2732 rx
2733 } else {
2734 let (tx, rx) = oneshot::channel();
2735 let abs_path = cx.prompt_for_paths(path_prompt_options);
2736
2737 cx.spawn_in(window, async move |workspace, cx| {
2738 let Ok(result) = abs_path.await else {
2739 return Ok(());
2740 };
2741
2742 match result {
2743 Ok(result) => {
2744 tx.send(result).ok();
2745 }
2746 Err(err) => {
2747 let rx = workspace.update_in(cx, |workspace, window, cx| {
2748 workspace.show_portal_error(err.to_string(), cx);
2749 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2750 let rx = prompt(workspace, lister, window, cx);
2751 workspace.on_prompt_for_open_path = Some(prompt);
2752 rx
2753 })?;
2754 if let Ok(path) = rx.await {
2755 tx.send(path).ok();
2756 }
2757 }
2758 };
2759 anyhow::Ok(())
2760 })
2761 .detach();
2762
2763 rx
2764 }
2765 }
2766
2767 pub fn prompt_for_new_path(
2768 &mut self,
2769 lister: DirectoryLister,
2770 suggested_name: Option<String>,
2771 window: &mut Window,
2772 cx: &mut Context<Self>,
2773 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2774 if self.project.read(cx).is_via_collab()
2775 || self.project.read(cx).is_via_remote_server()
2776 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2777 {
2778 let prompt = self.on_prompt_for_new_path.take().unwrap();
2779 let rx = prompt(self, lister, suggested_name, window, cx);
2780 self.on_prompt_for_new_path = Some(prompt);
2781 return rx;
2782 }
2783
2784 let (tx, rx) = oneshot::channel();
2785 cx.spawn_in(window, async move |workspace, cx| {
2786 let abs_path = workspace.update(cx, |workspace, cx| {
2787 let relative_to = workspace
2788 .most_recent_active_path(cx)
2789 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2790 .or_else(|| {
2791 let project = workspace.project.read(cx);
2792 project.visible_worktrees(cx).find_map(|worktree| {
2793 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2794 })
2795 })
2796 .or_else(std::env::home_dir)
2797 .unwrap_or_else(|| PathBuf::from(""));
2798 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2799 })?;
2800 let abs_path = match abs_path.await? {
2801 Ok(path) => path,
2802 Err(err) => {
2803 let rx = workspace.update_in(cx, |workspace, window, cx| {
2804 workspace.show_portal_error(err.to_string(), cx);
2805
2806 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2807 let rx = prompt(workspace, lister, suggested_name, window, cx);
2808 workspace.on_prompt_for_new_path = Some(prompt);
2809 rx
2810 })?;
2811 if let Ok(path) = rx.await {
2812 tx.send(path).ok();
2813 }
2814 return anyhow::Ok(());
2815 }
2816 };
2817
2818 tx.send(abs_path.map(|path| vec![path])).ok();
2819 anyhow::Ok(())
2820 })
2821 .detach();
2822
2823 rx
2824 }
2825
2826 pub fn titlebar_item(&self) -> Option<AnyView> {
2827 self.titlebar_item.clone()
2828 }
2829
2830 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2831 /// When set, git-related operations should use this worktree instead of deriving
2832 /// the active worktree from the focused file.
2833 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2834 self.active_worktree_override
2835 }
2836
2837 pub fn set_active_worktree_override(
2838 &mut self,
2839 worktree_id: Option<WorktreeId>,
2840 cx: &mut Context<Self>,
2841 ) {
2842 self.active_worktree_override = worktree_id;
2843 cx.notify();
2844 }
2845
2846 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2847 self.active_worktree_override = None;
2848 cx.notify();
2849 }
2850
2851 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2852 ///
2853 /// If the given workspace has a local project, then it will be passed
2854 /// to the callback. Otherwise, a new empty window will be created.
2855 pub fn with_local_workspace<T, F>(
2856 &mut self,
2857 window: &mut Window,
2858 cx: &mut Context<Self>,
2859 callback: F,
2860 ) -> Task<Result<T>>
2861 where
2862 T: 'static,
2863 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2864 {
2865 if self.project.read(cx).is_local() {
2866 Task::ready(Ok(callback(self, window, cx)))
2867 } else {
2868 let env = self.project.read(cx).cli_environment(cx);
2869 let task = Self::new_local(
2870 Vec::new(),
2871 self.app_state.clone(),
2872 None,
2873 env,
2874 None,
2875 true,
2876 cx,
2877 );
2878 cx.spawn_in(window, async move |_vh, cx| {
2879 let OpenResult {
2880 window: multi_workspace_window,
2881 ..
2882 } = task.await?;
2883 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2884 let workspace = multi_workspace.workspace().clone();
2885 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2886 })
2887 })
2888 }
2889 }
2890
2891 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2892 ///
2893 /// If the given workspace has a local project, then it will be passed
2894 /// to the callback. Otherwise, a new empty window will be created.
2895 pub fn with_local_or_wsl_workspace<T, F>(
2896 &mut self,
2897 window: &mut Window,
2898 cx: &mut Context<Self>,
2899 callback: F,
2900 ) -> Task<Result<T>>
2901 where
2902 T: 'static,
2903 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2904 {
2905 let project = self.project.read(cx);
2906 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
2907 Task::ready(Ok(callback(self, window, cx)))
2908 } else {
2909 let env = self.project.read(cx).cli_environment(cx);
2910 let task = Self::new_local(
2911 Vec::new(),
2912 self.app_state.clone(),
2913 None,
2914 env,
2915 None,
2916 true,
2917 cx,
2918 );
2919 cx.spawn_in(window, async move |_vh, cx| {
2920 let OpenResult {
2921 window: multi_workspace_window,
2922 ..
2923 } = task.await?;
2924 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2925 let workspace = multi_workspace.workspace().clone();
2926 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2927 })
2928 })
2929 }
2930 }
2931
2932 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2933 self.project.read(cx).worktrees(cx)
2934 }
2935
2936 pub fn visible_worktrees<'a>(
2937 &self,
2938 cx: &'a App,
2939 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2940 self.project.read(cx).visible_worktrees(cx)
2941 }
2942
2943 #[cfg(any(test, feature = "test-support"))]
2944 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
2945 let futures = self
2946 .worktrees(cx)
2947 .filter_map(|worktree| worktree.read(cx).as_local())
2948 .map(|worktree| worktree.scan_complete())
2949 .collect::<Vec<_>>();
2950 async move {
2951 for future in futures {
2952 future.await;
2953 }
2954 }
2955 }
2956
2957 pub fn close_global(cx: &mut App) {
2958 cx.defer(|cx| {
2959 cx.windows().iter().find(|window| {
2960 window
2961 .update(cx, |_, window, _| {
2962 if window.is_window_active() {
2963 //This can only get called when the window's project connection has been lost
2964 //so we don't need to prompt the user for anything and instead just close the window
2965 window.remove_window();
2966 true
2967 } else {
2968 false
2969 }
2970 })
2971 .unwrap_or(false)
2972 });
2973 });
2974 }
2975
2976 pub fn move_focused_panel_to_next_position(
2977 &mut self,
2978 _: &MoveFocusedPanelToNextPosition,
2979 window: &mut Window,
2980 cx: &mut Context<Self>,
2981 ) {
2982 let docks = self.all_docks();
2983 let active_dock = docks
2984 .into_iter()
2985 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
2986
2987 if let Some(dock) = active_dock {
2988 dock.update(cx, |dock, cx| {
2989 let active_panel = dock
2990 .active_panel()
2991 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
2992
2993 if let Some(panel) = active_panel {
2994 panel.move_to_next_position(window, cx);
2995 }
2996 })
2997 }
2998 }
2999
3000 pub fn prepare_to_close(
3001 &mut self,
3002 close_intent: CloseIntent,
3003 window: &mut Window,
3004 cx: &mut Context<Self>,
3005 ) -> Task<Result<bool>> {
3006 let active_call = self.active_global_call();
3007
3008 cx.spawn_in(window, async move |this, cx| {
3009 this.update(cx, |this, _| {
3010 if close_intent == CloseIntent::CloseWindow {
3011 this.removing = true;
3012 }
3013 })?;
3014
3015 let workspace_count = cx.update(|_window, cx| {
3016 cx.windows()
3017 .iter()
3018 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
3019 .count()
3020 })?;
3021
3022 #[cfg(target_os = "macos")]
3023 let save_last_workspace = false;
3024
3025 // On Linux and Windows, closing the last window should restore the last workspace.
3026 #[cfg(not(target_os = "macos"))]
3027 let save_last_workspace = {
3028 let remaining_workspaces = cx.update(|_window, cx| {
3029 cx.windows()
3030 .iter()
3031 .filter_map(|window| window.downcast::<MultiWorkspace>())
3032 .filter_map(|multi_workspace| {
3033 multi_workspace
3034 .update(cx, |multi_workspace, _, cx| {
3035 multi_workspace.workspace().read(cx).removing
3036 })
3037 .ok()
3038 })
3039 .filter(|removing| !removing)
3040 .count()
3041 })?;
3042
3043 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
3044 };
3045
3046 if let Some(active_call) = active_call
3047 && workspace_count == 1
3048 && cx
3049 .update(|_window, cx| active_call.0.is_in_room(cx))
3050 .unwrap_or(false)
3051 {
3052 if close_intent == CloseIntent::CloseWindow {
3053 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
3054 let answer = cx.update(|window, cx| {
3055 window.prompt(
3056 PromptLevel::Warning,
3057 "Do you want to leave the current call?",
3058 None,
3059 &["Close window and hang up", "Cancel"],
3060 cx,
3061 )
3062 })?;
3063
3064 if answer.await.log_err() == Some(1) {
3065 return anyhow::Ok(false);
3066 } else {
3067 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
3068 task.await.log_err();
3069 }
3070 }
3071 }
3072 if close_intent == CloseIntent::ReplaceWindow {
3073 _ = cx.update(|_window, cx| {
3074 let multi_workspace = cx
3075 .windows()
3076 .iter()
3077 .filter_map(|window| window.downcast::<MultiWorkspace>())
3078 .next()
3079 .unwrap();
3080 let project = multi_workspace
3081 .read(cx)?
3082 .workspace()
3083 .read(cx)
3084 .project
3085 .clone();
3086 if project.read(cx).is_shared() {
3087 active_call.0.unshare_project(project, cx)?;
3088 }
3089 Ok::<_, anyhow::Error>(())
3090 });
3091 }
3092 }
3093
3094 let save_result = this
3095 .update_in(cx, |this, window, cx| {
3096 this.save_all_internal(SaveIntent::Close, window, cx)
3097 })?
3098 .await;
3099
3100 // If we're not quitting, but closing, we remove the workspace from
3101 // the current session.
3102 if close_intent != CloseIntent::Quit
3103 && !save_last_workspace
3104 && save_result.as_ref().is_ok_and(|&res| res)
3105 {
3106 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
3107 .await;
3108 }
3109
3110 save_result
3111 })
3112 }
3113
3114 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
3115 self.save_all_internal(
3116 action.save_intent.unwrap_or(SaveIntent::SaveAll),
3117 window,
3118 cx,
3119 )
3120 .detach_and_log_err(cx);
3121 }
3122
3123 fn send_keystrokes(
3124 &mut self,
3125 action: &SendKeystrokes,
3126 window: &mut Window,
3127 cx: &mut Context<Self>,
3128 ) {
3129 let keystrokes: Vec<Keystroke> = action
3130 .0
3131 .split(' ')
3132 .flat_map(|k| Keystroke::parse(k).log_err())
3133 .map(|k| {
3134 cx.keyboard_mapper()
3135 .map_key_equivalent(k, false)
3136 .inner()
3137 .clone()
3138 })
3139 .collect();
3140 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
3141 }
3142
3143 pub fn send_keystrokes_impl(
3144 &mut self,
3145 keystrokes: Vec<Keystroke>,
3146 window: &mut Window,
3147 cx: &mut Context<Self>,
3148 ) -> Shared<Task<()>> {
3149 let mut state = self.dispatching_keystrokes.borrow_mut();
3150 if !state.dispatched.insert(keystrokes.clone()) {
3151 cx.propagate();
3152 return state.task.clone().unwrap();
3153 }
3154
3155 state.queue.extend(keystrokes);
3156
3157 let keystrokes = self.dispatching_keystrokes.clone();
3158 if state.task.is_none() {
3159 state.task = Some(
3160 window
3161 .spawn(cx, async move |cx| {
3162 // limit to 100 keystrokes to avoid infinite recursion.
3163 for _ in 0..100 {
3164 let keystroke = {
3165 let mut state = keystrokes.borrow_mut();
3166 let Some(keystroke) = state.queue.pop_front() else {
3167 state.dispatched.clear();
3168 state.task.take();
3169 return;
3170 };
3171 keystroke
3172 };
3173 cx.update(|window, cx| {
3174 let focused = window.focused(cx);
3175 window.dispatch_keystroke(keystroke.clone(), cx);
3176 if window.focused(cx) != focused {
3177 // dispatch_keystroke may cause the focus to change.
3178 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
3179 // And we need that to happen before the next keystroke to keep vim mode happy...
3180 // (Note that the tests always do this implicitly, so you must manually test with something like:
3181 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
3182 // )
3183 window.draw(cx).clear();
3184 }
3185 })
3186 .ok();
3187
3188 // Yield between synthetic keystrokes so deferred focus and
3189 // other effects can settle before dispatching the next key.
3190 yield_now().await;
3191 }
3192
3193 *keystrokes.borrow_mut() = Default::default();
3194 log::error!("over 100 keystrokes passed to send_keystrokes");
3195 })
3196 .shared(),
3197 );
3198 }
3199 state.task.clone().unwrap()
3200 }
3201
3202 fn save_all_internal(
3203 &mut self,
3204 mut save_intent: SaveIntent,
3205 window: &mut Window,
3206 cx: &mut Context<Self>,
3207 ) -> Task<Result<bool>> {
3208 if self.project.read(cx).is_disconnected(cx) {
3209 return Task::ready(Ok(true));
3210 }
3211 let dirty_items = self
3212 .panes
3213 .iter()
3214 .flat_map(|pane| {
3215 pane.read(cx).items().filter_map(|item| {
3216 if item.is_dirty(cx) {
3217 item.tab_content_text(0, cx);
3218 Some((pane.downgrade(), item.boxed_clone()))
3219 } else {
3220 None
3221 }
3222 })
3223 })
3224 .collect::<Vec<_>>();
3225
3226 let project = self.project.clone();
3227 cx.spawn_in(window, async move |workspace, cx| {
3228 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3229 let (serialize_tasks, remaining_dirty_items) =
3230 workspace.update_in(cx, |workspace, window, cx| {
3231 let mut remaining_dirty_items = Vec::new();
3232 let mut serialize_tasks = Vec::new();
3233 for (pane, item) in dirty_items {
3234 if let Some(task) = item
3235 .to_serializable_item_handle(cx)
3236 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3237 {
3238 serialize_tasks.push(task);
3239 } else {
3240 remaining_dirty_items.push((pane, item));
3241 }
3242 }
3243 (serialize_tasks, remaining_dirty_items)
3244 })?;
3245
3246 futures::future::try_join_all(serialize_tasks).await?;
3247
3248 if !remaining_dirty_items.is_empty() {
3249 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3250 }
3251
3252 if remaining_dirty_items.len() > 1 {
3253 let answer = workspace.update_in(cx, |_, window, cx| {
3254 let detail = Pane::file_names_for_prompt(
3255 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3256 cx,
3257 );
3258 window.prompt(
3259 PromptLevel::Warning,
3260 "Do you want to save all changes in the following files?",
3261 Some(&detail),
3262 &["Save all", "Discard all", "Cancel"],
3263 cx,
3264 )
3265 })?;
3266 match answer.await.log_err() {
3267 Some(0) => save_intent = SaveIntent::SaveAll,
3268 Some(1) => save_intent = SaveIntent::Skip,
3269 Some(2) => return Ok(false),
3270 _ => {}
3271 }
3272 }
3273
3274 remaining_dirty_items
3275 } else {
3276 dirty_items
3277 };
3278
3279 for (pane, item) in dirty_items {
3280 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3281 (
3282 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3283 item.project_entry_ids(cx),
3284 )
3285 })?;
3286 if (singleton || !project_entry_ids.is_empty())
3287 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3288 {
3289 return Ok(false);
3290 }
3291 }
3292 Ok(true)
3293 })
3294 }
3295
3296 pub fn open_workspace_for_paths(
3297 &mut self,
3298 replace_current_window: bool,
3299 paths: Vec<PathBuf>,
3300 window: &mut Window,
3301 cx: &mut Context<Self>,
3302 ) -> Task<Result<Entity<Workspace>>> {
3303 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
3304 let is_remote = self.project.read(cx).is_via_collab();
3305 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3306 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3307
3308 let window_to_replace = if replace_current_window {
3309 window_handle
3310 } else if is_remote || has_worktree || has_dirty_items {
3311 None
3312 } else {
3313 window_handle
3314 };
3315 let app_state = self.app_state.clone();
3316
3317 cx.spawn(async move |_, cx| {
3318 let OpenResult { workspace, .. } = cx
3319 .update(|cx| {
3320 open_paths(
3321 &paths,
3322 app_state,
3323 OpenOptions {
3324 replace_window: window_to_replace,
3325 ..Default::default()
3326 },
3327 cx,
3328 )
3329 })
3330 .await?;
3331 Ok(workspace)
3332 })
3333 }
3334
3335 #[allow(clippy::type_complexity)]
3336 pub fn open_paths(
3337 &mut self,
3338 mut abs_paths: Vec<PathBuf>,
3339 options: OpenOptions,
3340 pane: Option<WeakEntity<Pane>>,
3341 window: &mut Window,
3342 cx: &mut Context<Self>,
3343 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3344 let fs = self.app_state.fs.clone();
3345
3346 let caller_ordered_abs_paths = abs_paths.clone();
3347
3348 // Sort the paths to ensure we add worktrees for parents before their children.
3349 abs_paths.sort_unstable();
3350 cx.spawn_in(window, async move |this, cx| {
3351 let mut tasks = Vec::with_capacity(abs_paths.len());
3352
3353 for abs_path in &abs_paths {
3354 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3355 OpenVisible::All => Some(true),
3356 OpenVisible::None => Some(false),
3357 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3358 Some(Some(metadata)) => Some(!metadata.is_dir),
3359 Some(None) => Some(true),
3360 None => None,
3361 },
3362 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3363 Some(Some(metadata)) => Some(metadata.is_dir),
3364 Some(None) => Some(false),
3365 None => None,
3366 },
3367 };
3368 let project_path = match visible {
3369 Some(visible) => match this
3370 .update(cx, |this, cx| {
3371 Workspace::project_path_for_path(
3372 this.project.clone(),
3373 abs_path,
3374 visible,
3375 cx,
3376 )
3377 })
3378 .log_err()
3379 {
3380 Some(project_path) => project_path.await.log_err(),
3381 None => None,
3382 },
3383 None => None,
3384 };
3385
3386 let this = this.clone();
3387 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3388 let fs = fs.clone();
3389 let pane = pane.clone();
3390 let task = cx.spawn(async move |cx| {
3391 let (_worktree, project_path) = project_path?;
3392 if fs.is_dir(&abs_path).await {
3393 // Opening a directory should not race to update the active entry.
3394 // We'll select/reveal a deterministic final entry after all paths finish opening.
3395 None
3396 } else {
3397 Some(
3398 this.update_in(cx, |this, window, cx| {
3399 this.open_path(
3400 project_path,
3401 pane,
3402 options.focus.unwrap_or(true),
3403 window,
3404 cx,
3405 )
3406 })
3407 .ok()?
3408 .await,
3409 )
3410 }
3411 });
3412 tasks.push(task);
3413 }
3414
3415 let results = futures::future::join_all(tasks).await;
3416
3417 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3418 let mut winner: Option<(PathBuf, bool)> = None;
3419 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3420 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3421 if !metadata.is_dir {
3422 winner = Some((abs_path, false));
3423 break;
3424 }
3425 if winner.is_none() {
3426 winner = Some((abs_path, true));
3427 }
3428 } else if winner.is_none() {
3429 winner = Some((abs_path, false));
3430 }
3431 }
3432
3433 // Compute the winner entry id on the foreground thread and emit once, after all
3434 // paths finish opening. This avoids races between concurrently-opening paths
3435 // (directories in particular) and makes the resulting project panel selection
3436 // deterministic.
3437 if let Some((winner_abs_path, winner_is_dir)) = winner {
3438 'emit_winner: {
3439 let winner_abs_path: Arc<Path> =
3440 SanitizedPath::new(&winner_abs_path).as_path().into();
3441
3442 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3443 OpenVisible::All => true,
3444 OpenVisible::None => false,
3445 OpenVisible::OnlyFiles => !winner_is_dir,
3446 OpenVisible::OnlyDirectories => winner_is_dir,
3447 };
3448
3449 let Some(worktree_task) = this
3450 .update(cx, |workspace, cx| {
3451 workspace.project.update(cx, |project, cx| {
3452 project.find_or_create_worktree(
3453 winner_abs_path.as_ref(),
3454 visible,
3455 cx,
3456 )
3457 })
3458 })
3459 .ok()
3460 else {
3461 break 'emit_winner;
3462 };
3463
3464 let Ok((worktree, _)) = worktree_task.await else {
3465 break 'emit_winner;
3466 };
3467
3468 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3469 let worktree = worktree.read(cx);
3470 let worktree_abs_path = worktree.abs_path();
3471 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3472 worktree.root_entry()
3473 } else {
3474 winner_abs_path
3475 .strip_prefix(worktree_abs_path.as_ref())
3476 .ok()
3477 .and_then(|relative_path| {
3478 let relative_path =
3479 RelPath::new(relative_path, PathStyle::local())
3480 .log_err()?;
3481 worktree.entry_for_path(&relative_path)
3482 })
3483 }?;
3484 Some(entry.id)
3485 }) else {
3486 break 'emit_winner;
3487 };
3488
3489 this.update(cx, |workspace, cx| {
3490 workspace.project.update(cx, |_, cx| {
3491 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3492 });
3493 })
3494 .ok();
3495 }
3496 }
3497
3498 results
3499 })
3500 }
3501
3502 pub fn open_resolved_path(
3503 &mut self,
3504 path: ResolvedPath,
3505 window: &mut Window,
3506 cx: &mut Context<Self>,
3507 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3508 match path {
3509 ResolvedPath::ProjectPath { project_path, .. } => {
3510 self.open_path(project_path, None, true, window, cx)
3511 }
3512 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3513 PathBuf::from(path),
3514 OpenOptions {
3515 visible: Some(OpenVisible::None),
3516 ..Default::default()
3517 },
3518 window,
3519 cx,
3520 ),
3521 }
3522 }
3523
3524 pub fn absolute_path_of_worktree(
3525 &self,
3526 worktree_id: WorktreeId,
3527 cx: &mut Context<Self>,
3528 ) -> Option<PathBuf> {
3529 self.project
3530 .read(cx)
3531 .worktree_for_id(worktree_id, cx)
3532 // TODO: use `abs_path` or `root_dir`
3533 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3534 }
3535
3536 pub fn add_folder_to_project(
3537 &mut self,
3538 _: &AddFolderToProject,
3539 window: &mut Window,
3540 cx: &mut Context<Self>,
3541 ) {
3542 let project = self.project.read(cx);
3543 if project.is_via_collab() {
3544 self.show_error(
3545 &anyhow!("You cannot add folders to someone else's project"),
3546 cx,
3547 );
3548 return;
3549 }
3550 let paths = self.prompt_for_open_path(
3551 PathPromptOptions {
3552 files: false,
3553 directories: true,
3554 multiple: true,
3555 prompt: None,
3556 },
3557 DirectoryLister::Project(self.project.clone()),
3558 window,
3559 cx,
3560 );
3561 cx.spawn_in(window, async move |this, cx| {
3562 if let Some(paths) = paths.await.log_err().flatten() {
3563 let results = this
3564 .update_in(cx, |this, window, cx| {
3565 this.open_paths(
3566 paths,
3567 OpenOptions {
3568 visible: Some(OpenVisible::All),
3569 ..Default::default()
3570 },
3571 None,
3572 window,
3573 cx,
3574 )
3575 })?
3576 .await;
3577 for result in results.into_iter().flatten() {
3578 result.log_err();
3579 }
3580 }
3581 anyhow::Ok(())
3582 })
3583 .detach_and_log_err(cx);
3584 }
3585
3586 pub fn project_path_for_path(
3587 project: Entity<Project>,
3588 abs_path: &Path,
3589 visible: bool,
3590 cx: &mut App,
3591 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3592 let entry = project.update(cx, |project, cx| {
3593 project.find_or_create_worktree(abs_path, visible, cx)
3594 });
3595 cx.spawn(async move |cx| {
3596 let (worktree, path) = entry.await?;
3597 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3598 Ok((worktree, ProjectPath { worktree_id, path }))
3599 })
3600 }
3601
3602 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3603 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3604 }
3605
3606 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3607 self.items_of_type(cx).max_by_key(|item| item.item_id())
3608 }
3609
3610 pub fn items_of_type<'a, T: Item>(
3611 &'a self,
3612 cx: &'a App,
3613 ) -> impl 'a + Iterator<Item = Entity<T>> {
3614 self.panes
3615 .iter()
3616 .flat_map(|pane| pane.read(cx).items_of_type())
3617 }
3618
3619 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3620 self.active_pane().read(cx).active_item()
3621 }
3622
3623 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3624 let item = self.active_item(cx)?;
3625 item.to_any_view().downcast::<I>().ok()
3626 }
3627
3628 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3629 self.active_item(cx).and_then(|item| item.project_path(cx))
3630 }
3631
3632 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3633 self.recent_navigation_history_iter(cx)
3634 .filter_map(|(path, abs_path)| {
3635 let worktree = self
3636 .project
3637 .read(cx)
3638 .worktree_for_id(path.worktree_id, cx)?;
3639 if worktree.read(cx).is_visible() {
3640 abs_path
3641 } else {
3642 None
3643 }
3644 })
3645 .next()
3646 }
3647
3648 pub fn save_active_item(
3649 &mut self,
3650 save_intent: SaveIntent,
3651 window: &mut Window,
3652 cx: &mut App,
3653 ) -> Task<Result<()>> {
3654 let project = self.project.clone();
3655 let pane = self.active_pane();
3656 let item = pane.read(cx).active_item();
3657 let pane = pane.downgrade();
3658
3659 window.spawn(cx, async move |cx| {
3660 if let Some(item) = item {
3661 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3662 .await
3663 .map(|_| ())
3664 } else {
3665 Ok(())
3666 }
3667 })
3668 }
3669
3670 pub fn close_inactive_items_and_panes(
3671 &mut self,
3672 action: &CloseInactiveTabsAndPanes,
3673 window: &mut Window,
3674 cx: &mut Context<Self>,
3675 ) {
3676 if let Some(task) = self.close_all_internal(
3677 true,
3678 action.save_intent.unwrap_or(SaveIntent::Close),
3679 window,
3680 cx,
3681 ) {
3682 task.detach_and_log_err(cx)
3683 }
3684 }
3685
3686 pub fn close_all_items_and_panes(
3687 &mut self,
3688 action: &CloseAllItemsAndPanes,
3689 window: &mut Window,
3690 cx: &mut Context<Self>,
3691 ) {
3692 if let Some(task) = self.close_all_internal(
3693 false,
3694 action.save_intent.unwrap_or(SaveIntent::Close),
3695 window,
3696 cx,
3697 ) {
3698 task.detach_and_log_err(cx)
3699 }
3700 }
3701
3702 /// Closes the active item across all panes.
3703 pub fn close_item_in_all_panes(
3704 &mut self,
3705 action: &CloseItemInAllPanes,
3706 window: &mut Window,
3707 cx: &mut Context<Self>,
3708 ) {
3709 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3710 return;
3711 };
3712
3713 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3714 let close_pinned = action.close_pinned;
3715
3716 if let Some(project_path) = active_item.project_path(cx) {
3717 self.close_items_with_project_path(
3718 &project_path,
3719 save_intent,
3720 close_pinned,
3721 window,
3722 cx,
3723 );
3724 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3725 let item_id = active_item.item_id();
3726 self.active_pane().update(cx, |pane, cx| {
3727 pane.close_item_by_id(item_id, save_intent, window, cx)
3728 .detach_and_log_err(cx);
3729 });
3730 }
3731 }
3732
3733 /// Closes all items with the given project path across all panes.
3734 pub fn close_items_with_project_path(
3735 &mut self,
3736 project_path: &ProjectPath,
3737 save_intent: SaveIntent,
3738 close_pinned: bool,
3739 window: &mut Window,
3740 cx: &mut Context<Self>,
3741 ) {
3742 let panes = self.panes().to_vec();
3743 for pane in panes {
3744 pane.update(cx, |pane, cx| {
3745 pane.close_items_for_project_path(
3746 project_path,
3747 save_intent,
3748 close_pinned,
3749 window,
3750 cx,
3751 )
3752 .detach_and_log_err(cx);
3753 });
3754 }
3755 }
3756
3757 fn close_all_internal(
3758 &mut self,
3759 retain_active_pane: bool,
3760 save_intent: SaveIntent,
3761 window: &mut Window,
3762 cx: &mut Context<Self>,
3763 ) -> Option<Task<Result<()>>> {
3764 let current_pane = self.active_pane();
3765
3766 let mut tasks = Vec::new();
3767
3768 if retain_active_pane {
3769 let current_pane_close = current_pane.update(cx, |pane, cx| {
3770 pane.close_other_items(
3771 &CloseOtherItems {
3772 save_intent: None,
3773 close_pinned: false,
3774 },
3775 None,
3776 window,
3777 cx,
3778 )
3779 });
3780
3781 tasks.push(current_pane_close);
3782 }
3783
3784 for pane in self.panes() {
3785 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3786 continue;
3787 }
3788
3789 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3790 pane.close_all_items(
3791 &CloseAllItems {
3792 save_intent: Some(save_intent),
3793 close_pinned: false,
3794 },
3795 window,
3796 cx,
3797 )
3798 });
3799
3800 tasks.push(close_pane_items)
3801 }
3802
3803 if tasks.is_empty() {
3804 None
3805 } else {
3806 Some(cx.spawn_in(window, async move |_, _| {
3807 for task in tasks {
3808 task.await?
3809 }
3810 Ok(())
3811 }))
3812 }
3813 }
3814
3815 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3816 self.dock_at_position(position).read(cx).is_open()
3817 }
3818
3819 pub fn toggle_dock(
3820 &mut self,
3821 dock_side: DockPosition,
3822 window: &mut Window,
3823 cx: &mut Context<Self>,
3824 ) {
3825 let mut focus_center = false;
3826 let mut reveal_dock = false;
3827
3828 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3829 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3830
3831 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3832 telemetry::event!(
3833 "Panel Button Clicked",
3834 name = panel.persistent_name(),
3835 toggle_state = !was_visible
3836 );
3837 }
3838 if was_visible {
3839 self.save_open_dock_positions(cx);
3840 }
3841
3842 let dock = self.dock_at_position(dock_side);
3843 dock.update(cx, |dock, cx| {
3844 dock.set_open(!was_visible, window, cx);
3845
3846 if dock.active_panel().is_none() {
3847 let Some(panel_ix) = dock
3848 .first_enabled_panel_idx(cx)
3849 .log_with_level(log::Level::Info)
3850 else {
3851 return;
3852 };
3853 dock.activate_panel(panel_ix, window, cx);
3854 }
3855
3856 if let Some(active_panel) = dock.active_panel() {
3857 if was_visible {
3858 if active_panel
3859 .panel_focus_handle(cx)
3860 .contains_focused(window, cx)
3861 {
3862 focus_center = true;
3863 }
3864 } else {
3865 let focus_handle = &active_panel.panel_focus_handle(cx);
3866 window.focus(focus_handle, cx);
3867 reveal_dock = true;
3868 }
3869 }
3870 });
3871
3872 if reveal_dock {
3873 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3874 }
3875
3876 if focus_center {
3877 self.active_pane
3878 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3879 }
3880
3881 cx.notify();
3882 self.serialize_workspace(window, cx);
3883 }
3884
3885 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3886 self.all_docks().into_iter().find(|&dock| {
3887 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3888 })
3889 }
3890
3891 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3892 if let Some(dock) = self.active_dock(window, cx).cloned() {
3893 self.save_open_dock_positions(cx);
3894 dock.update(cx, |dock, cx| {
3895 dock.set_open(false, window, cx);
3896 });
3897 return true;
3898 }
3899 false
3900 }
3901
3902 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3903 self.save_open_dock_positions(cx);
3904 for dock in self.all_docks() {
3905 dock.update(cx, |dock, cx| {
3906 dock.set_open(false, window, cx);
3907 });
3908 }
3909
3910 cx.focus_self(window);
3911 cx.notify();
3912 self.serialize_workspace(window, cx);
3913 }
3914
3915 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
3916 self.all_docks()
3917 .into_iter()
3918 .filter_map(|dock| {
3919 let dock_ref = dock.read(cx);
3920 if dock_ref.is_open() {
3921 Some(dock_ref.position())
3922 } else {
3923 None
3924 }
3925 })
3926 .collect()
3927 }
3928
3929 /// Saves the positions of currently open docks.
3930 ///
3931 /// Updates `last_open_dock_positions` with positions of all currently open
3932 /// docks, to later be restored by the 'Toggle All Docks' action.
3933 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
3934 let open_dock_positions = self.get_open_dock_positions(cx);
3935 if !open_dock_positions.is_empty() {
3936 self.last_open_dock_positions = open_dock_positions;
3937 }
3938 }
3939
3940 /// Toggles all docks between open and closed states.
3941 ///
3942 /// If any docks are open, closes all and remembers their positions. If all
3943 /// docks are closed, restores the last remembered dock configuration.
3944 fn toggle_all_docks(
3945 &mut self,
3946 _: &ToggleAllDocks,
3947 window: &mut Window,
3948 cx: &mut Context<Self>,
3949 ) {
3950 let open_dock_positions = self.get_open_dock_positions(cx);
3951
3952 if !open_dock_positions.is_empty() {
3953 self.close_all_docks(window, cx);
3954 } else if !self.last_open_dock_positions.is_empty() {
3955 self.restore_last_open_docks(window, cx);
3956 }
3957 }
3958
3959 /// Reopens docks from the most recently remembered configuration.
3960 ///
3961 /// Opens all docks whose positions are stored in `last_open_dock_positions`
3962 /// and clears the stored positions.
3963 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3964 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
3965
3966 for position in positions_to_open {
3967 let dock = self.dock_at_position(position);
3968 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
3969 }
3970
3971 cx.focus_self(window);
3972 cx.notify();
3973 self.serialize_workspace(window, cx);
3974 }
3975
3976 /// Transfer focus to the panel of the given type.
3977 pub fn focus_panel<T: Panel>(
3978 &mut self,
3979 window: &mut Window,
3980 cx: &mut Context<Self>,
3981 ) -> Option<Entity<T>> {
3982 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
3983 panel.to_any().downcast().ok()
3984 }
3985
3986 /// Focus the panel of the given type if it isn't already focused. If it is
3987 /// already focused, then transfer focus back to the workspace center.
3988 /// When the `close_panel_on_toggle` setting is enabled, also closes the
3989 /// panel when transferring focus back to the center.
3990 pub fn toggle_panel_focus<T: Panel>(
3991 &mut self,
3992 window: &mut Window,
3993 cx: &mut Context<Self>,
3994 ) -> bool {
3995 let mut did_focus_panel = false;
3996 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
3997 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
3998 did_focus_panel
3999 });
4000
4001 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
4002 self.close_panel::<T>(window, cx);
4003 }
4004
4005 telemetry::event!(
4006 "Panel Button Clicked",
4007 name = T::persistent_name(),
4008 toggle_state = did_focus_panel
4009 );
4010
4011 did_focus_panel
4012 }
4013
4014 pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4015 if let Some(item) = self.active_item(cx) {
4016 item.item_focus_handle(cx).focus(window, cx);
4017 } else {
4018 log::error!("Could not find a focus target when switching focus to the center panes",);
4019 }
4020 }
4021
4022 pub fn activate_panel_for_proto_id(
4023 &mut self,
4024 panel_id: PanelId,
4025 window: &mut Window,
4026 cx: &mut Context<Self>,
4027 ) -> Option<Arc<dyn PanelHandle>> {
4028 let mut panel = None;
4029 for dock in self.all_docks() {
4030 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
4031 panel = dock.update(cx, |dock, cx| {
4032 dock.activate_panel(panel_index, window, cx);
4033 dock.set_open(true, window, cx);
4034 dock.active_panel().cloned()
4035 });
4036 break;
4037 }
4038 }
4039
4040 if panel.is_some() {
4041 cx.notify();
4042 self.serialize_workspace(window, cx);
4043 }
4044
4045 panel
4046 }
4047
4048 /// Focus or unfocus the given panel type, depending on the given callback.
4049 fn focus_or_unfocus_panel<T: Panel>(
4050 &mut self,
4051 window: &mut Window,
4052 cx: &mut Context<Self>,
4053 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
4054 ) -> Option<Arc<dyn PanelHandle>> {
4055 let mut result_panel = None;
4056 let mut serialize = false;
4057 for dock in self.all_docks() {
4058 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4059 let mut focus_center = false;
4060 let panel = dock.update(cx, |dock, cx| {
4061 dock.activate_panel(panel_index, window, cx);
4062
4063 let panel = dock.active_panel().cloned();
4064 if let Some(panel) = panel.as_ref() {
4065 if should_focus(&**panel, window, cx) {
4066 dock.set_open(true, window, cx);
4067 panel.panel_focus_handle(cx).focus(window, cx);
4068 } else {
4069 focus_center = true;
4070 }
4071 }
4072 panel
4073 });
4074
4075 if focus_center {
4076 self.active_pane
4077 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4078 }
4079
4080 result_panel = panel;
4081 serialize = true;
4082 break;
4083 }
4084 }
4085
4086 if serialize {
4087 self.serialize_workspace(window, cx);
4088 }
4089
4090 cx.notify();
4091 result_panel
4092 }
4093
4094 /// Open the panel of the given type
4095 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4096 for dock in self.all_docks() {
4097 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4098 dock.update(cx, |dock, cx| {
4099 dock.activate_panel(panel_index, window, cx);
4100 dock.set_open(true, window, cx);
4101 });
4102 }
4103 }
4104 }
4105
4106 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
4107 for dock in self.all_docks().iter() {
4108 dock.update(cx, |dock, cx| {
4109 if dock.panel::<T>().is_some() {
4110 dock.set_open(false, window, cx)
4111 }
4112 })
4113 }
4114 }
4115
4116 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
4117 self.all_docks()
4118 .iter()
4119 .find_map(|dock| dock.read(cx).panel::<T>())
4120 }
4121
4122 fn dismiss_zoomed_items_to_reveal(
4123 &mut self,
4124 dock_to_reveal: Option<DockPosition>,
4125 window: &mut Window,
4126 cx: &mut Context<Self>,
4127 ) {
4128 // If a center pane is zoomed, unzoom it.
4129 for pane in &self.panes {
4130 if pane != &self.active_pane || dock_to_reveal.is_some() {
4131 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4132 }
4133 }
4134
4135 // If another dock is zoomed, hide it.
4136 let mut focus_center = false;
4137 for dock in self.all_docks() {
4138 dock.update(cx, |dock, cx| {
4139 if Some(dock.position()) != dock_to_reveal
4140 && let Some(panel) = dock.active_panel()
4141 && panel.is_zoomed(window, cx)
4142 {
4143 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
4144 dock.set_open(false, window, cx);
4145 }
4146 });
4147 }
4148
4149 if focus_center {
4150 self.active_pane
4151 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4152 }
4153
4154 if self.zoomed_position != dock_to_reveal {
4155 self.zoomed = None;
4156 self.zoomed_position = None;
4157 cx.emit(Event::ZoomChanged);
4158 }
4159
4160 cx.notify();
4161 }
4162
4163 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4164 let pane = cx.new(|cx| {
4165 let mut pane = Pane::new(
4166 self.weak_handle(),
4167 self.project.clone(),
4168 self.pane_history_timestamp.clone(),
4169 None,
4170 NewFile.boxed_clone(),
4171 true,
4172 window,
4173 cx,
4174 );
4175 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
4176 pane
4177 });
4178 cx.subscribe_in(&pane, window, Self::handle_pane_event)
4179 .detach();
4180 self.panes.push(pane.clone());
4181
4182 window.focus(&pane.focus_handle(cx), cx);
4183
4184 cx.emit(Event::PaneAdded(pane.clone()));
4185 pane
4186 }
4187
4188 pub fn add_item_to_center(
4189 &mut self,
4190 item: Box<dyn ItemHandle>,
4191 window: &mut Window,
4192 cx: &mut Context<Self>,
4193 ) -> bool {
4194 if let Some(center_pane) = self.last_active_center_pane.clone() {
4195 if let Some(center_pane) = center_pane.upgrade() {
4196 center_pane.update(cx, |pane, cx| {
4197 pane.add_item(item, true, true, None, window, cx)
4198 });
4199 true
4200 } else {
4201 false
4202 }
4203 } else {
4204 false
4205 }
4206 }
4207
4208 pub fn add_item_to_active_pane(
4209 &mut self,
4210 item: Box<dyn ItemHandle>,
4211 destination_index: Option<usize>,
4212 focus_item: bool,
4213 window: &mut Window,
4214 cx: &mut App,
4215 ) {
4216 self.add_item(
4217 self.active_pane.clone(),
4218 item,
4219 destination_index,
4220 false,
4221 focus_item,
4222 window,
4223 cx,
4224 )
4225 }
4226
4227 pub fn add_item(
4228 &mut self,
4229 pane: Entity<Pane>,
4230 item: Box<dyn ItemHandle>,
4231 destination_index: Option<usize>,
4232 activate_pane: bool,
4233 focus_item: bool,
4234 window: &mut Window,
4235 cx: &mut App,
4236 ) {
4237 pane.update(cx, |pane, cx| {
4238 pane.add_item(
4239 item,
4240 activate_pane,
4241 focus_item,
4242 destination_index,
4243 window,
4244 cx,
4245 )
4246 });
4247 }
4248
4249 pub fn split_item(
4250 &mut self,
4251 split_direction: SplitDirection,
4252 item: Box<dyn ItemHandle>,
4253 window: &mut Window,
4254 cx: &mut Context<Self>,
4255 ) {
4256 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4257 self.add_item(new_pane, item, None, true, true, window, cx);
4258 }
4259
4260 pub fn open_abs_path(
4261 &mut self,
4262 abs_path: PathBuf,
4263 options: OpenOptions,
4264 window: &mut Window,
4265 cx: &mut Context<Self>,
4266 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4267 cx.spawn_in(window, async move |workspace, cx| {
4268 let open_paths_task_result = workspace
4269 .update_in(cx, |workspace, window, cx| {
4270 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4271 })
4272 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4273 .await;
4274 anyhow::ensure!(
4275 open_paths_task_result.len() == 1,
4276 "open abs path {abs_path:?} task returned incorrect number of results"
4277 );
4278 match open_paths_task_result
4279 .into_iter()
4280 .next()
4281 .expect("ensured single task result")
4282 {
4283 Some(open_result) => {
4284 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4285 }
4286 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4287 }
4288 })
4289 }
4290
4291 pub fn split_abs_path(
4292 &mut self,
4293 abs_path: PathBuf,
4294 visible: bool,
4295 window: &mut Window,
4296 cx: &mut Context<Self>,
4297 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4298 let project_path_task =
4299 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4300 cx.spawn_in(window, async move |this, cx| {
4301 let (_, path) = project_path_task.await?;
4302 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4303 .await
4304 })
4305 }
4306
4307 pub fn open_path(
4308 &mut self,
4309 path: impl Into<ProjectPath>,
4310 pane: Option<WeakEntity<Pane>>,
4311 focus_item: bool,
4312 window: &mut Window,
4313 cx: &mut App,
4314 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4315 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4316 }
4317
4318 pub fn open_path_preview(
4319 &mut self,
4320 path: impl Into<ProjectPath>,
4321 pane: Option<WeakEntity<Pane>>,
4322 focus_item: bool,
4323 allow_preview: bool,
4324 activate: bool,
4325 window: &mut Window,
4326 cx: &mut App,
4327 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4328 let pane = pane.unwrap_or_else(|| {
4329 self.last_active_center_pane.clone().unwrap_or_else(|| {
4330 self.panes
4331 .first()
4332 .expect("There must be an active pane")
4333 .downgrade()
4334 })
4335 });
4336
4337 let project_path = path.into();
4338 let task = self.load_path(project_path.clone(), window, cx);
4339 window.spawn(cx, async move |cx| {
4340 let (project_entry_id, build_item) = task.await?;
4341
4342 pane.update_in(cx, |pane, window, cx| {
4343 pane.open_item(
4344 project_entry_id,
4345 project_path,
4346 focus_item,
4347 allow_preview,
4348 activate,
4349 None,
4350 window,
4351 cx,
4352 build_item,
4353 )
4354 })
4355 })
4356 }
4357
4358 pub fn split_path(
4359 &mut self,
4360 path: impl Into<ProjectPath>,
4361 window: &mut Window,
4362 cx: &mut Context<Self>,
4363 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4364 self.split_path_preview(path, false, None, window, cx)
4365 }
4366
4367 pub fn split_path_preview(
4368 &mut self,
4369 path: impl Into<ProjectPath>,
4370 allow_preview: bool,
4371 split_direction: Option<SplitDirection>,
4372 window: &mut Window,
4373 cx: &mut Context<Self>,
4374 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4375 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4376 self.panes
4377 .first()
4378 .expect("There must be an active pane")
4379 .downgrade()
4380 });
4381
4382 if let Member::Pane(center_pane) = &self.center.root
4383 && center_pane.read(cx).items_len() == 0
4384 {
4385 return self.open_path(path, Some(pane), true, window, cx);
4386 }
4387
4388 let project_path = path.into();
4389 let task = self.load_path(project_path.clone(), window, cx);
4390 cx.spawn_in(window, async move |this, cx| {
4391 let (project_entry_id, build_item) = task.await?;
4392 this.update_in(cx, move |this, window, cx| -> Option<_> {
4393 let pane = pane.upgrade()?;
4394 let new_pane = this.split_pane(
4395 pane,
4396 split_direction.unwrap_or(SplitDirection::Right),
4397 window,
4398 cx,
4399 );
4400 new_pane.update(cx, |new_pane, cx| {
4401 Some(new_pane.open_item(
4402 project_entry_id,
4403 project_path,
4404 true,
4405 allow_preview,
4406 true,
4407 None,
4408 window,
4409 cx,
4410 build_item,
4411 ))
4412 })
4413 })
4414 .map(|option| option.context("pane was dropped"))?
4415 })
4416 }
4417
4418 fn load_path(
4419 &mut self,
4420 path: ProjectPath,
4421 window: &mut Window,
4422 cx: &mut App,
4423 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4424 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4425 registry.open_path(self.project(), &path, window, cx)
4426 }
4427
4428 pub fn find_project_item<T>(
4429 &self,
4430 pane: &Entity<Pane>,
4431 project_item: &Entity<T::Item>,
4432 cx: &App,
4433 ) -> Option<Entity<T>>
4434 where
4435 T: ProjectItem,
4436 {
4437 use project::ProjectItem as _;
4438 let project_item = project_item.read(cx);
4439 let entry_id = project_item.entry_id(cx);
4440 let project_path = project_item.project_path(cx);
4441
4442 let mut item = None;
4443 if let Some(entry_id) = entry_id {
4444 item = pane.read(cx).item_for_entry(entry_id, cx);
4445 }
4446 if item.is_none()
4447 && let Some(project_path) = project_path
4448 {
4449 item = pane.read(cx).item_for_path(project_path, cx);
4450 }
4451
4452 item.and_then(|item| item.downcast::<T>())
4453 }
4454
4455 pub fn is_project_item_open<T>(
4456 &self,
4457 pane: &Entity<Pane>,
4458 project_item: &Entity<T::Item>,
4459 cx: &App,
4460 ) -> bool
4461 where
4462 T: ProjectItem,
4463 {
4464 self.find_project_item::<T>(pane, project_item, cx)
4465 .is_some()
4466 }
4467
4468 pub fn open_project_item<T>(
4469 &mut self,
4470 pane: Entity<Pane>,
4471 project_item: Entity<T::Item>,
4472 activate_pane: bool,
4473 focus_item: bool,
4474 keep_old_preview: bool,
4475 allow_new_preview: bool,
4476 window: &mut Window,
4477 cx: &mut Context<Self>,
4478 ) -> Entity<T>
4479 where
4480 T: ProjectItem,
4481 {
4482 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4483
4484 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4485 if !keep_old_preview
4486 && let Some(old_id) = old_item_id
4487 && old_id != item.item_id()
4488 {
4489 // switching to a different item, so unpreview old active item
4490 pane.update(cx, |pane, _| {
4491 pane.unpreview_item_if_preview(old_id);
4492 });
4493 }
4494
4495 self.activate_item(&item, activate_pane, focus_item, window, cx);
4496 if !allow_new_preview {
4497 pane.update(cx, |pane, _| {
4498 pane.unpreview_item_if_preview(item.item_id());
4499 });
4500 }
4501 return item;
4502 }
4503
4504 let item = pane.update(cx, |pane, cx| {
4505 cx.new(|cx| {
4506 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4507 })
4508 });
4509 let mut destination_index = None;
4510 pane.update(cx, |pane, cx| {
4511 if !keep_old_preview && let Some(old_id) = old_item_id {
4512 pane.unpreview_item_if_preview(old_id);
4513 }
4514 if allow_new_preview {
4515 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4516 }
4517 });
4518
4519 self.add_item(
4520 pane,
4521 Box::new(item.clone()),
4522 destination_index,
4523 activate_pane,
4524 focus_item,
4525 window,
4526 cx,
4527 );
4528 item
4529 }
4530
4531 pub fn open_shared_screen(
4532 &mut self,
4533 peer_id: PeerId,
4534 window: &mut Window,
4535 cx: &mut Context<Self>,
4536 ) {
4537 if let Some(shared_screen) =
4538 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4539 {
4540 self.active_pane.update(cx, |pane, cx| {
4541 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4542 });
4543 }
4544 }
4545
4546 pub fn activate_item(
4547 &mut self,
4548 item: &dyn ItemHandle,
4549 activate_pane: bool,
4550 focus_item: bool,
4551 window: &mut Window,
4552 cx: &mut App,
4553 ) -> bool {
4554 let result = self.panes.iter().find_map(|pane| {
4555 pane.read(cx)
4556 .index_for_item(item)
4557 .map(|ix| (pane.clone(), ix))
4558 });
4559 if let Some((pane, ix)) = result {
4560 pane.update(cx, |pane, cx| {
4561 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4562 });
4563 true
4564 } else {
4565 false
4566 }
4567 }
4568
4569 fn activate_pane_at_index(
4570 &mut self,
4571 action: &ActivatePane,
4572 window: &mut Window,
4573 cx: &mut Context<Self>,
4574 ) {
4575 let panes = self.center.panes();
4576 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4577 window.focus(&pane.focus_handle(cx), cx);
4578 } else {
4579 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4580 .detach();
4581 }
4582 }
4583
4584 fn move_item_to_pane_at_index(
4585 &mut self,
4586 action: &MoveItemToPane,
4587 window: &mut Window,
4588 cx: &mut Context<Self>,
4589 ) {
4590 let panes = self.center.panes();
4591 let destination = match panes.get(action.destination) {
4592 Some(&destination) => destination.clone(),
4593 None => {
4594 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4595 return;
4596 }
4597 let direction = SplitDirection::Right;
4598 let split_off_pane = self
4599 .find_pane_in_direction(direction, cx)
4600 .unwrap_or_else(|| self.active_pane.clone());
4601 let new_pane = self.add_pane(window, cx);
4602 self.center.split(&split_off_pane, &new_pane, direction, cx);
4603 new_pane
4604 }
4605 };
4606
4607 if action.clone {
4608 if self
4609 .active_pane
4610 .read(cx)
4611 .active_item()
4612 .is_some_and(|item| item.can_split(cx))
4613 {
4614 clone_active_item(
4615 self.database_id(),
4616 &self.active_pane,
4617 &destination,
4618 action.focus,
4619 window,
4620 cx,
4621 );
4622 return;
4623 }
4624 }
4625 move_active_item(
4626 &self.active_pane,
4627 &destination,
4628 action.focus,
4629 true,
4630 window,
4631 cx,
4632 )
4633 }
4634
4635 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4636 let panes = self.center.panes();
4637 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4638 let next_ix = (ix + 1) % panes.len();
4639 let next_pane = panes[next_ix].clone();
4640 window.focus(&next_pane.focus_handle(cx), cx);
4641 }
4642 }
4643
4644 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4645 let panes = self.center.panes();
4646 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4647 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4648 let prev_pane = panes[prev_ix].clone();
4649 window.focus(&prev_pane.focus_handle(cx), cx);
4650 }
4651 }
4652
4653 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4654 let last_pane = self.center.last_pane();
4655 window.focus(&last_pane.focus_handle(cx), cx);
4656 }
4657
4658 pub fn activate_pane_in_direction(
4659 &mut self,
4660 direction: SplitDirection,
4661 window: &mut Window,
4662 cx: &mut App,
4663 ) {
4664 use ActivateInDirectionTarget as Target;
4665 enum Origin {
4666 Sidebar,
4667 LeftDock,
4668 RightDock,
4669 BottomDock,
4670 Center,
4671 }
4672
4673 let origin: Origin = if self
4674 .sidebar_focus_handle
4675 .as_ref()
4676 .is_some_and(|h| h.contains_focused(window, cx))
4677 {
4678 Origin::Sidebar
4679 } else {
4680 [
4681 (&self.left_dock, Origin::LeftDock),
4682 (&self.right_dock, Origin::RightDock),
4683 (&self.bottom_dock, Origin::BottomDock),
4684 ]
4685 .into_iter()
4686 .find_map(|(dock, origin)| {
4687 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4688 Some(origin)
4689 } else {
4690 None
4691 }
4692 })
4693 .unwrap_or(Origin::Center)
4694 };
4695
4696 let get_last_active_pane = || {
4697 let pane = self
4698 .last_active_center_pane
4699 .clone()
4700 .unwrap_or_else(|| {
4701 self.panes
4702 .first()
4703 .expect("There must be an active pane")
4704 .downgrade()
4705 })
4706 .upgrade()?;
4707 (pane.read(cx).items_len() != 0).then_some(pane)
4708 };
4709
4710 let try_dock =
4711 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4712
4713 let sidebar_target = self
4714 .sidebar_focus_handle
4715 .as_ref()
4716 .map(|h| Target::Sidebar(h.clone()));
4717
4718 let target = match (origin, direction) {
4719 // From the sidebar, only Right navigates into the workspace.
4720 (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
4721 .or_else(|| get_last_active_pane().map(Target::Pane))
4722 .or_else(|| try_dock(&self.bottom_dock))
4723 .or_else(|| try_dock(&self.right_dock)),
4724
4725 (Origin::Sidebar, _) => None,
4726
4727 // We're in the center, so we first try to go to a different pane,
4728 // otherwise try to go to a dock.
4729 (Origin::Center, direction) => {
4730 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4731 Some(Target::Pane(pane))
4732 } else {
4733 match direction {
4734 SplitDirection::Up => None,
4735 SplitDirection::Down => try_dock(&self.bottom_dock),
4736 SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
4737 SplitDirection::Right => try_dock(&self.right_dock),
4738 }
4739 }
4740 }
4741
4742 (Origin::LeftDock, SplitDirection::Right) => {
4743 if let Some(last_active_pane) = get_last_active_pane() {
4744 Some(Target::Pane(last_active_pane))
4745 } else {
4746 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4747 }
4748 }
4749
4750 (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
4751
4752 (Origin::LeftDock, SplitDirection::Down)
4753 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4754
4755 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4756 (Origin::BottomDock, SplitDirection::Left) => {
4757 try_dock(&self.left_dock).or(sidebar_target)
4758 }
4759 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4760
4761 (Origin::RightDock, SplitDirection::Left) => {
4762 if let Some(last_active_pane) = get_last_active_pane() {
4763 Some(Target::Pane(last_active_pane))
4764 } else {
4765 try_dock(&self.bottom_dock)
4766 .or_else(|| try_dock(&self.left_dock))
4767 .or(sidebar_target)
4768 }
4769 }
4770
4771 _ => None,
4772 };
4773
4774 match target {
4775 Some(ActivateInDirectionTarget::Pane(pane)) => {
4776 let pane = pane.read(cx);
4777 if let Some(item) = pane.active_item() {
4778 item.item_focus_handle(cx).focus(window, cx);
4779 } else {
4780 log::error!(
4781 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4782 );
4783 }
4784 }
4785 Some(ActivateInDirectionTarget::Dock(dock)) => {
4786 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4787 window.defer(cx, move |window, cx| {
4788 let dock = dock.read(cx);
4789 if let Some(panel) = dock.active_panel() {
4790 panel.panel_focus_handle(cx).focus(window, cx);
4791 } else {
4792 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4793 }
4794 })
4795 }
4796 Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
4797 focus_handle.focus(window, cx);
4798 }
4799 None => {}
4800 }
4801 }
4802
4803 pub fn move_item_to_pane_in_direction(
4804 &mut self,
4805 action: &MoveItemToPaneInDirection,
4806 window: &mut Window,
4807 cx: &mut Context<Self>,
4808 ) {
4809 let destination = match self.find_pane_in_direction(action.direction, cx) {
4810 Some(destination) => destination,
4811 None => {
4812 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4813 return;
4814 }
4815 let new_pane = self.add_pane(window, cx);
4816 self.center
4817 .split(&self.active_pane, &new_pane, action.direction, cx);
4818 new_pane
4819 }
4820 };
4821
4822 if action.clone {
4823 if self
4824 .active_pane
4825 .read(cx)
4826 .active_item()
4827 .is_some_and(|item| item.can_split(cx))
4828 {
4829 clone_active_item(
4830 self.database_id(),
4831 &self.active_pane,
4832 &destination,
4833 action.focus,
4834 window,
4835 cx,
4836 );
4837 return;
4838 }
4839 }
4840 move_active_item(
4841 &self.active_pane,
4842 &destination,
4843 action.focus,
4844 true,
4845 window,
4846 cx,
4847 );
4848 }
4849
4850 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4851 self.center.bounding_box_for_pane(pane)
4852 }
4853
4854 pub fn find_pane_in_direction(
4855 &mut self,
4856 direction: SplitDirection,
4857 cx: &App,
4858 ) -> Option<Entity<Pane>> {
4859 self.center
4860 .find_pane_in_direction(&self.active_pane, direction, cx)
4861 .cloned()
4862 }
4863
4864 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4865 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4866 self.center.swap(&self.active_pane, &to, cx);
4867 cx.notify();
4868 }
4869 }
4870
4871 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4872 if self
4873 .center
4874 .move_to_border(&self.active_pane, direction, cx)
4875 .unwrap()
4876 {
4877 cx.notify();
4878 }
4879 }
4880
4881 pub fn resize_pane(
4882 &mut self,
4883 axis: gpui::Axis,
4884 amount: Pixels,
4885 window: &mut Window,
4886 cx: &mut Context<Self>,
4887 ) {
4888 let docks = self.all_docks();
4889 let active_dock = docks
4890 .into_iter()
4891 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4892
4893 if let Some(dock_entity) = active_dock {
4894 let dock = dock_entity.read(cx);
4895 let Some(panel_size) = dock
4896 .active_panel()
4897 .map(|panel| self.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx))
4898 else {
4899 return;
4900 };
4901 match dock.position() {
4902 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4903 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4904 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4905 }
4906 } else {
4907 self.center
4908 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
4909 }
4910 cx.notify();
4911 }
4912
4913 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
4914 self.center.reset_pane_sizes(cx);
4915 cx.notify();
4916 }
4917
4918 fn handle_pane_focused(
4919 &mut self,
4920 pane: Entity<Pane>,
4921 window: &mut Window,
4922 cx: &mut Context<Self>,
4923 ) {
4924 // This is explicitly hoisted out of the following check for pane identity as
4925 // terminal panel panes are not registered as a center panes.
4926 self.status_bar.update(cx, |status_bar, cx| {
4927 status_bar.set_active_pane(&pane, window, cx);
4928 });
4929 if self.active_pane != pane {
4930 self.set_active_pane(&pane, window, cx);
4931 }
4932
4933 if self.last_active_center_pane.is_none() {
4934 self.last_active_center_pane = Some(pane.downgrade());
4935 }
4936
4937 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
4938 // This prevents the dock from closing when focus events fire during window activation.
4939 // We also preserve any dock whose active panel itself has focus — this covers
4940 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
4941 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
4942 let dock_read = dock.read(cx);
4943 if let Some(panel) = dock_read.active_panel() {
4944 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
4945 || panel.panel_focus_handle(cx).contains_focused(window, cx)
4946 {
4947 return Some(dock_read.position());
4948 }
4949 }
4950 None
4951 });
4952
4953 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
4954 if pane.read(cx).is_zoomed() {
4955 self.zoomed = Some(pane.downgrade().into());
4956 } else {
4957 self.zoomed = None;
4958 }
4959 self.zoomed_position = None;
4960 cx.emit(Event::ZoomChanged);
4961 self.update_active_view_for_followers(window, cx);
4962 pane.update(cx, |pane, _| {
4963 pane.track_alternate_file_items();
4964 });
4965
4966 cx.notify();
4967 }
4968
4969 fn set_active_pane(
4970 &mut self,
4971 pane: &Entity<Pane>,
4972 window: &mut Window,
4973 cx: &mut Context<Self>,
4974 ) {
4975 self.active_pane = pane.clone();
4976 self.active_item_path_changed(true, window, cx);
4977 self.last_active_center_pane = Some(pane.downgrade());
4978 }
4979
4980 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4981 self.update_active_view_for_followers(window, cx);
4982 }
4983
4984 fn handle_pane_event(
4985 &mut self,
4986 pane: &Entity<Pane>,
4987 event: &pane::Event,
4988 window: &mut Window,
4989 cx: &mut Context<Self>,
4990 ) {
4991 let mut serialize_workspace = true;
4992 match event {
4993 pane::Event::AddItem { item } => {
4994 item.added_to_pane(self, pane.clone(), window, cx);
4995 cx.emit(Event::ItemAdded {
4996 item: item.boxed_clone(),
4997 });
4998 }
4999 pane::Event::Split { direction, mode } => {
5000 match mode {
5001 SplitMode::ClonePane => {
5002 self.split_and_clone(pane.clone(), *direction, window, cx)
5003 .detach();
5004 }
5005 SplitMode::EmptyPane => {
5006 self.split_pane(pane.clone(), *direction, window, cx);
5007 }
5008 SplitMode::MovePane => {
5009 self.split_and_move(pane.clone(), *direction, window, cx);
5010 }
5011 };
5012 }
5013 pane::Event::JoinIntoNext => {
5014 self.join_pane_into_next(pane.clone(), window, cx);
5015 }
5016 pane::Event::JoinAll => {
5017 self.join_all_panes(window, cx);
5018 }
5019 pane::Event::Remove { focus_on_pane } => {
5020 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
5021 }
5022 pane::Event::ActivateItem {
5023 local,
5024 focus_changed,
5025 } => {
5026 window.invalidate_character_coordinates();
5027
5028 pane.update(cx, |pane, _| {
5029 pane.track_alternate_file_items();
5030 });
5031 if *local {
5032 self.unfollow_in_pane(pane, window, cx);
5033 }
5034 serialize_workspace = *focus_changed || pane != self.active_pane();
5035 if pane == self.active_pane() {
5036 self.active_item_path_changed(*focus_changed, window, cx);
5037 self.update_active_view_for_followers(window, cx);
5038 } else if *local {
5039 self.set_active_pane(pane, window, cx);
5040 }
5041 }
5042 pane::Event::UserSavedItem { item, save_intent } => {
5043 cx.emit(Event::UserSavedItem {
5044 pane: pane.downgrade(),
5045 item: item.boxed_clone(),
5046 save_intent: *save_intent,
5047 });
5048 serialize_workspace = false;
5049 }
5050 pane::Event::ChangeItemTitle => {
5051 if *pane == self.active_pane {
5052 self.active_item_path_changed(false, window, cx);
5053 }
5054 serialize_workspace = false;
5055 }
5056 pane::Event::RemovedItem { item } => {
5057 cx.emit(Event::ActiveItemChanged);
5058 self.update_window_edited(window, cx);
5059 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
5060 && entry.get().entity_id() == pane.entity_id()
5061 {
5062 entry.remove();
5063 }
5064 cx.emit(Event::ItemRemoved {
5065 item_id: item.item_id(),
5066 });
5067 }
5068 pane::Event::Focus => {
5069 window.invalidate_character_coordinates();
5070 self.handle_pane_focused(pane.clone(), window, cx);
5071 }
5072 pane::Event::ZoomIn => {
5073 if *pane == self.active_pane {
5074 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
5075 if pane.read(cx).has_focus(window, cx) {
5076 self.zoomed = Some(pane.downgrade().into());
5077 self.zoomed_position = None;
5078 cx.emit(Event::ZoomChanged);
5079 }
5080 cx.notify();
5081 }
5082 }
5083 pane::Event::ZoomOut => {
5084 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
5085 if self.zoomed_position.is_none() {
5086 self.zoomed = None;
5087 cx.emit(Event::ZoomChanged);
5088 }
5089 cx.notify();
5090 }
5091 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
5092 }
5093
5094 if serialize_workspace {
5095 self.serialize_workspace(window, cx);
5096 }
5097 }
5098
5099 pub fn unfollow_in_pane(
5100 &mut self,
5101 pane: &Entity<Pane>,
5102 window: &mut Window,
5103 cx: &mut Context<Workspace>,
5104 ) -> Option<CollaboratorId> {
5105 let leader_id = self.leader_for_pane(pane)?;
5106 self.unfollow(leader_id, window, cx);
5107 Some(leader_id)
5108 }
5109
5110 pub fn split_pane(
5111 &mut self,
5112 pane_to_split: Entity<Pane>,
5113 split_direction: SplitDirection,
5114 window: &mut Window,
5115 cx: &mut Context<Self>,
5116 ) -> Entity<Pane> {
5117 let new_pane = self.add_pane(window, cx);
5118 self.center
5119 .split(&pane_to_split, &new_pane, split_direction, cx);
5120 cx.notify();
5121 new_pane
5122 }
5123
5124 pub fn split_and_move(
5125 &mut self,
5126 pane: Entity<Pane>,
5127 direction: SplitDirection,
5128 window: &mut Window,
5129 cx: &mut Context<Self>,
5130 ) {
5131 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
5132 return;
5133 };
5134 let new_pane = self.add_pane(window, cx);
5135 new_pane.update(cx, |pane, cx| {
5136 pane.add_item(item, true, true, None, window, cx)
5137 });
5138 self.center.split(&pane, &new_pane, direction, cx);
5139 cx.notify();
5140 }
5141
5142 pub fn split_and_clone(
5143 &mut self,
5144 pane: Entity<Pane>,
5145 direction: SplitDirection,
5146 window: &mut Window,
5147 cx: &mut Context<Self>,
5148 ) -> Task<Option<Entity<Pane>>> {
5149 let Some(item) = pane.read(cx).active_item() else {
5150 return Task::ready(None);
5151 };
5152 if !item.can_split(cx) {
5153 return Task::ready(None);
5154 }
5155 let task = item.clone_on_split(self.database_id(), window, cx);
5156 cx.spawn_in(window, async move |this, cx| {
5157 if let Some(clone) = task.await {
5158 this.update_in(cx, |this, window, cx| {
5159 let new_pane = this.add_pane(window, cx);
5160 let nav_history = pane.read(cx).fork_nav_history();
5161 new_pane.update(cx, |pane, cx| {
5162 pane.set_nav_history(nav_history, cx);
5163 pane.add_item(clone, true, true, None, window, cx)
5164 });
5165 this.center.split(&pane, &new_pane, direction, cx);
5166 cx.notify();
5167 new_pane
5168 })
5169 .ok()
5170 } else {
5171 None
5172 }
5173 })
5174 }
5175
5176 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5177 let active_item = self.active_pane.read(cx).active_item();
5178 for pane in &self.panes {
5179 join_pane_into_active(&self.active_pane, pane, window, cx);
5180 }
5181 if let Some(active_item) = active_item {
5182 self.activate_item(active_item.as_ref(), true, true, window, cx);
5183 }
5184 cx.notify();
5185 }
5186
5187 pub fn join_pane_into_next(
5188 &mut self,
5189 pane: Entity<Pane>,
5190 window: &mut Window,
5191 cx: &mut Context<Self>,
5192 ) {
5193 let next_pane = self
5194 .find_pane_in_direction(SplitDirection::Right, cx)
5195 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
5196 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
5197 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
5198 let Some(next_pane) = next_pane else {
5199 return;
5200 };
5201 move_all_items(&pane, &next_pane, window, cx);
5202 cx.notify();
5203 }
5204
5205 fn remove_pane(
5206 &mut self,
5207 pane: Entity<Pane>,
5208 focus_on: Option<Entity<Pane>>,
5209 window: &mut Window,
5210 cx: &mut Context<Self>,
5211 ) {
5212 if self.center.remove(&pane, cx).unwrap() {
5213 self.force_remove_pane(&pane, &focus_on, window, cx);
5214 self.unfollow_in_pane(&pane, window, cx);
5215 self.last_leaders_by_pane.remove(&pane.downgrade());
5216 for removed_item in pane.read(cx).items() {
5217 self.panes_by_item.remove(&removed_item.item_id());
5218 }
5219
5220 cx.notify();
5221 } else {
5222 self.active_item_path_changed(true, window, cx);
5223 }
5224 cx.emit(Event::PaneRemoved);
5225 }
5226
5227 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5228 &mut self.panes
5229 }
5230
5231 pub fn panes(&self) -> &[Entity<Pane>] {
5232 &self.panes
5233 }
5234
5235 pub fn active_pane(&self) -> &Entity<Pane> {
5236 &self.active_pane
5237 }
5238
5239 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5240 for dock in self.all_docks() {
5241 if dock.focus_handle(cx).contains_focused(window, cx)
5242 && let Some(pane) = dock
5243 .read(cx)
5244 .active_panel()
5245 .and_then(|panel| panel.pane(cx))
5246 {
5247 return pane;
5248 }
5249 }
5250 self.active_pane().clone()
5251 }
5252
5253 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5254 self.find_pane_in_direction(SplitDirection::Right, cx)
5255 .unwrap_or_else(|| {
5256 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5257 })
5258 }
5259
5260 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5261 self.pane_for_item_id(handle.item_id())
5262 }
5263
5264 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5265 let weak_pane = self.panes_by_item.get(&item_id)?;
5266 weak_pane.upgrade()
5267 }
5268
5269 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5270 self.panes
5271 .iter()
5272 .find(|pane| pane.entity_id() == entity_id)
5273 .cloned()
5274 }
5275
5276 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5277 self.follower_states.retain(|leader_id, state| {
5278 if *leader_id == CollaboratorId::PeerId(peer_id) {
5279 for item in state.items_by_leader_view_id.values() {
5280 item.view.set_leader_id(None, window, cx);
5281 }
5282 false
5283 } else {
5284 true
5285 }
5286 });
5287 cx.notify();
5288 }
5289
5290 pub fn start_following(
5291 &mut self,
5292 leader_id: impl Into<CollaboratorId>,
5293 window: &mut Window,
5294 cx: &mut Context<Self>,
5295 ) -> Option<Task<Result<()>>> {
5296 let leader_id = leader_id.into();
5297 let pane = self.active_pane().clone();
5298
5299 self.last_leaders_by_pane
5300 .insert(pane.downgrade(), leader_id);
5301 self.unfollow(leader_id, window, cx);
5302 self.unfollow_in_pane(&pane, window, cx);
5303 self.follower_states.insert(
5304 leader_id,
5305 FollowerState {
5306 center_pane: pane.clone(),
5307 dock_pane: None,
5308 active_view_id: None,
5309 items_by_leader_view_id: Default::default(),
5310 },
5311 );
5312 cx.notify();
5313
5314 match leader_id {
5315 CollaboratorId::PeerId(leader_peer_id) => {
5316 let room_id = self.active_call()?.room_id(cx)?;
5317 let project_id = self.project.read(cx).remote_id();
5318 let request = self.app_state.client.request(proto::Follow {
5319 room_id,
5320 project_id,
5321 leader_id: Some(leader_peer_id),
5322 });
5323
5324 Some(cx.spawn_in(window, async move |this, cx| {
5325 let response = request.await?;
5326 this.update(cx, |this, _| {
5327 let state = this
5328 .follower_states
5329 .get_mut(&leader_id)
5330 .context("following interrupted")?;
5331 state.active_view_id = response
5332 .active_view
5333 .as_ref()
5334 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5335 anyhow::Ok(())
5336 })??;
5337 if let Some(view) = response.active_view {
5338 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5339 }
5340 this.update_in(cx, |this, window, cx| {
5341 this.leader_updated(leader_id, window, cx)
5342 })?;
5343 Ok(())
5344 }))
5345 }
5346 CollaboratorId::Agent => {
5347 self.leader_updated(leader_id, window, cx)?;
5348 Some(Task::ready(Ok(())))
5349 }
5350 }
5351 }
5352
5353 pub fn follow_next_collaborator(
5354 &mut self,
5355 _: &FollowNextCollaborator,
5356 window: &mut Window,
5357 cx: &mut Context<Self>,
5358 ) {
5359 let collaborators = self.project.read(cx).collaborators();
5360 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5361 let mut collaborators = collaborators.keys().copied();
5362 for peer_id in collaborators.by_ref() {
5363 if CollaboratorId::PeerId(peer_id) == leader_id {
5364 break;
5365 }
5366 }
5367 collaborators.next().map(CollaboratorId::PeerId)
5368 } else if let Some(last_leader_id) =
5369 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5370 {
5371 match last_leader_id {
5372 CollaboratorId::PeerId(peer_id) => {
5373 if collaborators.contains_key(peer_id) {
5374 Some(*last_leader_id)
5375 } else {
5376 None
5377 }
5378 }
5379 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5380 }
5381 } else {
5382 None
5383 };
5384
5385 let pane = self.active_pane.clone();
5386 let Some(leader_id) = next_leader_id.or_else(|| {
5387 Some(CollaboratorId::PeerId(
5388 collaborators.keys().copied().next()?,
5389 ))
5390 }) else {
5391 return;
5392 };
5393 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5394 return;
5395 }
5396 if let Some(task) = self.start_following(leader_id, window, cx) {
5397 task.detach_and_log_err(cx)
5398 }
5399 }
5400
5401 pub fn follow(
5402 &mut self,
5403 leader_id: impl Into<CollaboratorId>,
5404 window: &mut Window,
5405 cx: &mut Context<Self>,
5406 ) {
5407 let leader_id = leader_id.into();
5408
5409 if let CollaboratorId::PeerId(peer_id) = leader_id {
5410 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5411 return;
5412 };
5413 let Some(remote_participant) =
5414 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5415 else {
5416 return;
5417 };
5418
5419 let project = self.project.read(cx);
5420
5421 let other_project_id = match remote_participant.location {
5422 ParticipantLocation::External => None,
5423 ParticipantLocation::UnsharedProject => None,
5424 ParticipantLocation::SharedProject { project_id } => {
5425 if Some(project_id) == project.remote_id() {
5426 None
5427 } else {
5428 Some(project_id)
5429 }
5430 }
5431 };
5432
5433 // if they are active in another project, follow there.
5434 if let Some(project_id) = other_project_id {
5435 let app_state = self.app_state.clone();
5436 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5437 .detach_and_log_err(cx);
5438 }
5439 }
5440
5441 // if you're already following, find the right pane and focus it.
5442 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5443 window.focus(&follower_state.pane().focus_handle(cx), cx);
5444
5445 return;
5446 }
5447
5448 // Otherwise, follow.
5449 if let Some(task) = self.start_following(leader_id, window, cx) {
5450 task.detach_and_log_err(cx)
5451 }
5452 }
5453
5454 pub fn unfollow(
5455 &mut self,
5456 leader_id: impl Into<CollaboratorId>,
5457 window: &mut Window,
5458 cx: &mut Context<Self>,
5459 ) -> Option<()> {
5460 cx.notify();
5461
5462 let leader_id = leader_id.into();
5463 let state = self.follower_states.remove(&leader_id)?;
5464 for (_, item) in state.items_by_leader_view_id {
5465 item.view.set_leader_id(None, window, cx);
5466 }
5467
5468 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5469 let project_id = self.project.read(cx).remote_id();
5470 let room_id = self.active_call()?.room_id(cx)?;
5471 self.app_state
5472 .client
5473 .send(proto::Unfollow {
5474 room_id,
5475 project_id,
5476 leader_id: Some(leader_peer_id),
5477 })
5478 .log_err();
5479 }
5480
5481 Some(())
5482 }
5483
5484 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5485 self.follower_states.contains_key(&id.into())
5486 }
5487
5488 fn active_item_path_changed(
5489 &mut self,
5490 focus_changed: bool,
5491 window: &mut Window,
5492 cx: &mut Context<Self>,
5493 ) {
5494 cx.emit(Event::ActiveItemChanged);
5495 let active_entry = self.active_project_path(cx);
5496 self.project.update(cx, |project, cx| {
5497 project.set_active_path(active_entry.clone(), cx)
5498 });
5499
5500 if focus_changed && let Some(project_path) = &active_entry {
5501 let git_store_entity = self.project.read(cx).git_store().clone();
5502 git_store_entity.update(cx, |git_store, cx| {
5503 git_store.set_active_repo_for_path(project_path, cx);
5504 });
5505 }
5506
5507 self.update_window_title(window, cx);
5508 }
5509
5510 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5511 let project = self.project().read(cx);
5512 let mut title = String::new();
5513
5514 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5515 let name = {
5516 let settings_location = SettingsLocation {
5517 worktree_id: worktree.read(cx).id(),
5518 path: RelPath::empty(),
5519 };
5520
5521 let settings = WorktreeSettings::get(Some(settings_location), cx);
5522 match &settings.project_name {
5523 Some(name) => name.as_str(),
5524 None => worktree.read(cx).root_name_str(),
5525 }
5526 };
5527 if i > 0 {
5528 title.push_str(", ");
5529 }
5530 title.push_str(name);
5531 }
5532
5533 if title.is_empty() {
5534 title = "empty project".to_string();
5535 }
5536
5537 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5538 let filename = path.path.file_name().or_else(|| {
5539 Some(
5540 project
5541 .worktree_for_id(path.worktree_id, cx)?
5542 .read(cx)
5543 .root_name_str(),
5544 )
5545 });
5546
5547 if let Some(filename) = filename {
5548 title.push_str(" — ");
5549 title.push_str(filename.as_ref());
5550 }
5551 }
5552
5553 if project.is_via_collab() {
5554 title.push_str(" ↙");
5555 } else if project.is_shared() {
5556 title.push_str(" ↗");
5557 }
5558
5559 if let Some(last_title) = self.last_window_title.as_ref()
5560 && &title == last_title
5561 {
5562 return;
5563 }
5564 window.set_window_title(&title);
5565 SystemWindowTabController::update_tab_title(
5566 cx,
5567 window.window_handle().window_id(),
5568 SharedString::from(&title),
5569 );
5570 self.last_window_title = Some(title);
5571 }
5572
5573 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5574 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5575 if is_edited != self.window_edited {
5576 self.window_edited = is_edited;
5577 window.set_window_edited(self.window_edited)
5578 }
5579 }
5580
5581 fn update_item_dirty_state(
5582 &mut self,
5583 item: &dyn ItemHandle,
5584 window: &mut Window,
5585 cx: &mut App,
5586 ) {
5587 let is_dirty = item.is_dirty(cx);
5588 let item_id = item.item_id();
5589 let was_dirty = self.dirty_items.contains_key(&item_id);
5590 if is_dirty == was_dirty {
5591 return;
5592 }
5593 if was_dirty {
5594 self.dirty_items.remove(&item_id);
5595 self.update_window_edited(window, cx);
5596 return;
5597 }
5598
5599 let workspace = self.weak_handle();
5600 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5601 return;
5602 };
5603 let on_release_callback = Box::new(move |cx: &mut App| {
5604 window_handle
5605 .update(cx, |_, window, cx| {
5606 workspace
5607 .update(cx, |workspace, cx| {
5608 workspace.dirty_items.remove(&item_id);
5609 workspace.update_window_edited(window, cx)
5610 })
5611 .ok();
5612 })
5613 .ok();
5614 });
5615
5616 let s = item.on_release(cx, on_release_callback);
5617 self.dirty_items.insert(item_id, s);
5618 self.update_window_edited(window, cx);
5619 }
5620
5621 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5622 if self.notifications.is_empty() {
5623 None
5624 } else {
5625 Some(
5626 div()
5627 .absolute()
5628 .right_3()
5629 .bottom_3()
5630 .w_112()
5631 .h_full()
5632 .flex()
5633 .flex_col()
5634 .justify_end()
5635 .gap_2()
5636 .children(
5637 self.notifications
5638 .iter()
5639 .map(|(_, notification)| notification.clone().into_any()),
5640 ),
5641 )
5642 }
5643 }
5644
5645 // RPC handlers
5646
5647 fn active_view_for_follower(
5648 &self,
5649 follower_project_id: Option<u64>,
5650 window: &mut Window,
5651 cx: &mut Context<Self>,
5652 ) -> Option<proto::View> {
5653 let (item, panel_id) = self.active_item_for_followers(window, cx);
5654 let item = item?;
5655 let leader_id = self
5656 .pane_for(&*item)
5657 .and_then(|pane| self.leader_for_pane(&pane));
5658 let leader_peer_id = match leader_id {
5659 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5660 Some(CollaboratorId::Agent) | None => None,
5661 };
5662
5663 let item_handle = item.to_followable_item_handle(cx)?;
5664 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5665 let variant = item_handle.to_state_proto(window, cx)?;
5666
5667 if item_handle.is_project_item(window, cx)
5668 && (follower_project_id.is_none()
5669 || follower_project_id != self.project.read(cx).remote_id())
5670 {
5671 return None;
5672 }
5673
5674 Some(proto::View {
5675 id: id.to_proto(),
5676 leader_id: leader_peer_id,
5677 variant: Some(variant),
5678 panel_id: panel_id.map(|id| id as i32),
5679 })
5680 }
5681
5682 fn handle_follow(
5683 &mut self,
5684 follower_project_id: Option<u64>,
5685 window: &mut Window,
5686 cx: &mut Context<Self>,
5687 ) -> proto::FollowResponse {
5688 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5689
5690 cx.notify();
5691 proto::FollowResponse {
5692 views: active_view.iter().cloned().collect(),
5693 active_view,
5694 }
5695 }
5696
5697 fn handle_update_followers(
5698 &mut self,
5699 leader_id: PeerId,
5700 message: proto::UpdateFollowers,
5701 _window: &mut Window,
5702 _cx: &mut Context<Self>,
5703 ) {
5704 self.leader_updates_tx
5705 .unbounded_send((leader_id, message))
5706 .ok();
5707 }
5708
5709 async fn process_leader_update(
5710 this: &WeakEntity<Self>,
5711 leader_id: PeerId,
5712 update: proto::UpdateFollowers,
5713 cx: &mut AsyncWindowContext,
5714 ) -> Result<()> {
5715 match update.variant.context("invalid update")? {
5716 proto::update_followers::Variant::CreateView(view) => {
5717 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5718 let should_add_view = this.update(cx, |this, _| {
5719 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5720 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5721 } else {
5722 anyhow::Ok(false)
5723 }
5724 })??;
5725
5726 if should_add_view {
5727 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5728 }
5729 }
5730 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5731 let should_add_view = this.update(cx, |this, _| {
5732 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5733 state.active_view_id = update_active_view
5734 .view
5735 .as_ref()
5736 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5737
5738 if state.active_view_id.is_some_and(|view_id| {
5739 !state.items_by_leader_view_id.contains_key(&view_id)
5740 }) {
5741 anyhow::Ok(true)
5742 } else {
5743 anyhow::Ok(false)
5744 }
5745 } else {
5746 anyhow::Ok(false)
5747 }
5748 })??;
5749
5750 if should_add_view && let Some(view) = update_active_view.view {
5751 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5752 }
5753 }
5754 proto::update_followers::Variant::UpdateView(update_view) => {
5755 let variant = update_view.variant.context("missing update view variant")?;
5756 let id = update_view.id.context("missing update view id")?;
5757 let mut tasks = Vec::new();
5758 this.update_in(cx, |this, window, cx| {
5759 let project = this.project.clone();
5760 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5761 let view_id = ViewId::from_proto(id.clone())?;
5762 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5763 tasks.push(item.view.apply_update_proto(
5764 &project,
5765 variant.clone(),
5766 window,
5767 cx,
5768 ));
5769 }
5770 }
5771 anyhow::Ok(())
5772 })??;
5773 try_join_all(tasks).await.log_err();
5774 }
5775 }
5776 this.update_in(cx, |this, window, cx| {
5777 this.leader_updated(leader_id, window, cx)
5778 })?;
5779 Ok(())
5780 }
5781
5782 async fn add_view_from_leader(
5783 this: WeakEntity<Self>,
5784 leader_id: PeerId,
5785 view: &proto::View,
5786 cx: &mut AsyncWindowContext,
5787 ) -> Result<()> {
5788 let this = this.upgrade().context("workspace dropped")?;
5789
5790 let Some(id) = view.id.clone() else {
5791 anyhow::bail!("no id for view");
5792 };
5793 let id = ViewId::from_proto(id)?;
5794 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5795
5796 let pane = this.update(cx, |this, _cx| {
5797 let state = this
5798 .follower_states
5799 .get(&leader_id.into())
5800 .context("stopped following")?;
5801 anyhow::Ok(state.pane().clone())
5802 })?;
5803 let existing_item = pane.update_in(cx, |pane, window, cx| {
5804 let client = this.read(cx).client().clone();
5805 pane.items().find_map(|item| {
5806 let item = item.to_followable_item_handle(cx)?;
5807 if item.remote_id(&client, window, cx) == Some(id) {
5808 Some(item)
5809 } else {
5810 None
5811 }
5812 })
5813 })?;
5814 let item = if let Some(existing_item) = existing_item {
5815 existing_item
5816 } else {
5817 let variant = view.variant.clone();
5818 anyhow::ensure!(variant.is_some(), "missing view variant");
5819
5820 let task = cx.update(|window, cx| {
5821 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5822 })?;
5823
5824 let Some(task) = task else {
5825 anyhow::bail!(
5826 "failed to construct view from leader (maybe from a different version of zed?)"
5827 );
5828 };
5829
5830 let mut new_item = task.await?;
5831 pane.update_in(cx, |pane, window, cx| {
5832 let mut item_to_remove = None;
5833 for (ix, item) in pane.items().enumerate() {
5834 if let Some(item) = item.to_followable_item_handle(cx) {
5835 match new_item.dedup(item.as_ref(), window, cx) {
5836 Some(item::Dedup::KeepExisting) => {
5837 new_item =
5838 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5839 break;
5840 }
5841 Some(item::Dedup::ReplaceExisting) => {
5842 item_to_remove = Some((ix, item.item_id()));
5843 break;
5844 }
5845 None => {}
5846 }
5847 }
5848 }
5849
5850 if let Some((ix, id)) = item_to_remove {
5851 pane.remove_item(id, false, false, window, cx);
5852 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5853 }
5854 })?;
5855
5856 new_item
5857 };
5858
5859 this.update_in(cx, |this, window, cx| {
5860 let state = this.follower_states.get_mut(&leader_id.into())?;
5861 item.set_leader_id(Some(leader_id.into()), window, cx);
5862 state.items_by_leader_view_id.insert(
5863 id,
5864 FollowerView {
5865 view: item,
5866 location: panel_id,
5867 },
5868 );
5869
5870 Some(())
5871 })
5872 .context("no follower state")?;
5873
5874 Ok(())
5875 }
5876
5877 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5878 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5879 return;
5880 };
5881
5882 if let Some(agent_location) = self.project.read(cx).agent_location() {
5883 let buffer_entity_id = agent_location.buffer.entity_id();
5884 let view_id = ViewId {
5885 creator: CollaboratorId::Agent,
5886 id: buffer_entity_id.as_u64(),
5887 };
5888 follower_state.active_view_id = Some(view_id);
5889
5890 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5891 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5892 hash_map::Entry::Vacant(entry) => {
5893 let existing_view =
5894 follower_state
5895 .center_pane
5896 .read(cx)
5897 .items()
5898 .find_map(|item| {
5899 let item = item.to_followable_item_handle(cx)?;
5900 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5901 && item.project_item_model_ids(cx).as_slice()
5902 == [buffer_entity_id]
5903 {
5904 Some(item)
5905 } else {
5906 None
5907 }
5908 });
5909 let view = existing_view.or_else(|| {
5910 agent_location.buffer.upgrade().and_then(|buffer| {
5911 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
5912 registry.build_item(buffer, self.project.clone(), None, window, cx)
5913 })?
5914 .to_followable_item_handle(cx)
5915 })
5916 });
5917
5918 view.map(|view| {
5919 entry.insert(FollowerView {
5920 view,
5921 location: None,
5922 })
5923 })
5924 }
5925 };
5926
5927 if let Some(item) = item {
5928 item.view
5929 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
5930 item.view
5931 .update_agent_location(agent_location.position, window, cx);
5932 }
5933 } else {
5934 follower_state.active_view_id = None;
5935 }
5936
5937 self.leader_updated(CollaboratorId::Agent, window, cx);
5938 }
5939
5940 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
5941 let mut is_project_item = true;
5942 let mut update = proto::UpdateActiveView::default();
5943 if window.is_window_active() {
5944 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
5945
5946 if let Some(item) = active_item
5947 && item.item_focus_handle(cx).contains_focused(window, cx)
5948 {
5949 let leader_id = self
5950 .pane_for(&*item)
5951 .and_then(|pane| self.leader_for_pane(&pane));
5952 let leader_peer_id = match leader_id {
5953 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5954 Some(CollaboratorId::Agent) | None => None,
5955 };
5956
5957 if let Some(item) = item.to_followable_item_handle(cx) {
5958 let id = item
5959 .remote_id(&self.app_state.client, window, cx)
5960 .map(|id| id.to_proto());
5961
5962 if let Some(id) = id
5963 && let Some(variant) = item.to_state_proto(window, cx)
5964 {
5965 let view = Some(proto::View {
5966 id,
5967 leader_id: leader_peer_id,
5968 variant: Some(variant),
5969 panel_id: panel_id.map(|id| id as i32),
5970 });
5971
5972 is_project_item = item.is_project_item(window, cx);
5973 update = proto::UpdateActiveView { view };
5974 };
5975 }
5976 }
5977 }
5978
5979 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
5980 if active_view_id != self.last_active_view_id.as_ref() {
5981 self.last_active_view_id = active_view_id.cloned();
5982 self.update_followers(
5983 is_project_item,
5984 proto::update_followers::Variant::UpdateActiveView(update),
5985 window,
5986 cx,
5987 );
5988 }
5989 }
5990
5991 fn active_item_for_followers(
5992 &self,
5993 window: &mut Window,
5994 cx: &mut App,
5995 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
5996 let mut active_item = None;
5997 let mut panel_id = None;
5998 for dock in self.all_docks() {
5999 if dock.focus_handle(cx).contains_focused(window, cx)
6000 && let Some(panel) = dock.read(cx).active_panel()
6001 && let Some(pane) = panel.pane(cx)
6002 && let Some(item) = pane.read(cx).active_item()
6003 {
6004 active_item = Some(item);
6005 panel_id = panel.remote_id();
6006 break;
6007 }
6008 }
6009
6010 if active_item.is_none() {
6011 active_item = self.active_pane().read(cx).active_item();
6012 }
6013 (active_item, panel_id)
6014 }
6015
6016 fn update_followers(
6017 &self,
6018 project_only: bool,
6019 update: proto::update_followers::Variant,
6020 _: &mut Window,
6021 cx: &mut App,
6022 ) -> Option<()> {
6023 // If this update only applies to for followers in the current project,
6024 // then skip it unless this project is shared. If it applies to all
6025 // followers, regardless of project, then set `project_id` to none,
6026 // indicating that it goes to all followers.
6027 let project_id = if project_only {
6028 Some(self.project.read(cx).remote_id()?)
6029 } else {
6030 None
6031 };
6032 self.app_state().workspace_store.update(cx, |store, cx| {
6033 store.update_followers(project_id, update, cx)
6034 })
6035 }
6036
6037 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
6038 self.follower_states.iter().find_map(|(leader_id, state)| {
6039 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
6040 Some(*leader_id)
6041 } else {
6042 None
6043 }
6044 })
6045 }
6046
6047 fn leader_updated(
6048 &mut self,
6049 leader_id: impl Into<CollaboratorId>,
6050 window: &mut Window,
6051 cx: &mut Context<Self>,
6052 ) -> Option<Box<dyn ItemHandle>> {
6053 cx.notify();
6054
6055 let leader_id = leader_id.into();
6056 let (panel_id, item) = match leader_id {
6057 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
6058 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
6059 };
6060
6061 let state = self.follower_states.get(&leader_id)?;
6062 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
6063 let pane;
6064 if let Some(panel_id) = panel_id {
6065 pane = self
6066 .activate_panel_for_proto_id(panel_id, window, cx)?
6067 .pane(cx)?;
6068 let state = self.follower_states.get_mut(&leader_id)?;
6069 state.dock_pane = Some(pane.clone());
6070 } else {
6071 pane = state.center_pane.clone();
6072 let state = self.follower_states.get_mut(&leader_id)?;
6073 if let Some(dock_pane) = state.dock_pane.take() {
6074 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
6075 }
6076 }
6077
6078 pane.update(cx, |pane, cx| {
6079 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
6080 if let Some(index) = pane.index_for_item(item.as_ref()) {
6081 pane.activate_item(index, false, false, window, cx);
6082 } else {
6083 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
6084 }
6085
6086 if focus_active_item {
6087 pane.focus_active_item(window, cx)
6088 }
6089 });
6090
6091 Some(item)
6092 }
6093
6094 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
6095 let state = self.follower_states.get(&CollaboratorId::Agent)?;
6096 let active_view_id = state.active_view_id?;
6097 Some(
6098 state
6099 .items_by_leader_view_id
6100 .get(&active_view_id)?
6101 .view
6102 .boxed_clone(),
6103 )
6104 }
6105
6106 fn active_item_for_peer(
6107 &self,
6108 peer_id: PeerId,
6109 window: &mut Window,
6110 cx: &mut Context<Self>,
6111 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
6112 let call = self.active_call()?;
6113 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
6114 let leader_in_this_app;
6115 let leader_in_this_project;
6116 match participant.location {
6117 ParticipantLocation::SharedProject { project_id } => {
6118 leader_in_this_app = true;
6119 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
6120 }
6121 ParticipantLocation::UnsharedProject => {
6122 leader_in_this_app = true;
6123 leader_in_this_project = false;
6124 }
6125 ParticipantLocation::External => {
6126 leader_in_this_app = false;
6127 leader_in_this_project = false;
6128 }
6129 };
6130 let state = self.follower_states.get(&peer_id.into())?;
6131 let mut item_to_activate = None;
6132 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
6133 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
6134 && (leader_in_this_project || !item.view.is_project_item(window, cx))
6135 {
6136 item_to_activate = Some((item.location, item.view.boxed_clone()));
6137 }
6138 } else if let Some(shared_screen) =
6139 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
6140 {
6141 item_to_activate = Some((None, Box::new(shared_screen)));
6142 }
6143 item_to_activate
6144 }
6145
6146 fn shared_screen_for_peer(
6147 &self,
6148 peer_id: PeerId,
6149 pane: &Entity<Pane>,
6150 window: &mut Window,
6151 cx: &mut App,
6152 ) -> Option<Entity<SharedScreen>> {
6153 self.active_call()?
6154 .create_shared_screen(peer_id, pane, window, cx)
6155 }
6156
6157 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6158 if window.is_window_active() {
6159 self.update_active_view_for_followers(window, cx);
6160
6161 if let Some(database_id) = self.database_id {
6162 let db = WorkspaceDb::global(cx);
6163 cx.background_spawn(async move { db.update_timestamp(database_id).await })
6164 .detach();
6165 }
6166 } else {
6167 for pane in &self.panes {
6168 pane.update(cx, |pane, cx| {
6169 if let Some(item) = pane.active_item() {
6170 item.workspace_deactivated(window, cx);
6171 }
6172 for item in pane.items() {
6173 if matches!(
6174 item.workspace_settings(cx).autosave,
6175 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
6176 ) {
6177 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
6178 .detach_and_log_err(cx);
6179 }
6180 }
6181 });
6182 }
6183 }
6184 }
6185
6186 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
6187 self.active_call.as_ref().map(|(call, _)| &*call.0)
6188 }
6189
6190 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
6191 self.active_call.as_ref().map(|(call, _)| call.clone())
6192 }
6193
6194 fn on_active_call_event(
6195 &mut self,
6196 event: &ActiveCallEvent,
6197 window: &mut Window,
6198 cx: &mut Context<Self>,
6199 ) {
6200 match event {
6201 ActiveCallEvent::ParticipantLocationChanged { participant_id }
6202 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
6203 self.leader_updated(participant_id, window, cx);
6204 }
6205 }
6206 }
6207
6208 pub fn database_id(&self) -> Option<WorkspaceId> {
6209 self.database_id
6210 }
6211
6212 #[cfg(any(test, feature = "test-support"))]
6213 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
6214 self.database_id = Some(id);
6215 }
6216
6217 pub fn session_id(&self) -> Option<String> {
6218 self.session_id.clone()
6219 }
6220
6221 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6222 let Some(display) = window.display(cx) else {
6223 return Task::ready(());
6224 };
6225 let Ok(display_uuid) = display.uuid() else {
6226 return Task::ready(());
6227 };
6228
6229 let window_bounds = window.inner_window_bounds();
6230 let database_id = self.database_id;
6231 let has_paths = !self.root_paths(cx).is_empty();
6232 let db = WorkspaceDb::global(cx);
6233 let kvp = db::kvp::KeyValueStore::global(cx);
6234
6235 cx.background_executor().spawn(async move {
6236 if !has_paths {
6237 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6238 .await
6239 .log_err();
6240 }
6241 if let Some(database_id) = database_id {
6242 db.set_window_open_status(
6243 database_id,
6244 SerializedWindowBounds(window_bounds),
6245 display_uuid,
6246 )
6247 .await
6248 .log_err();
6249 } else {
6250 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6251 .await
6252 .log_err();
6253 }
6254 })
6255 }
6256
6257 /// Bypass the 200ms serialization throttle and write workspace state to
6258 /// the DB immediately. Returns a task the caller can await to ensure the
6259 /// write completes. Used by the quit handler so the most recent state
6260 /// isn't lost to a pending throttle timer when the process exits.
6261 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6262 self._schedule_serialize_workspace.take();
6263 self._serialize_workspace_task.take();
6264 self.bounds_save_task_queued.take();
6265
6266 let bounds_task = self.save_window_bounds(window, cx);
6267 let serialize_task = self.serialize_workspace_internal(window, cx);
6268 cx.spawn(async move |_| {
6269 bounds_task.await;
6270 serialize_task.await;
6271 })
6272 }
6273
6274 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6275 let project = self.project().read(cx);
6276 project
6277 .visible_worktrees(cx)
6278 .map(|worktree| worktree.read(cx).abs_path())
6279 .collect::<Vec<_>>()
6280 }
6281
6282 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6283 match member {
6284 Member::Axis(PaneAxis { members, .. }) => {
6285 for child in members.iter() {
6286 self.remove_panes(child.clone(), window, cx)
6287 }
6288 }
6289 Member::Pane(pane) => {
6290 self.force_remove_pane(&pane, &None, window, cx);
6291 }
6292 }
6293 }
6294
6295 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6296 self.session_id.take();
6297 self.serialize_workspace_internal(window, cx)
6298 }
6299
6300 fn force_remove_pane(
6301 &mut self,
6302 pane: &Entity<Pane>,
6303 focus_on: &Option<Entity<Pane>>,
6304 window: &mut Window,
6305 cx: &mut Context<Workspace>,
6306 ) {
6307 self.panes.retain(|p| p != pane);
6308 if let Some(focus_on) = focus_on {
6309 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6310 } else if self.active_pane() == pane {
6311 self.panes
6312 .last()
6313 .unwrap()
6314 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6315 }
6316 if self.last_active_center_pane == Some(pane.downgrade()) {
6317 self.last_active_center_pane = None;
6318 }
6319 cx.notify();
6320 }
6321
6322 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6323 if self._schedule_serialize_workspace.is_none() {
6324 self._schedule_serialize_workspace =
6325 Some(cx.spawn_in(window, async move |this, cx| {
6326 cx.background_executor()
6327 .timer(SERIALIZATION_THROTTLE_TIME)
6328 .await;
6329 this.update_in(cx, |this, window, cx| {
6330 this._serialize_workspace_task =
6331 Some(this.serialize_workspace_internal(window, cx));
6332 this._schedule_serialize_workspace.take();
6333 })
6334 .log_err();
6335 }));
6336 }
6337 }
6338
6339 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6340 let Some(database_id) = self.database_id() else {
6341 return Task::ready(());
6342 };
6343
6344 fn serialize_pane_handle(
6345 pane_handle: &Entity<Pane>,
6346 window: &mut Window,
6347 cx: &mut App,
6348 ) -> SerializedPane {
6349 let (items, active, pinned_count) = {
6350 let pane = pane_handle.read(cx);
6351 let active_item_id = pane.active_item().map(|item| item.item_id());
6352 (
6353 pane.items()
6354 .filter_map(|handle| {
6355 let handle = handle.to_serializable_item_handle(cx)?;
6356
6357 Some(SerializedItem {
6358 kind: Arc::from(handle.serialized_item_kind()),
6359 item_id: handle.item_id().as_u64(),
6360 active: Some(handle.item_id()) == active_item_id,
6361 preview: pane.is_active_preview_item(handle.item_id()),
6362 })
6363 })
6364 .collect::<Vec<_>>(),
6365 pane.has_focus(window, cx),
6366 pane.pinned_count(),
6367 )
6368 };
6369
6370 SerializedPane::new(items, active, pinned_count)
6371 }
6372
6373 fn build_serialized_pane_group(
6374 pane_group: &Member,
6375 window: &mut Window,
6376 cx: &mut App,
6377 ) -> SerializedPaneGroup {
6378 match pane_group {
6379 Member::Axis(PaneAxis {
6380 axis,
6381 members,
6382 flexes,
6383 bounding_boxes: _,
6384 }) => SerializedPaneGroup::Group {
6385 axis: SerializedAxis(*axis),
6386 children: members
6387 .iter()
6388 .map(|member| build_serialized_pane_group(member, window, cx))
6389 .collect::<Vec<_>>(),
6390 flexes: Some(flexes.lock().clone()),
6391 },
6392 Member::Pane(pane_handle) => {
6393 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6394 }
6395 }
6396 }
6397
6398 fn build_serialized_docks(
6399 this: &Workspace,
6400 window: &mut Window,
6401 cx: &mut App,
6402 ) -> DockStructure {
6403 this.capture_dock_state(window, cx)
6404 }
6405
6406 match self.workspace_location(cx) {
6407 WorkspaceLocation::Location(location, paths) => {
6408 let breakpoints = self.project.update(cx, |project, cx| {
6409 project
6410 .breakpoint_store()
6411 .read(cx)
6412 .all_source_breakpoints(cx)
6413 });
6414 let user_toolchains = self
6415 .project
6416 .read(cx)
6417 .user_toolchains(cx)
6418 .unwrap_or_default();
6419
6420 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6421 let docks = build_serialized_docks(self, window, cx);
6422 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6423
6424 let serialized_workspace = SerializedWorkspace {
6425 id: database_id,
6426 location,
6427 paths,
6428 center_group,
6429 window_bounds,
6430 display: Default::default(),
6431 docks,
6432 centered_layout: self.centered_layout,
6433 session_id: self.session_id.clone(),
6434 breakpoints,
6435 window_id: Some(window.window_handle().window_id().as_u64()),
6436 user_toolchains,
6437 };
6438
6439 let db = WorkspaceDb::global(cx);
6440 window.spawn(cx, async move |_| {
6441 db.save_workspace(serialized_workspace).await;
6442 })
6443 }
6444 WorkspaceLocation::DetachFromSession => {
6445 let window_bounds = SerializedWindowBounds(window.window_bounds());
6446 let display = window.display(cx).and_then(|d| d.uuid().ok());
6447 // Save dock state for empty local workspaces
6448 let docks = build_serialized_docks(self, window, cx);
6449 let db = WorkspaceDb::global(cx);
6450 let kvp = db::kvp::KeyValueStore::global(cx);
6451 window.spawn(cx, async move |_| {
6452 db.set_window_open_status(
6453 database_id,
6454 window_bounds,
6455 display.unwrap_or_default(),
6456 )
6457 .await
6458 .log_err();
6459 db.set_session_id(database_id, None).await.log_err();
6460 persistence::write_default_dock_state(&kvp, docks)
6461 .await
6462 .log_err();
6463 })
6464 }
6465 WorkspaceLocation::None => {
6466 // Save dock state for empty non-local workspaces
6467 let docks = build_serialized_docks(self, window, cx);
6468 let kvp = db::kvp::KeyValueStore::global(cx);
6469 window.spawn(cx, async move |_| {
6470 persistence::write_default_dock_state(&kvp, docks)
6471 .await
6472 .log_err();
6473 })
6474 }
6475 }
6476 }
6477
6478 fn has_any_items_open(&self, cx: &App) -> bool {
6479 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6480 }
6481
6482 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6483 let paths = PathList::new(&self.root_paths(cx));
6484 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6485 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6486 } else if self.project.read(cx).is_local() {
6487 if !paths.is_empty() || self.has_any_items_open(cx) {
6488 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6489 } else {
6490 WorkspaceLocation::DetachFromSession
6491 }
6492 } else {
6493 WorkspaceLocation::None
6494 }
6495 }
6496
6497 fn update_history(&self, cx: &mut App) {
6498 let Some(id) = self.database_id() else {
6499 return;
6500 };
6501 if !self.project.read(cx).is_local() {
6502 return;
6503 }
6504 if let Some(manager) = HistoryManager::global(cx) {
6505 let paths = PathList::new(&self.root_paths(cx));
6506 manager.update(cx, |this, cx| {
6507 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6508 });
6509 }
6510 }
6511
6512 async fn serialize_items(
6513 this: &WeakEntity<Self>,
6514 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6515 cx: &mut AsyncWindowContext,
6516 ) -> Result<()> {
6517 const CHUNK_SIZE: usize = 200;
6518
6519 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6520
6521 while let Some(items_received) = serializable_items.next().await {
6522 let unique_items =
6523 items_received
6524 .into_iter()
6525 .fold(HashMap::default(), |mut acc, item| {
6526 acc.entry(item.item_id()).or_insert(item);
6527 acc
6528 });
6529
6530 // We use into_iter() here so that the references to the items are moved into
6531 // the tasks and not kept alive while we're sleeping.
6532 for (_, item) in unique_items.into_iter() {
6533 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6534 item.serialize(workspace, false, window, cx)
6535 }) {
6536 cx.background_spawn(async move { task.await.log_err() })
6537 .detach();
6538 }
6539 }
6540
6541 cx.background_executor()
6542 .timer(SERIALIZATION_THROTTLE_TIME)
6543 .await;
6544 }
6545
6546 Ok(())
6547 }
6548
6549 pub(crate) fn enqueue_item_serialization(
6550 &mut self,
6551 item: Box<dyn SerializableItemHandle>,
6552 ) -> Result<()> {
6553 self.serializable_items_tx
6554 .unbounded_send(item)
6555 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6556 }
6557
6558 pub(crate) fn load_workspace(
6559 serialized_workspace: SerializedWorkspace,
6560 paths_to_open: Vec<Option<ProjectPath>>,
6561 window: &mut Window,
6562 cx: &mut Context<Workspace>,
6563 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6564 cx.spawn_in(window, async move |workspace, cx| {
6565 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6566
6567 let mut center_group = None;
6568 let mut center_items = None;
6569
6570 // Traverse the splits tree and add to things
6571 if let Some((group, active_pane, items)) = serialized_workspace
6572 .center_group
6573 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6574 .await
6575 {
6576 center_items = Some(items);
6577 center_group = Some((group, active_pane))
6578 }
6579
6580 let mut items_by_project_path = HashMap::default();
6581 let mut item_ids_by_kind = HashMap::default();
6582 let mut all_deserialized_items = Vec::default();
6583 cx.update(|_, cx| {
6584 for item in center_items.unwrap_or_default().into_iter().flatten() {
6585 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6586 item_ids_by_kind
6587 .entry(serializable_item_handle.serialized_item_kind())
6588 .or_insert(Vec::new())
6589 .push(item.item_id().as_u64() as ItemId);
6590 }
6591
6592 if let Some(project_path) = item.project_path(cx) {
6593 items_by_project_path.insert(project_path, item.clone());
6594 }
6595 all_deserialized_items.push(item);
6596 }
6597 })?;
6598
6599 let opened_items = paths_to_open
6600 .into_iter()
6601 .map(|path_to_open| {
6602 path_to_open
6603 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6604 })
6605 .collect::<Vec<_>>();
6606
6607 // Remove old panes from workspace panes list
6608 workspace.update_in(cx, |workspace, window, cx| {
6609 if let Some((center_group, active_pane)) = center_group {
6610 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6611
6612 // Swap workspace center group
6613 workspace.center = PaneGroup::with_root(center_group);
6614 workspace.center.set_is_center(true);
6615 workspace.center.mark_positions(cx);
6616
6617 if let Some(active_pane) = active_pane {
6618 workspace.set_active_pane(&active_pane, window, cx);
6619 cx.focus_self(window);
6620 } else {
6621 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6622 }
6623 }
6624
6625 let docks = serialized_workspace.docks;
6626
6627 for (dock, serialized_dock) in [
6628 (&mut workspace.right_dock, docks.right),
6629 (&mut workspace.left_dock, docks.left),
6630 (&mut workspace.bottom_dock, docks.bottom),
6631 ]
6632 .iter_mut()
6633 {
6634 dock.update(cx, |dock, cx| {
6635 dock.serialized_dock = Some(serialized_dock.clone());
6636 dock.restore_state(window, cx);
6637 });
6638 }
6639
6640 cx.notify();
6641 })?;
6642
6643 let _ = project
6644 .update(cx, |project, cx| {
6645 project
6646 .breakpoint_store()
6647 .update(cx, |breakpoint_store, cx| {
6648 breakpoint_store
6649 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6650 })
6651 })
6652 .await;
6653
6654 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6655 // after loading the items, we might have different items and in order to avoid
6656 // the database filling up, we delete items that haven't been loaded now.
6657 //
6658 // The items that have been loaded, have been saved after they've been added to the workspace.
6659 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6660 item_ids_by_kind
6661 .into_iter()
6662 .map(|(item_kind, loaded_items)| {
6663 SerializableItemRegistry::cleanup(
6664 item_kind,
6665 serialized_workspace.id,
6666 loaded_items,
6667 window,
6668 cx,
6669 )
6670 .log_err()
6671 })
6672 .collect::<Vec<_>>()
6673 })?;
6674
6675 futures::future::join_all(clean_up_tasks).await;
6676
6677 workspace
6678 .update_in(cx, |workspace, window, cx| {
6679 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6680 workspace.serialize_workspace_internal(window, cx).detach();
6681
6682 // Ensure that we mark the window as edited if we did load dirty items
6683 workspace.update_window_edited(window, cx);
6684 })
6685 .ok();
6686
6687 Ok(opened_items)
6688 })
6689 }
6690
6691 pub fn key_context(&self, cx: &App) -> KeyContext {
6692 let mut context = KeyContext::new_with_defaults();
6693 context.add("Workspace");
6694 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6695 if let Some(status) = self
6696 .debugger_provider
6697 .as_ref()
6698 .and_then(|provider| provider.active_thread_state(cx))
6699 {
6700 match status {
6701 ThreadStatus::Running | ThreadStatus::Stepping => {
6702 context.add("debugger_running");
6703 }
6704 ThreadStatus::Stopped => context.add("debugger_stopped"),
6705 ThreadStatus::Exited | ThreadStatus::Ended => {}
6706 }
6707 }
6708
6709 if self.left_dock.read(cx).is_open() {
6710 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6711 context.set("left_dock", active_panel.panel_key());
6712 }
6713 }
6714
6715 if self.right_dock.read(cx).is_open() {
6716 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6717 context.set("right_dock", active_panel.panel_key());
6718 }
6719 }
6720
6721 if self.bottom_dock.read(cx).is_open() {
6722 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6723 context.set("bottom_dock", active_panel.panel_key());
6724 }
6725 }
6726
6727 context
6728 }
6729
6730 /// Multiworkspace uses this to add workspace action handling to itself
6731 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6732 self.add_workspace_actions_listeners(div, window, cx)
6733 .on_action(cx.listener(
6734 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6735 for action in &action_sequence.0 {
6736 window.dispatch_action(action.boxed_clone(), cx);
6737 }
6738 },
6739 ))
6740 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6741 .on_action(cx.listener(Self::close_all_items_and_panes))
6742 .on_action(cx.listener(Self::close_item_in_all_panes))
6743 .on_action(cx.listener(Self::save_all))
6744 .on_action(cx.listener(Self::send_keystrokes))
6745 .on_action(cx.listener(Self::add_folder_to_project))
6746 .on_action(cx.listener(Self::follow_next_collaborator))
6747 .on_action(cx.listener(Self::activate_pane_at_index))
6748 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6749 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6750 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6751 .on_action(cx.listener(Self::toggle_theme_mode))
6752 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6753 let pane = workspace.active_pane().clone();
6754 workspace.unfollow_in_pane(&pane, window, cx);
6755 }))
6756 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6757 workspace
6758 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6759 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6760 }))
6761 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6762 workspace
6763 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6764 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6765 }))
6766 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6767 workspace
6768 .save_active_item(SaveIntent::SaveAs, window, cx)
6769 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6770 }))
6771 .on_action(
6772 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6773 workspace.activate_previous_pane(window, cx)
6774 }),
6775 )
6776 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6777 workspace.activate_next_pane(window, cx)
6778 }))
6779 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6780 workspace.activate_last_pane(window, cx)
6781 }))
6782 .on_action(
6783 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6784 workspace.activate_next_window(cx)
6785 }),
6786 )
6787 .on_action(
6788 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6789 workspace.activate_previous_window(cx)
6790 }),
6791 )
6792 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6793 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6794 }))
6795 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6796 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6797 }))
6798 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6799 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6800 }))
6801 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6802 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6803 }))
6804 .on_action(cx.listener(
6805 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6806 workspace.move_item_to_pane_in_direction(action, window, cx)
6807 },
6808 ))
6809 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6810 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6811 }))
6812 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6813 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6814 }))
6815 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6816 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6817 }))
6818 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6819 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6820 }))
6821 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6822 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6823 SplitDirection::Down,
6824 SplitDirection::Up,
6825 SplitDirection::Right,
6826 SplitDirection::Left,
6827 ];
6828 for dir in DIRECTION_PRIORITY {
6829 if workspace.find_pane_in_direction(dir, cx).is_some() {
6830 workspace.swap_pane_in_direction(dir, cx);
6831 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6832 break;
6833 }
6834 }
6835 }))
6836 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6837 workspace.move_pane_to_border(SplitDirection::Left, cx)
6838 }))
6839 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6840 workspace.move_pane_to_border(SplitDirection::Right, cx)
6841 }))
6842 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6843 workspace.move_pane_to_border(SplitDirection::Up, cx)
6844 }))
6845 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6846 workspace.move_pane_to_border(SplitDirection::Down, cx)
6847 }))
6848 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6849 this.toggle_dock(DockPosition::Left, window, cx);
6850 }))
6851 .on_action(cx.listener(
6852 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6853 workspace.toggle_dock(DockPosition::Right, window, cx);
6854 },
6855 ))
6856 .on_action(cx.listener(
6857 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6858 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6859 },
6860 ))
6861 .on_action(cx.listener(
6862 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6863 if !workspace.close_active_dock(window, cx) {
6864 cx.propagate();
6865 }
6866 },
6867 ))
6868 .on_action(
6869 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6870 workspace.close_all_docks(window, cx);
6871 }),
6872 )
6873 .on_action(cx.listener(Self::toggle_all_docks))
6874 .on_action(cx.listener(
6875 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6876 workspace.clear_all_notifications(cx);
6877 },
6878 ))
6879 .on_action(cx.listener(
6880 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6881 workspace.clear_navigation_history(window, cx);
6882 },
6883 ))
6884 .on_action(cx.listener(
6885 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6886 if let Some((notification_id, _)) = workspace.notifications.pop() {
6887 workspace.suppress_notification(¬ification_id, cx);
6888 }
6889 },
6890 ))
6891 .on_action(cx.listener(
6892 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6893 workspace.show_worktree_trust_security_modal(true, window, cx);
6894 },
6895 ))
6896 .on_action(
6897 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6898 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6899 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6900 trusted_worktrees.clear_trusted_paths()
6901 });
6902 let db = WorkspaceDb::global(cx);
6903 cx.spawn(async move |_, cx| {
6904 if db.clear_trusted_worktrees().await.log_err().is_some() {
6905 cx.update(|cx| reload(cx));
6906 }
6907 })
6908 .detach();
6909 }
6910 }),
6911 )
6912 .on_action(cx.listener(
6913 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
6914 workspace.reopen_closed_item(window, cx).detach();
6915 },
6916 ))
6917 .on_action(cx.listener(
6918 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
6919 for dock in workspace.all_docks() {
6920 if dock.focus_handle(cx).contains_focused(window, cx) {
6921 let panel = dock.read(cx).active_panel().cloned();
6922 if let Some(panel) = panel {
6923 dock.update(cx, |dock, cx| {
6924 dock.set_panel_size_state(
6925 panel.as_ref(),
6926 dock::PanelSizeState::default(),
6927 cx,
6928 );
6929 });
6930 }
6931 return;
6932 }
6933 }
6934 },
6935 ))
6936 .on_action(cx.listener(
6937 |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
6938 for dock in workspace.all_docks() {
6939 let panel = dock.read(cx).visible_panel().cloned();
6940 if let Some(panel) = panel {
6941 dock.update(cx, |dock, cx| {
6942 dock.set_panel_size_state(
6943 panel.as_ref(),
6944 dock::PanelSizeState::default(),
6945 cx,
6946 );
6947 });
6948 }
6949 }
6950 },
6951 ))
6952 .on_action(cx.listener(
6953 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
6954 adjust_active_dock_size_by_px(
6955 px_with_ui_font_fallback(act.px, cx),
6956 workspace,
6957 window,
6958 cx,
6959 );
6960 },
6961 ))
6962 .on_action(cx.listener(
6963 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
6964 adjust_active_dock_size_by_px(
6965 px_with_ui_font_fallback(act.px, cx) * -1.,
6966 workspace,
6967 window,
6968 cx,
6969 );
6970 },
6971 ))
6972 .on_action(cx.listener(
6973 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
6974 adjust_open_docks_size_by_px(
6975 px_with_ui_font_fallback(act.px, cx),
6976 workspace,
6977 window,
6978 cx,
6979 );
6980 },
6981 ))
6982 .on_action(cx.listener(
6983 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
6984 adjust_open_docks_size_by_px(
6985 px_with_ui_font_fallback(act.px, cx) * -1.,
6986 workspace,
6987 window,
6988 cx,
6989 );
6990 },
6991 ))
6992 .on_action(cx.listener(Workspace::toggle_centered_layout))
6993 .on_action(cx.listener(
6994 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
6995 if let Some(active_dock) = workspace.active_dock(window, cx) {
6996 let dock = active_dock.read(cx);
6997 if let Some(active_panel) = dock.active_panel() {
6998 if active_panel.pane(cx).is_none() {
6999 let mut recent_pane: Option<Entity<Pane>> = None;
7000 let mut recent_timestamp = 0;
7001 for pane_handle in workspace.panes() {
7002 let pane = pane_handle.read(cx);
7003 for entry in pane.activation_history() {
7004 if entry.timestamp > recent_timestamp {
7005 recent_timestamp = entry.timestamp;
7006 recent_pane = Some(pane_handle.clone());
7007 }
7008 }
7009 }
7010
7011 if let Some(pane) = recent_pane {
7012 pane.update(cx, |pane, cx| {
7013 let current_index = pane.active_item_index();
7014 let items_len = pane.items_len();
7015 if items_len > 0 {
7016 let next_index = if current_index + 1 < items_len {
7017 current_index + 1
7018 } else {
7019 0
7020 };
7021 pane.activate_item(
7022 next_index, false, false, window, cx,
7023 );
7024 }
7025 });
7026 return;
7027 }
7028 }
7029 }
7030 }
7031 cx.propagate();
7032 },
7033 ))
7034 .on_action(cx.listener(
7035 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
7036 if let Some(active_dock) = workspace.active_dock(window, cx) {
7037 let dock = active_dock.read(cx);
7038 if let Some(active_panel) = dock.active_panel() {
7039 if active_panel.pane(cx).is_none() {
7040 let mut recent_pane: Option<Entity<Pane>> = None;
7041 let mut recent_timestamp = 0;
7042 for pane_handle in workspace.panes() {
7043 let pane = pane_handle.read(cx);
7044 for entry in pane.activation_history() {
7045 if entry.timestamp > recent_timestamp {
7046 recent_timestamp = entry.timestamp;
7047 recent_pane = Some(pane_handle.clone());
7048 }
7049 }
7050 }
7051
7052 if let Some(pane) = recent_pane {
7053 pane.update(cx, |pane, cx| {
7054 let current_index = pane.active_item_index();
7055 let items_len = pane.items_len();
7056 if items_len > 0 {
7057 let prev_index = if current_index > 0 {
7058 current_index - 1
7059 } else {
7060 items_len.saturating_sub(1)
7061 };
7062 pane.activate_item(
7063 prev_index, false, false, window, cx,
7064 );
7065 }
7066 });
7067 return;
7068 }
7069 }
7070 }
7071 }
7072 cx.propagate();
7073 },
7074 ))
7075 .on_action(cx.listener(
7076 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
7077 if let Some(active_dock) = workspace.active_dock(window, cx) {
7078 let dock = active_dock.read(cx);
7079 if let Some(active_panel) = dock.active_panel() {
7080 if active_panel.pane(cx).is_none() {
7081 let active_pane = workspace.active_pane().clone();
7082 active_pane.update(cx, |pane, cx| {
7083 pane.close_active_item(action, window, cx)
7084 .detach_and_log_err(cx);
7085 });
7086 return;
7087 }
7088 }
7089 }
7090 cx.propagate();
7091 },
7092 ))
7093 .on_action(
7094 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
7095 let pane = workspace.active_pane().clone();
7096 if let Some(item) = pane.read(cx).active_item() {
7097 item.toggle_read_only(window, cx);
7098 }
7099 }),
7100 )
7101 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
7102 workspace.focus_center_pane(window, cx);
7103 }))
7104 .on_action(cx.listener(Workspace::cancel))
7105 }
7106
7107 #[cfg(any(test, feature = "test-support"))]
7108 pub fn set_random_database_id(&mut self) {
7109 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
7110 }
7111
7112 #[cfg(any(test, feature = "test-support"))]
7113 pub(crate) fn test_new(
7114 project: Entity<Project>,
7115 window: &mut Window,
7116 cx: &mut Context<Self>,
7117 ) -> Self {
7118 use node_runtime::NodeRuntime;
7119 use session::Session;
7120
7121 let client = project.read(cx).client();
7122 let user_store = project.read(cx).user_store();
7123 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
7124 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
7125 window.activate_window();
7126 let app_state = Arc::new(AppState {
7127 languages: project.read(cx).languages().clone(),
7128 workspace_store,
7129 client,
7130 user_store,
7131 fs: project.read(cx).fs().clone(),
7132 build_window_options: |_, _| Default::default(),
7133 node_runtime: NodeRuntime::unavailable(),
7134 session,
7135 });
7136 let workspace = Self::new(Default::default(), project, app_state, window, cx);
7137 workspace
7138 .active_pane
7139 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
7140 workspace
7141 }
7142
7143 pub fn register_action<A: Action>(
7144 &mut self,
7145 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
7146 ) -> &mut Self {
7147 let callback = Arc::new(callback);
7148
7149 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
7150 let callback = callback.clone();
7151 div.on_action(cx.listener(move |workspace, event, window, cx| {
7152 (callback)(workspace, event, window, cx)
7153 }))
7154 }));
7155 self
7156 }
7157 pub fn register_action_renderer(
7158 &mut self,
7159 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
7160 ) -> &mut Self {
7161 self.workspace_actions.push(Box::new(callback));
7162 self
7163 }
7164
7165 fn add_workspace_actions_listeners(
7166 &self,
7167 mut div: Div,
7168 window: &mut Window,
7169 cx: &mut Context<Self>,
7170 ) -> Div {
7171 for action in self.workspace_actions.iter() {
7172 div = (action)(div, self, window, cx)
7173 }
7174 div
7175 }
7176
7177 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
7178 self.modal_layer.read(cx).has_active_modal()
7179 }
7180
7181 pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
7182 self.modal_layer
7183 .read(cx)
7184 .is_active_modal_command_palette(cx)
7185 }
7186
7187 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
7188 self.modal_layer.read(cx).active_modal()
7189 }
7190
7191 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
7192 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
7193 /// If no modal is active, the new modal will be shown.
7194 ///
7195 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
7196 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
7197 /// will not be shown.
7198 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
7199 where
7200 B: FnOnce(&mut Window, &mut Context<V>) -> V,
7201 {
7202 self.modal_layer.update(cx, |modal_layer, cx| {
7203 modal_layer.toggle_modal(window, cx, build)
7204 })
7205 }
7206
7207 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
7208 self.modal_layer
7209 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
7210 }
7211
7212 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
7213 self.toast_layer
7214 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
7215 }
7216
7217 pub fn toggle_centered_layout(
7218 &mut self,
7219 _: &ToggleCenteredLayout,
7220 _: &mut Window,
7221 cx: &mut Context<Self>,
7222 ) {
7223 self.centered_layout = !self.centered_layout;
7224 if let Some(database_id) = self.database_id() {
7225 let db = WorkspaceDb::global(cx);
7226 let centered_layout = self.centered_layout;
7227 cx.background_spawn(async move {
7228 db.set_centered_layout(database_id, centered_layout).await
7229 })
7230 .detach_and_log_err(cx);
7231 }
7232 cx.notify();
7233 }
7234
7235 fn adjust_padding(padding: Option<f32>) -> f32 {
7236 padding
7237 .unwrap_or(CenteredPaddingSettings::default().0)
7238 .clamp(
7239 CenteredPaddingSettings::MIN_PADDING,
7240 CenteredPaddingSettings::MAX_PADDING,
7241 )
7242 }
7243
7244 fn render_dock(
7245 &self,
7246 position: DockPosition,
7247 dock: &Entity<Dock>,
7248 window: &mut Window,
7249 cx: &mut App,
7250 ) -> Option<Div> {
7251 if self.zoomed_position == Some(position) {
7252 return None;
7253 }
7254
7255 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7256 let pane = panel.pane(cx)?;
7257 let follower_states = &self.follower_states;
7258 leader_border_for_pane(follower_states, &pane, window, cx)
7259 });
7260
7261 Some(
7262 div()
7263 .flex()
7264 .flex_none()
7265 .overflow_hidden()
7266 .child(dock.clone())
7267 .children(leader_border),
7268 )
7269 }
7270
7271 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7272 window
7273 .root::<MultiWorkspace>()
7274 .flatten()
7275 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7276 }
7277
7278 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7279 self.zoomed.as_ref()
7280 }
7281
7282 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7283 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7284 return;
7285 };
7286 let windows = cx.windows();
7287 let next_window =
7288 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7289 || {
7290 windows
7291 .iter()
7292 .cycle()
7293 .skip_while(|window| window.window_id() != current_window_id)
7294 .nth(1)
7295 },
7296 );
7297
7298 if let Some(window) = next_window {
7299 window
7300 .update(cx, |_, window, _| window.activate_window())
7301 .ok();
7302 }
7303 }
7304
7305 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7306 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7307 return;
7308 };
7309 let windows = cx.windows();
7310 let prev_window =
7311 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7312 || {
7313 windows
7314 .iter()
7315 .rev()
7316 .cycle()
7317 .skip_while(|window| window.window_id() != current_window_id)
7318 .nth(1)
7319 },
7320 );
7321
7322 if let Some(window) = prev_window {
7323 window
7324 .update(cx, |_, window, _| window.activate_window())
7325 .ok();
7326 }
7327 }
7328
7329 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7330 if cx.stop_active_drag(window) {
7331 } else if let Some((notification_id, _)) = self.notifications.pop() {
7332 dismiss_app_notification(¬ification_id, cx);
7333 } else {
7334 cx.propagate();
7335 }
7336 }
7337
7338 fn adjust_dock_size_by_px(
7339 &mut self,
7340 panel_size: Pixels,
7341 dock_pos: DockPosition,
7342 px: Pixels,
7343 window: &mut Window,
7344 cx: &mut Context<Self>,
7345 ) {
7346 match dock_pos {
7347 DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
7348 DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
7349 DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
7350 }
7351 }
7352
7353 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7354 let workspace_width = self.bounds.size.width;
7355 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7356
7357 self.right_dock.read_with(cx, |right_dock, cx| {
7358 let right_dock_size = right_dock
7359 .stored_active_panel_size(window, cx)
7360 .unwrap_or(Pixels::ZERO);
7361 if right_dock_size + size > workspace_width {
7362 size = workspace_width - right_dock_size
7363 }
7364 });
7365
7366 let ratio = self.flexible_dock_ratio_for_size(DockPosition::Left, size, window, cx);
7367 self.left_dock.update(cx, |left_dock, cx| {
7368 if WorkspaceSettings::get_global(cx)
7369 .resize_all_panels_in_dock
7370 .contains(&DockPosition::Left)
7371 {
7372 left_dock.resize_all_panels(Some(size), ratio, window, cx);
7373 } else {
7374 left_dock.resize_active_panel(Some(size), ratio, window, cx);
7375 }
7376 });
7377 }
7378
7379 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7380 let workspace_width = self.bounds.size.width;
7381 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7382 self.left_dock.read_with(cx, |left_dock, cx| {
7383 let left_dock_size = left_dock
7384 .stored_active_panel_size(window, cx)
7385 .unwrap_or(Pixels::ZERO);
7386 if left_dock_size + size > workspace_width {
7387 size = workspace_width - left_dock_size
7388 }
7389 });
7390 let ratio = self.flexible_dock_ratio_for_size(DockPosition::Right, size, window, cx);
7391 self.right_dock.update(cx, |right_dock, cx| {
7392 if WorkspaceSettings::get_global(cx)
7393 .resize_all_panels_in_dock
7394 .contains(&DockPosition::Right)
7395 {
7396 right_dock.resize_all_panels(Some(size), ratio, window, cx);
7397 } else {
7398 right_dock.resize_active_panel(Some(size), ratio, window, cx);
7399 }
7400 });
7401 }
7402
7403 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7404 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7405 self.bottom_dock.update(cx, |bottom_dock, cx| {
7406 if WorkspaceSettings::get_global(cx)
7407 .resize_all_panels_in_dock
7408 .contains(&DockPosition::Bottom)
7409 {
7410 bottom_dock.resize_all_panels(Some(size), None, window, cx);
7411 } else {
7412 bottom_dock.resize_active_panel(Some(size), None, window, cx);
7413 }
7414 });
7415 }
7416
7417 fn toggle_edit_predictions_all_files(
7418 &mut self,
7419 _: &ToggleEditPrediction,
7420 _window: &mut Window,
7421 cx: &mut Context<Self>,
7422 ) {
7423 let fs = self.project().read(cx).fs().clone();
7424 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7425 update_settings_file(fs, cx, move |file, _| {
7426 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7427 });
7428 }
7429
7430 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7431 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7432 let next_mode = match current_mode {
7433 Some(theme::ThemeAppearanceMode::Light) => theme::ThemeAppearanceMode::Dark,
7434 Some(theme::ThemeAppearanceMode::Dark) => theme::ThemeAppearanceMode::Light,
7435 Some(theme::ThemeAppearanceMode::System) | None => match cx.theme().appearance() {
7436 theme::Appearance::Light => theme::ThemeAppearanceMode::Dark,
7437 theme::Appearance::Dark => theme::ThemeAppearanceMode::Light,
7438 },
7439 };
7440
7441 let fs = self.project().read(cx).fs().clone();
7442 settings::update_settings_file(fs, cx, move |settings, _cx| {
7443 theme::set_mode(settings, next_mode);
7444 });
7445 }
7446
7447 pub fn show_worktree_trust_security_modal(
7448 &mut self,
7449 toggle: bool,
7450 window: &mut Window,
7451 cx: &mut Context<Self>,
7452 ) {
7453 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7454 if toggle {
7455 security_modal.update(cx, |security_modal, cx| {
7456 security_modal.dismiss(cx);
7457 })
7458 } else {
7459 security_modal.update(cx, |security_modal, cx| {
7460 security_modal.refresh_restricted_paths(cx);
7461 });
7462 }
7463 } else {
7464 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7465 .map(|trusted_worktrees| {
7466 trusted_worktrees
7467 .read(cx)
7468 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7469 })
7470 .unwrap_or(false);
7471 if has_restricted_worktrees {
7472 let project = self.project().read(cx);
7473 let remote_host = project
7474 .remote_connection_options(cx)
7475 .map(RemoteHostLocation::from);
7476 let worktree_store = project.worktree_store().downgrade();
7477 self.toggle_modal(window, cx, |_, cx| {
7478 SecurityModal::new(worktree_store, remote_host, cx)
7479 });
7480 }
7481 }
7482 }
7483}
7484
7485pub trait AnyActiveCall {
7486 fn entity(&self) -> AnyEntity;
7487 fn is_in_room(&self, _: &App) -> bool;
7488 fn room_id(&self, _: &App) -> Option<u64>;
7489 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7490 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7491 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7492 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7493 fn is_sharing_project(&self, _: &App) -> bool;
7494 fn has_remote_participants(&self, _: &App) -> bool;
7495 fn local_participant_is_guest(&self, _: &App) -> bool;
7496 fn client(&self, _: &App) -> Arc<Client>;
7497 fn share_on_join(&self, _: &App) -> bool;
7498 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7499 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7500 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7501 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7502 fn join_project(
7503 &self,
7504 _: u64,
7505 _: Arc<LanguageRegistry>,
7506 _: Arc<dyn Fs>,
7507 _: &mut App,
7508 ) -> Task<Result<Entity<Project>>>;
7509 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7510 fn subscribe(
7511 &self,
7512 _: &mut Window,
7513 _: &mut Context<Workspace>,
7514 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7515 ) -> Subscription;
7516 fn create_shared_screen(
7517 &self,
7518 _: PeerId,
7519 _: &Entity<Pane>,
7520 _: &mut Window,
7521 _: &mut App,
7522 ) -> Option<Entity<SharedScreen>>;
7523}
7524
7525#[derive(Clone)]
7526pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7527impl Global for GlobalAnyActiveCall {}
7528
7529impl GlobalAnyActiveCall {
7530 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7531 cx.try_global()
7532 }
7533
7534 pub(crate) fn global(cx: &App) -> &Self {
7535 cx.global()
7536 }
7537}
7538
7539pub fn merge_conflict_notification_id() -> NotificationId {
7540 struct MergeConflictNotification;
7541 NotificationId::unique::<MergeConflictNotification>()
7542}
7543
7544/// Workspace-local view of a remote participant's location.
7545#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7546pub enum ParticipantLocation {
7547 SharedProject { project_id: u64 },
7548 UnsharedProject,
7549 External,
7550}
7551
7552impl ParticipantLocation {
7553 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7554 match location
7555 .and_then(|l| l.variant)
7556 .context("participant location was not provided")?
7557 {
7558 proto::participant_location::Variant::SharedProject(project) => {
7559 Ok(Self::SharedProject {
7560 project_id: project.id,
7561 })
7562 }
7563 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7564 proto::participant_location::Variant::External(_) => Ok(Self::External),
7565 }
7566 }
7567}
7568/// Workspace-local view of a remote collaborator's state.
7569/// This is the subset of `call::RemoteParticipant` that workspace needs.
7570#[derive(Clone)]
7571pub struct RemoteCollaborator {
7572 pub user: Arc<User>,
7573 pub peer_id: PeerId,
7574 pub location: ParticipantLocation,
7575 pub participant_index: ParticipantIndex,
7576}
7577
7578pub enum ActiveCallEvent {
7579 ParticipantLocationChanged { participant_id: PeerId },
7580 RemoteVideoTracksChanged { participant_id: PeerId },
7581}
7582
7583fn leader_border_for_pane(
7584 follower_states: &HashMap<CollaboratorId, FollowerState>,
7585 pane: &Entity<Pane>,
7586 _: &Window,
7587 cx: &App,
7588) -> Option<Div> {
7589 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7590 if state.pane() == pane {
7591 Some((*leader_id, state))
7592 } else {
7593 None
7594 }
7595 })?;
7596
7597 let mut leader_color = match leader_id {
7598 CollaboratorId::PeerId(leader_peer_id) => {
7599 let leader = GlobalAnyActiveCall::try_global(cx)?
7600 .0
7601 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7602
7603 cx.theme()
7604 .players()
7605 .color_for_participant(leader.participant_index.0)
7606 .cursor
7607 }
7608 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7609 };
7610 leader_color.fade_out(0.3);
7611 Some(
7612 div()
7613 .absolute()
7614 .size_full()
7615 .left_0()
7616 .top_0()
7617 .border_2()
7618 .border_color(leader_color),
7619 )
7620}
7621
7622fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7623 ZED_WINDOW_POSITION
7624 .zip(*ZED_WINDOW_SIZE)
7625 .map(|(position, size)| Bounds {
7626 origin: position,
7627 size,
7628 })
7629}
7630
7631fn open_items(
7632 serialized_workspace: Option<SerializedWorkspace>,
7633 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7634 window: &mut Window,
7635 cx: &mut Context<Workspace>,
7636) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7637 let restored_items = serialized_workspace.map(|serialized_workspace| {
7638 Workspace::load_workspace(
7639 serialized_workspace,
7640 project_paths_to_open
7641 .iter()
7642 .map(|(_, project_path)| project_path)
7643 .cloned()
7644 .collect(),
7645 window,
7646 cx,
7647 )
7648 });
7649
7650 cx.spawn_in(window, async move |workspace, cx| {
7651 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7652
7653 if let Some(restored_items) = restored_items {
7654 let restored_items = restored_items.await?;
7655
7656 let restored_project_paths = restored_items
7657 .iter()
7658 .filter_map(|item| {
7659 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7660 .ok()
7661 .flatten()
7662 })
7663 .collect::<HashSet<_>>();
7664
7665 for restored_item in restored_items {
7666 opened_items.push(restored_item.map(Ok));
7667 }
7668
7669 project_paths_to_open
7670 .iter_mut()
7671 .for_each(|(_, project_path)| {
7672 if let Some(project_path_to_open) = project_path
7673 && restored_project_paths.contains(project_path_to_open)
7674 {
7675 *project_path = None;
7676 }
7677 });
7678 } else {
7679 for _ in 0..project_paths_to_open.len() {
7680 opened_items.push(None);
7681 }
7682 }
7683 assert!(opened_items.len() == project_paths_to_open.len());
7684
7685 let tasks =
7686 project_paths_to_open
7687 .into_iter()
7688 .enumerate()
7689 .map(|(ix, (abs_path, project_path))| {
7690 let workspace = workspace.clone();
7691 cx.spawn(async move |cx| {
7692 let file_project_path = project_path?;
7693 let abs_path_task = workspace.update(cx, |workspace, cx| {
7694 workspace.project().update(cx, |project, cx| {
7695 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7696 })
7697 });
7698
7699 // We only want to open file paths here. If one of the items
7700 // here is a directory, it was already opened further above
7701 // with a `find_or_create_worktree`.
7702 if let Ok(task) = abs_path_task
7703 && task.await.is_none_or(|p| p.is_file())
7704 {
7705 return Some((
7706 ix,
7707 workspace
7708 .update_in(cx, |workspace, window, cx| {
7709 workspace.open_path(
7710 file_project_path,
7711 None,
7712 true,
7713 window,
7714 cx,
7715 )
7716 })
7717 .log_err()?
7718 .await,
7719 ));
7720 }
7721 None
7722 })
7723 });
7724
7725 let tasks = tasks.collect::<Vec<_>>();
7726
7727 let tasks = futures::future::join_all(tasks);
7728 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7729 opened_items[ix] = Some(path_open_result);
7730 }
7731
7732 Ok(opened_items)
7733 })
7734}
7735
7736#[derive(Clone)]
7737enum ActivateInDirectionTarget {
7738 Pane(Entity<Pane>),
7739 Dock(Entity<Dock>),
7740 Sidebar(FocusHandle),
7741}
7742
7743fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7744 window
7745 .update(cx, |multi_workspace, _, cx| {
7746 let workspace = multi_workspace.workspace().clone();
7747 workspace.update(cx, |workspace, cx| {
7748 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7749 struct DatabaseFailedNotification;
7750
7751 workspace.show_notification(
7752 NotificationId::unique::<DatabaseFailedNotification>(),
7753 cx,
7754 |cx| {
7755 cx.new(|cx| {
7756 MessageNotification::new("Failed to load the database file.", cx)
7757 .primary_message("File an Issue")
7758 .primary_icon(IconName::Plus)
7759 .primary_on_click(|window, cx| {
7760 window.dispatch_action(Box::new(FileBugReport), cx)
7761 })
7762 })
7763 },
7764 );
7765 }
7766 });
7767 })
7768 .log_err();
7769}
7770
7771fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7772 if val == 0 {
7773 ThemeSettings::get_global(cx).ui_font_size(cx)
7774 } else {
7775 px(val as f32)
7776 }
7777}
7778
7779fn adjust_active_dock_size_by_px(
7780 px: Pixels,
7781 workspace: &mut Workspace,
7782 window: &mut Window,
7783 cx: &mut Context<Workspace>,
7784) {
7785 let Some(active_dock) = workspace
7786 .all_docks()
7787 .into_iter()
7788 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7789 else {
7790 return;
7791 };
7792 let dock = active_dock.read(cx);
7793 let Some(panel_size) = dock
7794 .active_panel()
7795 .map(|panel| workspace.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx))
7796 else {
7797 return;
7798 };
7799 let dock_pos = dock.position();
7800 workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
7801}
7802
7803fn adjust_open_docks_size_by_px(
7804 px: Pixels,
7805 workspace: &mut Workspace,
7806 window: &mut Window,
7807 cx: &mut Context<Workspace>,
7808) {
7809 let docks = workspace
7810 .all_docks()
7811 .into_iter()
7812 .filter_map(|dock_entity| {
7813 let dock = dock_entity.read(cx);
7814 if dock.is_open() {
7815 let panel_size = dock.active_panel().map(|panel| {
7816 workspace.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx)
7817 })?;
7818 let dock_pos = dock.position();
7819 Some((panel_size, dock_pos, px))
7820 } else {
7821 None
7822 }
7823 })
7824 .collect::<Vec<_>>();
7825
7826 docks
7827 .into_iter()
7828 .for_each(|(panel_size, dock_pos, offset)| {
7829 workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
7830 });
7831}
7832
7833impl Focusable for Workspace {
7834 fn focus_handle(&self, cx: &App) -> FocusHandle {
7835 self.active_pane.focus_handle(cx)
7836 }
7837}
7838
7839#[derive(Clone)]
7840struct DraggedDock(DockPosition);
7841
7842impl Render for DraggedDock {
7843 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7844 gpui::Empty
7845 }
7846}
7847
7848impl Render for Workspace {
7849 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7850 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7851 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7852 log::info!("Rendered first frame");
7853 }
7854
7855 let centered_layout = self.centered_layout
7856 && self.center.panes().len() == 1
7857 && self.active_item(cx).is_some();
7858 let render_padding = |size| {
7859 (size > 0.0).then(|| {
7860 div()
7861 .h_full()
7862 .w(relative(size))
7863 .bg(cx.theme().colors().editor_background)
7864 .border_color(cx.theme().colors().pane_group_border)
7865 })
7866 };
7867 let paddings = if centered_layout {
7868 let settings = WorkspaceSettings::get_global(cx).centered_layout;
7869 (
7870 render_padding(Self::adjust_padding(
7871 settings.left_padding.map(|padding| padding.0),
7872 )),
7873 render_padding(Self::adjust_padding(
7874 settings.right_padding.map(|padding| padding.0),
7875 )),
7876 )
7877 } else {
7878 (None, None)
7879 };
7880 let ui_font = theme::setup_ui_font(window, cx);
7881
7882 let theme = cx.theme().clone();
7883 let colors = theme.colors();
7884 let notification_entities = self
7885 .notifications
7886 .iter()
7887 .map(|(_, notification)| notification.entity_id())
7888 .collect::<Vec<_>>();
7889 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
7890
7891 div()
7892 .relative()
7893 .size_full()
7894 .flex()
7895 .flex_col()
7896 .font(ui_font)
7897 .gap_0()
7898 .justify_start()
7899 .items_start()
7900 .text_color(colors.text)
7901 .overflow_hidden()
7902 .children(self.titlebar_item.clone())
7903 .on_modifiers_changed(move |_, _, cx| {
7904 for &id in ¬ification_entities {
7905 cx.notify(id);
7906 }
7907 })
7908 .child(
7909 div()
7910 .size_full()
7911 .relative()
7912 .flex_1()
7913 .flex()
7914 .flex_col()
7915 .child(
7916 div()
7917 .id("workspace")
7918 .bg(colors.background)
7919 .relative()
7920 .flex_1()
7921 .w_full()
7922 .flex()
7923 .flex_col()
7924 .overflow_hidden()
7925 .border_t_1()
7926 .border_b_1()
7927 .border_color(colors.border)
7928 .child({
7929 let this = cx.entity();
7930 canvas(
7931 move |bounds, window, cx| {
7932 this.update(cx, |this, cx| {
7933 let bounds_changed = this.bounds != bounds;
7934 this.bounds = bounds;
7935
7936 if bounds_changed {
7937 this.left_dock.update(cx, |dock, cx| {
7938 dock.clamp_panel_size(
7939 bounds.size.width,
7940 window,
7941 cx,
7942 )
7943 });
7944
7945 this.right_dock.update(cx, |dock, cx| {
7946 dock.clamp_panel_size(
7947 bounds.size.width,
7948 window,
7949 cx,
7950 )
7951 });
7952
7953 this.bottom_dock.update(cx, |dock, cx| {
7954 dock.clamp_panel_size(
7955 bounds.size.height,
7956 window,
7957 cx,
7958 )
7959 });
7960 }
7961 })
7962 },
7963 |_, _, _, _| {},
7964 )
7965 .absolute()
7966 .size_full()
7967 })
7968 .when(self.zoomed.is_none(), |this| {
7969 this.on_drag_move(cx.listener(
7970 move |workspace,
7971 e: &DragMoveEvent<DraggedDock>,
7972 window,
7973 cx| {
7974 if workspace.previous_dock_drag_coordinates
7975 != Some(e.event.position)
7976 {
7977 workspace.previous_dock_drag_coordinates =
7978 Some(e.event.position);
7979
7980 match e.drag(cx).0 {
7981 DockPosition::Left => {
7982 workspace.resize_left_dock(
7983 e.event.position.x
7984 - workspace.bounds.left(),
7985 window,
7986 cx,
7987 );
7988 }
7989 DockPosition::Right => {
7990 workspace.resize_right_dock(
7991 workspace.bounds.right()
7992 - e.event.position.x,
7993 window,
7994 cx,
7995 );
7996 }
7997 DockPosition::Bottom => {
7998 workspace.resize_bottom_dock(
7999 workspace.bounds.bottom()
8000 - e.event.position.y,
8001 window,
8002 cx,
8003 );
8004 }
8005 };
8006 workspace.serialize_workspace(window, cx);
8007 }
8008 },
8009 ))
8010
8011 })
8012 .child({
8013 match bottom_dock_layout {
8014 BottomDockLayout::Full => div()
8015 .flex()
8016 .flex_col()
8017 .h_full()
8018 .child(
8019 div()
8020 .flex()
8021 .flex_row()
8022 .flex_1()
8023 .overflow_hidden()
8024 .children(self.render_dock(
8025 DockPosition::Left,
8026 &self.left_dock,
8027 window,
8028 cx,
8029 ))
8030
8031 .child(
8032 div()
8033 .flex()
8034 .flex_col()
8035 .flex_1()
8036 .overflow_hidden()
8037 .child(
8038 h_flex()
8039 .flex_1()
8040 .when_some(
8041 paddings.0,
8042 |this, p| {
8043 this.child(
8044 p.border_r_1(),
8045 )
8046 },
8047 )
8048 .child(self.center.render(
8049 self.zoomed.as_ref(),
8050 &PaneRenderContext {
8051 follower_states:
8052 &self.follower_states,
8053 active_call: self.active_call(),
8054 active_pane: &self.active_pane,
8055 app_state: &self.app_state,
8056 project: &self.project,
8057 workspace: &self.weak_self,
8058 },
8059 window,
8060 cx,
8061 ))
8062 .when_some(
8063 paddings.1,
8064 |this, p| {
8065 this.child(
8066 p.border_l_1(),
8067 )
8068 },
8069 ),
8070 ),
8071 )
8072
8073 .children(self.render_dock(
8074 DockPosition::Right,
8075 &self.right_dock,
8076 window,
8077 cx,
8078 )),
8079 )
8080 .child(div().w_full().children(self.render_dock(
8081 DockPosition::Bottom,
8082 &self.bottom_dock,
8083 window,
8084 cx
8085 ))),
8086
8087 BottomDockLayout::LeftAligned => div()
8088 .flex()
8089 .flex_row()
8090 .h_full()
8091 .child(
8092 div()
8093 .flex()
8094 .flex_col()
8095 .flex_1()
8096 .h_full()
8097 .child(
8098 div()
8099 .flex()
8100 .flex_row()
8101 .flex_1()
8102 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
8103
8104 .child(
8105 div()
8106 .flex()
8107 .flex_col()
8108 .flex_1()
8109 .overflow_hidden()
8110 .child(
8111 h_flex()
8112 .flex_1()
8113 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8114 .child(self.center.render(
8115 self.zoomed.as_ref(),
8116 &PaneRenderContext {
8117 follower_states:
8118 &self.follower_states,
8119 active_call: self.active_call(),
8120 active_pane: &self.active_pane,
8121 app_state: &self.app_state,
8122 project: &self.project,
8123 workspace: &self.weak_self,
8124 },
8125 window,
8126 cx,
8127 ))
8128 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8129 )
8130 )
8131
8132 )
8133 .child(
8134 div()
8135 .w_full()
8136 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8137 ),
8138 )
8139 .children(self.render_dock(
8140 DockPosition::Right,
8141 &self.right_dock,
8142 window,
8143 cx,
8144 )),
8145 BottomDockLayout::RightAligned => div()
8146 .flex()
8147 .flex_row()
8148 .h_full()
8149 .children(self.render_dock(
8150 DockPosition::Left,
8151 &self.left_dock,
8152 window,
8153 cx,
8154 ))
8155
8156 .child(
8157 div()
8158 .flex()
8159 .flex_col()
8160 .flex_1()
8161 .h_full()
8162 .child(
8163 div()
8164 .flex()
8165 .flex_row()
8166 .flex_1()
8167 .child(
8168 div()
8169 .flex()
8170 .flex_col()
8171 .flex_1()
8172 .overflow_hidden()
8173 .child(
8174 h_flex()
8175 .flex_1()
8176 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8177 .child(self.center.render(
8178 self.zoomed.as_ref(),
8179 &PaneRenderContext {
8180 follower_states:
8181 &self.follower_states,
8182 active_call: self.active_call(),
8183 active_pane: &self.active_pane,
8184 app_state: &self.app_state,
8185 project: &self.project,
8186 workspace: &self.weak_self,
8187 },
8188 window,
8189 cx,
8190 ))
8191 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8192 )
8193 )
8194
8195 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
8196 )
8197 .child(
8198 div()
8199 .w_full()
8200 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8201 ),
8202 ),
8203 BottomDockLayout::Contained => div()
8204 .flex()
8205 .flex_row()
8206 .h_full()
8207 .children(self.render_dock(
8208 DockPosition::Left,
8209 &self.left_dock,
8210 window,
8211 cx,
8212 ))
8213
8214 .child(
8215 div()
8216 .flex()
8217 .flex_col()
8218 .flex_1()
8219 .overflow_hidden()
8220 .child(
8221 h_flex()
8222 .flex_1()
8223 .when_some(paddings.0, |this, p| {
8224 this.child(p.border_r_1())
8225 })
8226 .child(self.center.render(
8227 self.zoomed.as_ref(),
8228 &PaneRenderContext {
8229 follower_states:
8230 &self.follower_states,
8231 active_call: self.active_call(),
8232 active_pane: &self.active_pane,
8233 app_state: &self.app_state,
8234 project: &self.project,
8235 workspace: &self.weak_self,
8236 },
8237 window,
8238 cx,
8239 ))
8240 .when_some(paddings.1, |this, p| {
8241 this.child(p.border_l_1())
8242 }),
8243 )
8244 .children(self.render_dock(
8245 DockPosition::Bottom,
8246 &self.bottom_dock,
8247 window,
8248 cx,
8249 )),
8250 )
8251
8252 .children(self.render_dock(
8253 DockPosition::Right,
8254 &self.right_dock,
8255 window,
8256 cx,
8257 )),
8258 }
8259 })
8260 .children(self.zoomed.as_ref().and_then(|view| {
8261 let zoomed_view = view.upgrade()?;
8262 let div = div()
8263 .occlude()
8264 .absolute()
8265 .overflow_hidden()
8266 .border_color(colors.border)
8267 .bg(colors.background)
8268 .child(zoomed_view)
8269 .inset_0()
8270 .shadow_lg();
8271
8272 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8273 return Some(div);
8274 }
8275
8276 Some(match self.zoomed_position {
8277 Some(DockPosition::Left) => div.right_2().border_r_1(),
8278 Some(DockPosition::Right) => div.left_2().border_l_1(),
8279 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8280 None => {
8281 div.top_2().bottom_2().left_2().right_2().border_1()
8282 }
8283 })
8284 }))
8285 .children(self.render_notifications(window, cx)),
8286 )
8287 .when(self.status_bar_visible(cx), |parent| {
8288 parent.child(self.status_bar.clone())
8289 })
8290 .child(self.toast_layer.clone()),
8291 )
8292 }
8293}
8294
8295impl WorkspaceStore {
8296 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8297 Self {
8298 workspaces: Default::default(),
8299 _subscriptions: vec![
8300 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8301 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8302 ],
8303 client,
8304 }
8305 }
8306
8307 pub fn update_followers(
8308 &self,
8309 project_id: Option<u64>,
8310 update: proto::update_followers::Variant,
8311 cx: &App,
8312 ) -> Option<()> {
8313 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8314 let room_id = active_call.0.room_id(cx)?;
8315 self.client
8316 .send(proto::UpdateFollowers {
8317 room_id,
8318 project_id,
8319 variant: Some(update),
8320 })
8321 .log_err()
8322 }
8323
8324 pub async fn handle_follow(
8325 this: Entity<Self>,
8326 envelope: TypedEnvelope<proto::Follow>,
8327 mut cx: AsyncApp,
8328 ) -> Result<proto::FollowResponse> {
8329 this.update(&mut cx, |this, cx| {
8330 let follower = Follower {
8331 project_id: envelope.payload.project_id,
8332 peer_id: envelope.original_sender_id()?,
8333 };
8334
8335 let mut response = proto::FollowResponse::default();
8336
8337 this.workspaces.retain(|(window_handle, weak_workspace)| {
8338 let Some(workspace) = weak_workspace.upgrade() else {
8339 return false;
8340 };
8341 window_handle
8342 .update(cx, |_, window, cx| {
8343 workspace.update(cx, |workspace, cx| {
8344 let handler_response =
8345 workspace.handle_follow(follower.project_id, window, cx);
8346 if let Some(active_view) = handler_response.active_view
8347 && workspace.project.read(cx).remote_id() == follower.project_id
8348 {
8349 response.active_view = Some(active_view)
8350 }
8351 });
8352 })
8353 .is_ok()
8354 });
8355
8356 Ok(response)
8357 })
8358 }
8359
8360 async fn handle_update_followers(
8361 this: Entity<Self>,
8362 envelope: TypedEnvelope<proto::UpdateFollowers>,
8363 mut cx: AsyncApp,
8364 ) -> Result<()> {
8365 let leader_id = envelope.original_sender_id()?;
8366 let update = envelope.payload;
8367
8368 this.update(&mut cx, |this, cx| {
8369 this.workspaces.retain(|(window_handle, weak_workspace)| {
8370 let Some(workspace) = weak_workspace.upgrade() else {
8371 return false;
8372 };
8373 window_handle
8374 .update(cx, |_, window, cx| {
8375 workspace.update(cx, |workspace, cx| {
8376 let project_id = workspace.project.read(cx).remote_id();
8377 if update.project_id != project_id && update.project_id.is_some() {
8378 return;
8379 }
8380 workspace.handle_update_followers(
8381 leader_id,
8382 update.clone(),
8383 window,
8384 cx,
8385 );
8386 });
8387 })
8388 .is_ok()
8389 });
8390 Ok(())
8391 })
8392 }
8393
8394 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8395 self.workspaces.iter().map(|(_, weak)| weak)
8396 }
8397
8398 pub fn workspaces_with_windows(
8399 &self,
8400 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8401 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8402 }
8403}
8404
8405impl ViewId {
8406 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8407 Ok(Self {
8408 creator: message
8409 .creator
8410 .map(CollaboratorId::PeerId)
8411 .context("creator is missing")?,
8412 id: message.id,
8413 })
8414 }
8415
8416 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8417 if let CollaboratorId::PeerId(peer_id) = self.creator {
8418 Some(proto::ViewId {
8419 creator: Some(peer_id),
8420 id: self.id,
8421 })
8422 } else {
8423 None
8424 }
8425 }
8426}
8427
8428impl FollowerState {
8429 fn pane(&self) -> &Entity<Pane> {
8430 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8431 }
8432}
8433
8434pub trait WorkspaceHandle {
8435 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8436}
8437
8438impl WorkspaceHandle for Entity<Workspace> {
8439 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8440 self.read(cx)
8441 .worktrees(cx)
8442 .flat_map(|worktree| {
8443 let worktree_id = worktree.read(cx).id();
8444 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8445 worktree_id,
8446 path: f.path.clone(),
8447 })
8448 })
8449 .collect::<Vec<_>>()
8450 }
8451}
8452
8453pub async fn last_opened_workspace_location(
8454 db: &WorkspaceDb,
8455 fs: &dyn fs::Fs,
8456) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8457 db.last_workspace(fs)
8458 .await
8459 .log_err()
8460 .flatten()
8461 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8462}
8463
8464pub async fn last_session_workspace_locations(
8465 db: &WorkspaceDb,
8466 last_session_id: &str,
8467 last_session_window_stack: Option<Vec<WindowId>>,
8468 fs: &dyn fs::Fs,
8469) -> Option<Vec<SessionWorkspace>> {
8470 db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8471 .await
8472 .log_err()
8473}
8474
8475pub struct MultiWorkspaceRestoreResult {
8476 pub window_handle: WindowHandle<MultiWorkspace>,
8477 pub errors: Vec<anyhow::Error>,
8478}
8479
8480pub async fn restore_multiworkspace(
8481 multi_workspace: SerializedMultiWorkspace,
8482 app_state: Arc<AppState>,
8483 cx: &mut AsyncApp,
8484) -> anyhow::Result<MultiWorkspaceRestoreResult> {
8485 let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
8486 let mut group_iter = workspaces.into_iter();
8487 let first = group_iter
8488 .next()
8489 .context("window group must not be empty")?;
8490
8491 let window_handle = if first.paths.is_empty() {
8492 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
8493 .await?
8494 } else {
8495 let OpenResult { window, .. } = cx
8496 .update(|cx| {
8497 Workspace::new_local(
8498 first.paths.paths().to_vec(),
8499 app_state.clone(),
8500 None,
8501 None,
8502 None,
8503 true,
8504 cx,
8505 )
8506 })
8507 .await?;
8508 window
8509 };
8510
8511 let mut errors = Vec::new();
8512
8513 for session_workspace in group_iter {
8514 let error = if session_workspace.paths.is_empty() {
8515 cx.update(|cx| {
8516 open_workspace_by_id(
8517 session_workspace.workspace_id,
8518 app_state.clone(),
8519 Some(window_handle),
8520 cx,
8521 )
8522 })
8523 .await
8524 .err()
8525 } else {
8526 cx.update(|cx| {
8527 Workspace::new_local(
8528 session_workspace.paths.paths().to_vec(),
8529 app_state.clone(),
8530 Some(window_handle),
8531 None,
8532 None,
8533 false,
8534 cx,
8535 )
8536 })
8537 .await
8538 .err()
8539 };
8540
8541 if let Some(error) = error {
8542 errors.push(error);
8543 }
8544 }
8545
8546 if let Some(target_id) = state.active_workspace_id {
8547 window_handle
8548 .update(cx, |multi_workspace, window, cx| {
8549 let target_index = multi_workspace
8550 .workspaces()
8551 .iter()
8552 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8553 if let Some(index) = target_index {
8554 multi_workspace.activate_index(index, window, cx);
8555 } else if !multi_workspace.workspaces().is_empty() {
8556 multi_workspace.activate_index(0, window, cx);
8557 }
8558 })
8559 .ok();
8560 } else {
8561 window_handle
8562 .update(cx, |multi_workspace, window, cx| {
8563 if !multi_workspace.workspaces().is_empty() {
8564 multi_workspace.activate_index(0, window, cx);
8565 }
8566 })
8567 .ok();
8568 }
8569
8570 if state.sidebar_open {
8571 window_handle
8572 .update(cx, |multi_workspace, _, cx| {
8573 multi_workspace.open_sidebar(cx);
8574 })
8575 .ok();
8576 }
8577
8578 window_handle
8579 .update(cx, |_, window, _cx| {
8580 window.activate_window();
8581 })
8582 .ok();
8583
8584 Ok(MultiWorkspaceRestoreResult {
8585 window_handle,
8586 errors,
8587 })
8588}
8589
8590actions!(
8591 collab,
8592 [
8593 /// Opens the channel notes for the current call.
8594 ///
8595 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8596 /// channel in the collab panel.
8597 ///
8598 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8599 /// can be copied via "Copy link to section" in the context menu of the channel notes
8600 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8601 OpenChannelNotes,
8602 /// Mutes your microphone.
8603 Mute,
8604 /// Deafens yourself (mute both microphone and speakers).
8605 Deafen,
8606 /// Leaves the current call.
8607 LeaveCall,
8608 /// Shares the current project with collaborators.
8609 ShareProject,
8610 /// Shares your screen with collaborators.
8611 ScreenShare,
8612 /// Copies the current room name and session id for debugging purposes.
8613 CopyRoomId,
8614 ]
8615);
8616
8617/// Opens the channel notes for a specific channel by its ID.
8618#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8619#[action(namespace = collab)]
8620#[serde(deny_unknown_fields)]
8621pub struct OpenChannelNotesById {
8622 pub channel_id: u64,
8623}
8624
8625actions!(
8626 zed,
8627 [
8628 /// Opens the Zed log file.
8629 OpenLog,
8630 /// Reveals the Zed log file in the system file manager.
8631 RevealLogInFileManager
8632 ]
8633);
8634
8635async fn join_channel_internal(
8636 channel_id: ChannelId,
8637 app_state: &Arc<AppState>,
8638 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8639 requesting_workspace: Option<WeakEntity<Workspace>>,
8640 active_call: &dyn AnyActiveCall,
8641 cx: &mut AsyncApp,
8642) -> Result<bool> {
8643 let (should_prompt, already_in_channel) = cx.update(|cx| {
8644 if !active_call.is_in_room(cx) {
8645 return (false, false);
8646 }
8647
8648 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8649 let should_prompt = active_call.is_sharing_project(cx)
8650 && active_call.has_remote_participants(cx)
8651 && !already_in_channel;
8652 (should_prompt, already_in_channel)
8653 });
8654
8655 if already_in_channel {
8656 let task = cx.update(|cx| {
8657 if let Some((project, host)) = active_call.most_active_project(cx) {
8658 Some(join_in_room_project(project, host, app_state.clone(), cx))
8659 } else {
8660 None
8661 }
8662 });
8663 if let Some(task) = task {
8664 task.await?;
8665 }
8666 return anyhow::Ok(true);
8667 }
8668
8669 if should_prompt {
8670 if let Some(multi_workspace) = requesting_window {
8671 let answer = multi_workspace
8672 .update(cx, |_, window, cx| {
8673 window.prompt(
8674 PromptLevel::Warning,
8675 "Do you want to switch channels?",
8676 Some("Leaving this call will unshare your current project."),
8677 &["Yes, Join Channel", "Cancel"],
8678 cx,
8679 )
8680 })?
8681 .await;
8682
8683 if answer == Ok(1) {
8684 return Ok(false);
8685 }
8686 } else {
8687 return Ok(false);
8688 }
8689 }
8690
8691 let client = cx.update(|cx| active_call.client(cx));
8692
8693 let mut client_status = client.status();
8694
8695 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8696 'outer: loop {
8697 let Some(status) = client_status.recv().await else {
8698 anyhow::bail!("error connecting");
8699 };
8700
8701 match status {
8702 Status::Connecting
8703 | Status::Authenticating
8704 | Status::Authenticated
8705 | Status::Reconnecting
8706 | Status::Reauthenticating
8707 | Status::Reauthenticated => continue,
8708 Status::Connected { .. } => break 'outer,
8709 Status::SignedOut | Status::AuthenticationError => {
8710 return Err(ErrorCode::SignedOut.into());
8711 }
8712 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8713 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8714 return Err(ErrorCode::Disconnected.into());
8715 }
8716 }
8717 }
8718
8719 let joined = cx
8720 .update(|cx| active_call.join_channel(channel_id, cx))
8721 .await?;
8722
8723 if !joined {
8724 return anyhow::Ok(true);
8725 }
8726
8727 cx.update(|cx| active_call.room_update_completed(cx)).await;
8728
8729 let task = cx.update(|cx| {
8730 if let Some((project, host)) = active_call.most_active_project(cx) {
8731 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8732 }
8733
8734 // If you are the first to join a channel, see if you should share your project.
8735 if !active_call.has_remote_participants(cx)
8736 && !active_call.local_participant_is_guest(cx)
8737 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8738 {
8739 let project = workspace.update(cx, |workspace, cx| {
8740 let project = workspace.project.read(cx);
8741
8742 if !active_call.share_on_join(cx) {
8743 return None;
8744 }
8745
8746 if (project.is_local() || project.is_via_remote_server())
8747 && project.visible_worktrees(cx).any(|tree| {
8748 tree.read(cx)
8749 .root_entry()
8750 .is_some_and(|entry| entry.is_dir())
8751 })
8752 {
8753 Some(workspace.project.clone())
8754 } else {
8755 None
8756 }
8757 });
8758 if let Some(project) = project {
8759 let share_task = active_call.share_project(project, cx);
8760 return Some(cx.spawn(async move |_cx| -> Result<()> {
8761 share_task.await?;
8762 Ok(())
8763 }));
8764 }
8765 }
8766
8767 None
8768 });
8769 if let Some(task) = task {
8770 task.await?;
8771 return anyhow::Ok(true);
8772 }
8773 anyhow::Ok(false)
8774}
8775
8776pub fn join_channel(
8777 channel_id: ChannelId,
8778 app_state: Arc<AppState>,
8779 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8780 requesting_workspace: Option<WeakEntity<Workspace>>,
8781 cx: &mut App,
8782) -> Task<Result<()>> {
8783 let active_call = GlobalAnyActiveCall::global(cx).clone();
8784 cx.spawn(async move |cx| {
8785 let result = join_channel_internal(
8786 channel_id,
8787 &app_state,
8788 requesting_window,
8789 requesting_workspace,
8790 &*active_call.0,
8791 cx,
8792 )
8793 .await;
8794
8795 // join channel succeeded, and opened a window
8796 if matches!(result, Ok(true)) {
8797 return anyhow::Ok(());
8798 }
8799
8800 // find an existing workspace to focus and show call controls
8801 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8802 if active_window.is_none() {
8803 // no open workspaces, make one to show the error in (blergh)
8804 let OpenResult {
8805 window: window_handle,
8806 ..
8807 } = cx
8808 .update(|cx| {
8809 Workspace::new_local(
8810 vec![],
8811 app_state.clone(),
8812 requesting_window,
8813 None,
8814 None,
8815 true,
8816 cx,
8817 )
8818 })
8819 .await?;
8820
8821 window_handle
8822 .update(cx, |_, window, _cx| {
8823 window.activate_window();
8824 })
8825 .ok();
8826
8827 if result.is_ok() {
8828 cx.update(|cx| {
8829 cx.dispatch_action(&OpenChannelNotes);
8830 });
8831 }
8832
8833 active_window = Some(window_handle);
8834 }
8835
8836 if let Err(err) = result {
8837 log::error!("failed to join channel: {}", err);
8838 if let Some(active_window) = active_window {
8839 active_window
8840 .update(cx, |_, window, cx| {
8841 let detail: SharedString = match err.error_code() {
8842 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8843 ErrorCode::UpgradeRequired => concat!(
8844 "Your are running an unsupported version of Zed. ",
8845 "Please update to continue."
8846 )
8847 .into(),
8848 ErrorCode::NoSuchChannel => concat!(
8849 "No matching channel was found. ",
8850 "Please check the link and try again."
8851 )
8852 .into(),
8853 ErrorCode::Forbidden => concat!(
8854 "This channel is private, and you do not have access. ",
8855 "Please ask someone to add you and try again."
8856 )
8857 .into(),
8858 ErrorCode::Disconnected => {
8859 "Please check your internet connection and try again.".into()
8860 }
8861 _ => format!("{}\n\nPlease try again.", err).into(),
8862 };
8863 window.prompt(
8864 PromptLevel::Critical,
8865 "Failed to join channel",
8866 Some(&detail),
8867 &["Ok"],
8868 cx,
8869 )
8870 })?
8871 .await
8872 .ok();
8873 }
8874 }
8875
8876 // return ok, we showed the error to the user.
8877 anyhow::Ok(())
8878 })
8879}
8880
8881pub async fn get_any_active_multi_workspace(
8882 app_state: Arc<AppState>,
8883 mut cx: AsyncApp,
8884) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8885 // find an existing workspace to focus and show call controls
8886 let active_window = activate_any_workspace_window(&mut cx);
8887 if active_window.is_none() {
8888 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
8889 .await?;
8890 }
8891 activate_any_workspace_window(&mut cx).context("could not open zed")
8892}
8893
8894fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
8895 cx.update(|cx| {
8896 if let Some(workspace_window) = cx
8897 .active_window()
8898 .and_then(|window| window.downcast::<MultiWorkspace>())
8899 {
8900 return Some(workspace_window);
8901 }
8902
8903 for window in cx.windows() {
8904 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
8905 workspace_window
8906 .update(cx, |_, window, _| window.activate_window())
8907 .ok();
8908 return Some(workspace_window);
8909 }
8910 }
8911 None
8912 })
8913}
8914
8915pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
8916 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
8917}
8918
8919pub fn workspace_windows_for_location(
8920 serialized_location: &SerializedWorkspaceLocation,
8921 cx: &App,
8922) -> Vec<WindowHandle<MultiWorkspace>> {
8923 cx.windows()
8924 .into_iter()
8925 .filter_map(|window| window.downcast::<MultiWorkspace>())
8926 .filter(|multi_workspace| {
8927 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
8928 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
8929 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
8930 }
8931 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
8932 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
8933 a.distro_name == b.distro_name
8934 }
8935 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
8936 a.container_id == b.container_id
8937 }
8938 #[cfg(any(test, feature = "test-support"))]
8939 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
8940 a.id == b.id
8941 }
8942 _ => false,
8943 };
8944
8945 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
8946 multi_workspace.workspaces().iter().any(|workspace| {
8947 match workspace.read(cx).workspace_location(cx) {
8948 WorkspaceLocation::Location(location, _) => {
8949 match (&location, serialized_location) {
8950 (
8951 SerializedWorkspaceLocation::Local,
8952 SerializedWorkspaceLocation::Local,
8953 ) => true,
8954 (
8955 SerializedWorkspaceLocation::Remote(a),
8956 SerializedWorkspaceLocation::Remote(b),
8957 ) => same_host(a, b),
8958 _ => false,
8959 }
8960 }
8961 _ => false,
8962 }
8963 })
8964 })
8965 })
8966 .collect()
8967}
8968
8969pub async fn find_existing_workspace(
8970 abs_paths: &[PathBuf],
8971 open_options: &OpenOptions,
8972 location: &SerializedWorkspaceLocation,
8973 cx: &mut AsyncApp,
8974) -> (
8975 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
8976 OpenVisible,
8977) {
8978 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
8979 let mut open_visible = OpenVisible::All;
8980 let mut best_match = None;
8981
8982 if open_options.open_new_workspace != Some(true) {
8983 cx.update(|cx| {
8984 for window in workspace_windows_for_location(location, cx) {
8985 if let Ok(multi_workspace) = window.read(cx) {
8986 for workspace in multi_workspace.workspaces() {
8987 let project = workspace.read(cx).project.read(cx);
8988 let m = project.visibility_for_paths(
8989 abs_paths,
8990 open_options.open_new_workspace == None,
8991 cx,
8992 );
8993 if m > best_match {
8994 existing = Some((window, workspace.clone()));
8995 best_match = m;
8996 } else if best_match.is_none()
8997 && open_options.open_new_workspace == Some(false)
8998 {
8999 existing = Some((window, workspace.clone()))
9000 }
9001 }
9002 }
9003 }
9004 });
9005
9006 let all_paths_are_files = existing
9007 .as_ref()
9008 .and_then(|(_, target_workspace)| {
9009 cx.update(|cx| {
9010 let workspace = target_workspace.read(cx);
9011 let project = workspace.project.read(cx);
9012 let path_style = workspace.path_style(cx);
9013 Some(!abs_paths.iter().any(|path| {
9014 let path = util::paths::SanitizedPath::new(path);
9015 project.worktrees(cx).any(|worktree| {
9016 let worktree = worktree.read(cx);
9017 let abs_path = worktree.abs_path();
9018 path_style
9019 .strip_prefix(path.as_ref(), abs_path.as_ref())
9020 .and_then(|rel| worktree.entry_for_path(&rel))
9021 .is_some_and(|e| e.is_dir())
9022 })
9023 }))
9024 })
9025 })
9026 .unwrap_or(false);
9027
9028 if open_options.open_new_workspace.is_none()
9029 && existing.is_some()
9030 && open_options.wait
9031 && all_paths_are_files
9032 {
9033 cx.update(|cx| {
9034 let windows = workspace_windows_for_location(location, cx);
9035 let window = cx
9036 .active_window()
9037 .and_then(|window| window.downcast::<MultiWorkspace>())
9038 .filter(|window| windows.contains(window))
9039 .or_else(|| windows.into_iter().next());
9040 if let Some(window) = window {
9041 if let Ok(multi_workspace) = window.read(cx) {
9042 let active_workspace = multi_workspace.workspace().clone();
9043 existing = Some((window, active_workspace));
9044 open_visible = OpenVisible::None;
9045 }
9046 }
9047 });
9048 }
9049 }
9050 (existing, open_visible)
9051}
9052
9053#[derive(Default, Clone)]
9054pub struct OpenOptions {
9055 pub visible: Option<OpenVisible>,
9056 pub focus: Option<bool>,
9057 pub open_new_workspace: Option<bool>,
9058 pub wait: bool,
9059 pub replace_window: Option<WindowHandle<MultiWorkspace>>,
9060 pub env: Option<HashMap<String, String>>,
9061}
9062
9063/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
9064/// or [`Workspace::open_workspace_for_paths`].
9065pub struct OpenResult {
9066 pub window: WindowHandle<MultiWorkspace>,
9067 pub workspace: Entity<Workspace>,
9068 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
9069}
9070
9071/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
9072pub fn open_workspace_by_id(
9073 workspace_id: WorkspaceId,
9074 app_state: Arc<AppState>,
9075 requesting_window: Option<WindowHandle<MultiWorkspace>>,
9076 cx: &mut App,
9077) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
9078 let project_handle = Project::local(
9079 app_state.client.clone(),
9080 app_state.node_runtime.clone(),
9081 app_state.user_store.clone(),
9082 app_state.languages.clone(),
9083 app_state.fs.clone(),
9084 None,
9085 project::LocalProjectFlags {
9086 init_worktree_trust: true,
9087 ..project::LocalProjectFlags::default()
9088 },
9089 cx,
9090 );
9091
9092 let db = WorkspaceDb::global(cx);
9093 let kvp = db::kvp::KeyValueStore::global(cx);
9094 cx.spawn(async move |cx| {
9095 let serialized_workspace = db
9096 .workspace_for_id(workspace_id)
9097 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
9098
9099 let centered_layout = serialized_workspace.centered_layout;
9100
9101 let (window, workspace) = if let Some(window) = requesting_window {
9102 let workspace = window.update(cx, |multi_workspace, window, cx| {
9103 let workspace = cx.new(|cx| {
9104 let mut workspace = Workspace::new(
9105 Some(workspace_id),
9106 project_handle.clone(),
9107 app_state.clone(),
9108 window,
9109 cx,
9110 );
9111 workspace.centered_layout = centered_layout;
9112 workspace
9113 });
9114 multi_workspace.add_workspace(workspace.clone(), cx);
9115 workspace
9116 })?;
9117 (window, workspace)
9118 } else {
9119 let window_bounds_override = window_bounds_env_override();
9120
9121 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
9122 (Some(WindowBounds::Windowed(bounds)), None)
9123 } else if let Some(display) = serialized_workspace.display
9124 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
9125 {
9126 (Some(bounds.0), Some(display))
9127 } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
9128 (Some(bounds), Some(display))
9129 } else {
9130 (None, None)
9131 };
9132
9133 let options = cx.update(|cx| {
9134 let mut options = (app_state.build_window_options)(display, cx);
9135 options.window_bounds = window_bounds;
9136 options
9137 });
9138
9139 let window = cx.open_window(options, {
9140 let app_state = app_state.clone();
9141 let project_handle = project_handle.clone();
9142 move |window, cx| {
9143 let workspace = cx.new(|cx| {
9144 let mut workspace = Workspace::new(
9145 Some(workspace_id),
9146 project_handle,
9147 app_state,
9148 window,
9149 cx,
9150 );
9151 workspace.centered_layout = centered_layout;
9152 workspace
9153 });
9154 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9155 }
9156 })?;
9157
9158 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
9159 multi_workspace.workspace().clone()
9160 })?;
9161
9162 (window, workspace)
9163 };
9164
9165 notify_if_database_failed(window, cx);
9166
9167 // Restore items from the serialized workspace
9168 window
9169 .update(cx, |_, window, cx| {
9170 workspace.update(cx, |_workspace, cx| {
9171 open_items(Some(serialized_workspace), vec![], window, cx)
9172 })
9173 })?
9174 .await?;
9175
9176 window.update(cx, |_, window, cx| {
9177 workspace.update(cx, |workspace, cx| {
9178 workspace.serialize_workspace(window, cx);
9179 });
9180 })?;
9181
9182 Ok(window)
9183 })
9184}
9185
9186#[allow(clippy::type_complexity)]
9187pub fn open_paths(
9188 abs_paths: &[PathBuf],
9189 app_state: Arc<AppState>,
9190 open_options: OpenOptions,
9191 cx: &mut App,
9192) -> Task<anyhow::Result<OpenResult>> {
9193 let abs_paths = abs_paths.to_vec();
9194 #[cfg(target_os = "windows")]
9195 let wsl_path = abs_paths
9196 .iter()
9197 .find_map(|p| util::paths::WslPath::from_path(p));
9198
9199 cx.spawn(async move |cx| {
9200 let (mut existing, mut open_visible) = find_existing_workspace(
9201 &abs_paths,
9202 &open_options,
9203 &SerializedWorkspaceLocation::Local,
9204 cx,
9205 )
9206 .await;
9207
9208 // Fallback: if no workspace contains the paths and all paths are files,
9209 // prefer an existing local workspace window (active window first).
9210 if open_options.open_new_workspace.is_none() && existing.is_none() {
9211 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9212 let all_metadatas = futures::future::join_all(all_paths)
9213 .await
9214 .into_iter()
9215 .filter_map(|result| result.ok().flatten())
9216 .collect::<Vec<_>>();
9217
9218 if all_metadatas.iter().all(|file| !file.is_dir) {
9219 cx.update(|cx| {
9220 let windows = workspace_windows_for_location(
9221 &SerializedWorkspaceLocation::Local,
9222 cx,
9223 );
9224 let window = cx
9225 .active_window()
9226 .and_then(|window| window.downcast::<MultiWorkspace>())
9227 .filter(|window| windows.contains(window))
9228 .or_else(|| windows.into_iter().next());
9229 if let Some(window) = window {
9230 if let Ok(multi_workspace) = window.read(cx) {
9231 let active_workspace = multi_workspace.workspace().clone();
9232 existing = Some((window, active_workspace));
9233 open_visible = OpenVisible::None;
9234 }
9235 }
9236 });
9237 }
9238 }
9239
9240 let result = if let Some((existing, target_workspace)) = existing {
9241 let open_task = existing
9242 .update(cx, |multi_workspace, window, cx| {
9243 window.activate_window();
9244 multi_workspace.activate(target_workspace.clone(), cx);
9245 target_workspace.update(cx, |workspace, cx| {
9246 workspace.open_paths(
9247 abs_paths,
9248 OpenOptions {
9249 visible: Some(open_visible),
9250 ..Default::default()
9251 },
9252 None,
9253 window,
9254 cx,
9255 )
9256 })
9257 })?
9258 .await;
9259
9260 _ = existing.update(cx, |multi_workspace, _, cx| {
9261 let workspace = multi_workspace.workspace().clone();
9262 workspace.update(cx, |workspace, cx| {
9263 for item in open_task.iter().flatten() {
9264 if let Err(e) = item {
9265 workspace.show_error(&e, cx);
9266 }
9267 }
9268 });
9269 });
9270
9271 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9272 } else {
9273 let result = cx
9274 .update(move |cx| {
9275 Workspace::new_local(
9276 abs_paths,
9277 app_state.clone(),
9278 open_options.replace_window,
9279 open_options.env,
9280 None,
9281 true,
9282 cx,
9283 )
9284 })
9285 .await;
9286
9287 if let Ok(ref result) = result {
9288 result.window
9289 .update(cx, |_, window, _cx| {
9290 window.activate_window();
9291 })
9292 .log_err();
9293 }
9294
9295 result
9296 };
9297
9298 #[cfg(target_os = "windows")]
9299 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9300 && let Ok(ref result) = result
9301 {
9302 result.window
9303 .update(cx, move |multi_workspace, _window, cx| {
9304 struct OpenInWsl;
9305 let workspace = multi_workspace.workspace().clone();
9306 workspace.update(cx, |workspace, cx| {
9307 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9308 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9309 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9310 cx.new(move |cx| {
9311 MessageNotification::new(msg, cx)
9312 .primary_message("Open in WSL")
9313 .primary_icon(IconName::FolderOpen)
9314 .primary_on_click(move |window, cx| {
9315 window.dispatch_action(Box::new(remote::OpenWslPath {
9316 distro: remote::WslConnectionOptions {
9317 distro_name: distro.clone(),
9318 user: None,
9319 },
9320 paths: vec![path.clone().into()],
9321 }), cx)
9322 })
9323 })
9324 });
9325 });
9326 })
9327 .unwrap();
9328 };
9329 result
9330 })
9331}
9332
9333pub fn open_new(
9334 open_options: OpenOptions,
9335 app_state: Arc<AppState>,
9336 cx: &mut App,
9337 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9338) -> Task<anyhow::Result<()>> {
9339 let task = Workspace::new_local(
9340 Vec::new(),
9341 app_state,
9342 open_options.replace_window,
9343 open_options.env,
9344 Some(Box::new(init)),
9345 true,
9346 cx,
9347 );
9348 cx.spawn(async move |cx| {
9349 let OpenResult { window, .. } = task.await?;
9350 window
9351 .update(cx, |_, window, _cx| {
9352 window.activate_window();
9353 })
9354 .ok();
9355 Ok(())
9356 })
9357}
9358
9359pub fn create_and_open_local_file(
9360 path: &'static Path,
9361 window: &mut Window,
9362 cx: &mut Context<Workspace>,
9363 default_content: impl 'static + Send + FnOnce() -> Rope,
9364) -> Task<Result<Box<dyn ItemHandle>>> {
9365 cx.spawn_in(window, async move |workspace, cx| {
9366 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9367 if !fs.is_file(path).await {
9368 fs.create_file(path, Default::default()).await?;
9369 fs.save(path, &default_content(), Default::default())
9370 .await?;
9371 }
9372
9373 workspace
9374 .update_in(cx, |workspace, window, cx| {
9375 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9376 let path = workspace
9377 .project
9378 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9379 cx.spawn_in(window, async move |workspace, cx| {
9380 let path = path.await?;
9381
9382 let path = fs.canonicalize(&path).await.unwrap_or(path);
9383
9384 let mut items = workspace
9385 .update_in(cx, |workspace, window, cx| {
9386 workspace.open_paths(
9387 vec![path.to_path_buf()],
9388 OpenOptions {
9389 visible: Some(OpenVisible::None),
9390 ..Default::default()
9391 },
9392 None,
9393 window,
9394 cx,
9395 )
9396 })?
9397 .await;
9398 let item = items.pop().flatten();
9399 item.with_context(|| format!("path {path:?} is not a file"))?
9400 })
9401 })
9402 })?
9403 .await?
9404 .await
9405 })
9406}
9407
9408pub fn open_remote_project_with_new_connection(
9409 window: WindowHandle<MultiWorkspace>,
9410 remote_connection: Arc<dyn RemoteConnection>,
9411 cancel_rx: oneshot::Receiver<()>,
9412 delegate: Arc<dyn RemoteClientDelegate>,
9413 app_state: Arc<AppState>,
9414 paths: Vec<PathBuf>,
9415 cx: &mut App,
9416) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9417 cx.spawn(async move |cx| {
9418 let (workspace_id, serialized_workspace) =
9419 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9420 .await?;
9421
9422 let session = match cx
9423 .update(|cx| {
9424 remote::RemoteClient::new(
9425 ConnectionIdentifier::Workspace(workspace_id.0),
9426 remote_connection,
9427 cancel_rx,
9428 delegate,
9429 cx,
9430 )
9431 })
9432 .await?
9433 {
9434 Some(result) => result,
9435 None => return Ok(Vec::new()),
9436 };
9437
9438 let project = cx.update(|cx| {
9439 project::Project::remote(
9440 session,
9441 app_state.client.clone(),
9442 app_state.node_runtime.clone(),
9443 app_state.user_store.clone(),
9444 app_state.languages.clone(),
9445 app_state.fs.clone(),
9446 true,
9447 cx,
9448 )
9449 });
9450
9451 open_remote_project_inner(
9452 project,
9453 paths,
9454 workspace_id,
9455 serialized_workspace,
9456 app_state,
9457 window,
9458 cx,
9459 )
9460 .await
9461 })
9462}
9463
9464pub fn open_remote_project_with_existing_connection(
9465 connection_options: RemoteConnectionOptions,
9466 project: Entity<Project>,
9467 paths: Vec<PathBuf>,
9468 app_state: Arc<AppState>,
9469 window: WindowHandle<MultiWorkspace>,
9470 cx: &mut AsyncApp,
9471) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9472 cx.spawn(async move |cx| {
9473 let (workspace_id, serialized_workspace) =
9474 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9475
9476 open_remote_project_inner(
9477 project,
9478 paths,
9479 workspace_id,
9480 serialized_workspace,
9481 app_state,
9482 window,
9483 cx,
9484 )
9485 .await
9486 })
9487}
9488
9489async fn open_remote_project_inner(
9490 project: Entity<Project>,
9491 paths: Vec<PathBuf>,
9492 workspace_id: WorkspaceId,
9493 serialized_workspace: Option<SerializedWorkspace>,
9494 app_state: Arc<AppState>,
9495 window: WindowHandle<MultiWorkspace>,
9496 cx: &mut AsyncApp,
9497) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9498 let db = cx.update(|cx| WorkspaceDb::global(cx));
9499 let toolchains = db.toolchains(workspace_id).await?;
9500 for (toolchain, worktree_path, path) in toolchains {
9501 project
9502 .update(cx, |this, cx| {
9503 let Some(worktree_id) =
9504 this.find_worktree(&worktree_path, cx)
9505 .and_then(|(worktree, rel_path)| {
9506 if rel_path.is_empty() {
9507 Some(worktree.read(cx).id())
9508 } else {
9509 None
9510 }
9511 })
9512 else {
9513 return Task::ready(None);
9514 };
9515
9516 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9517 })
9518 .await;
9519 }
9520 let mut project_paths_to_open = vec![];
9521 let mut project_path_errors = vec![];
9522
9523 for path in paths {
9524 let result = cx
9525 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9526 .await;
9527 match result {
9528 Ok((_, project_path)) => {
9529 project_paths_to_open.push((path.clone(), Some(project_path)));
9530 }
9531 Err(error) => {
9532 project_path_errors.push(error);
9533 }
9534 };
9535 }
9536
9537 if project_paths_to_open.is_empty() {
9538 return Err(project_path_errors.pop().context("no paths given")?);
9539 }
9540
9541 let workspace = window.update(cx, |multi_workspace, window, cx| {
9542 telemetry::event!("SSH Project Opened");
9543
9544 let new_workspace = cx.new(|cx| {
9545 let mut workspace =
9546 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9547 workspace.update_history(cx);
9548
9549 if let Some(ref serialized) = serialized_workspace {
9550 workspace.centered_layout = serialized.centered_layout;
9551 }
9552
9553 workspace
9554 });
9555
9556 multi_workspace.activate(new_workspace.clone(), cx);
9557 new_workspace
9558 })?;
9559
9560 let items = window
9561 .update(cx, |_, window, cx| {
9562 window.activate_window();
9563 workspace.update(cx, |_workspace, cx| {
9564 open_items(serialized_workspace, project_paths_to_open, window, cx)
9565 })
9566 })?
9567 .await?;
9568
9569 workspace.update(cx, |workspace, cx| {
9570 for error in project_path_errors {
9571 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9572 if let Some(path) = error.error_tag("path") {
9573 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9574 }
9575 } else {
9576 workspace.show_error(&error, cx)
9577 }
9578 }
9579 });
9580
9581 Ok(items.into_iter().map(|item| item?.ok()).collect())
9582}
9583
9584fn deserialize_remote_project(
9585 connection_options: RemoteConnectionOptions,
9586 paths: Vec<PathBuf>,
9587 cx: &AsyncApp,
9588) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9589 let db = cx.update(|cx| WorkspaceDb::global(cx));
9590 cx.background_spawn(async move {
9591 let remote_connection_id = db
9592 .get_or_create_remote_connection(connection_options)
9593 .await?;
9594
9595 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9596
9597 let workspace_id = if let Some(workspace_id) =
9598 serialized_workspace.as_ref().map(|workspace| workspace.id)
9599 {
9600 workspace_id
9601 } else {
9602 db.next_id().await?
9603 };
9604
9605 Ok((workspace_id, serialized_workspace))
9606 })
9607}
9608
9609pub fn join_in_room_project(
9610 project_id: u64,
9611 follow_user_id: u64,
9612 app_state: Arc<AppState>,
9613 cx: &mut App,
9614) -> Task<Result<()>> {
9615 let windows = cx.windows();
9616 cx.spawn(async move |cx| {
9617 let existing_window_and_workspace: Option<(
9618 WindowHandle<MultiWorkspace>,
9619 Entity<Workspace>,
9620 )> = windows.into_iter().find_map(|window_handle| {
9621 window_handle
9622 .downcast::<MultiWorkspace>()
9623 .and_then(|window_handle| {
9624 window_handle
9625 .update(cx, |multi_workspace, _window, cx| {
9626 for workspace in multi_workspace.workspaces() {
9627 if workspace.read(cx).project().read(cx).remote_id()
9628 == Some(project_id)
9629 {
9630 return Some((window_handle, workspace.clone()));
9631 }
9632 }
9633 None
9634 })
9635 .unwrap_or(None)
9636 })
9637 });
9638
9639 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9640 existing_window_and_workspace
9641 {
9642 existing_window
9643 .update(cx, |multi_workspace, _, cx| {
9644 multi_workspace.activate(target_workspace, cx);
9645 })
9646 .ok();
9647 existing_window
9648 } else {
9649 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9650 let project = cx
9651 .update(|cx| {
9652 active_call.0.join_project(
9653 project_id,
9654 app_state.languages.clone(),
9655 app_state.fs.clone(),
9656 cx,
9657 )
9658 })
9659 .await?;
9660
9661 let window_bounds_override = window_bounds_env_override();
9662 cx.update(|cx| {
9663 let mut options = (app_state.build_window_options)(None, cx);
9664 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9665 cx.open_window(options, |window, cx| {
9666 let workspace = cx.new(|cx| {
9667 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9668 });
9669 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9670 })
9671 })?
9672 };
9673
9674 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9675 cx.activate(true);
9676 window.activate_window();
9677
9678 // We set the active workspace above, so this is the correct workspace.
9679 let workspace = multi_workspace.workspace().clone();
9680 workspace.update(cx, |workspace, cx| {
9681 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9682 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9683 .or_else(|| {
9684 // If we couldn't follow the given user, follow the host instead.
9685 let collaborator = workspace
9686 .project()
9687 .read(cx)
9688 .collaborators()
9689 .values()
9690 .find(|collaborator| collaborator.is_host)?;
9691 Some(collaborator.peer_id)
9692 });
9693
9694 if let Some(follow_peer_id) = follow_peer_id {
9695 workspace.follow(follow_peer_id, window, cx);
9696 }
9697 });
9698 })?;
9699
9700 anyhow::Ok(())
9701 })
9702}
9703
9704pub fn reload(cx: &mut App) {
9705 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9706 let mut workspace_windows = cx
9707 .windows()
9708 .into_iter()
9709 .filter_map(|window| window.downcast::<MultiWorkspace>())
9710 .collect::<Vec<_>>();
9711
9712 // If multiple windows have unsaved changes, and need a save prompt,
9713 // prompt in the active window before switching to a different window.
9714 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9715
9716 let mut prompt = None;
9717 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9718 prompt = window
9719 .update(cx, |_, window, cx| {
9720 window.prompt(
9721 PromptLevel::Info,
9722 "Are you sure you want to restart?",
9723 None,
9724 &["Restart", "Cancel"],
9725 cx,
9726 )
9727 })
9728 .ok();
9729 }
9730
9731 cx.spawn(async move |cx| {
9732 if let Some(prompt) = prompt {
9733 let answer = prompt.await?;
9734 if answer != 0 {
9735 return anyhow::Ok(());
9736 }
9737 }
9738
9739 // If the user cancels any save prompt, then keep the app open.
9740 for window in workspace_windows {
9741 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9742 let workspace = multi_workspace.workspace().clone();
9743 workspace.update(cx, |workspace, cx| {
9744 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9745 })
9746 }) && !should_close.await?
9747 {
9748 return anyhow::Ok(());
9749 }
9750 }
9751 cx.update(|cx| cx.restart());
9752 anyhow::Ok(())
9753 })
9754 .detach_and_log_err(cx);
9755}
9756
9757fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9758 let mut parts = value.split(',');
9759 let x: usize = parts.next()?.parse().ok()?;
9760 let y: usize = parts.next()?.parse().ok()?;
9761 Some(point(px(x as f32), px(y as f32)))
9762}
9763
9764fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9765 let mut parts = value.split(',');
9766 let width: usize = parts.next()?.parse().ok()?;
9767 let height: usize = parts.next()?.parse().ok()?;
9768 Some(size(px(width as f32), px(height as f32)))
9769}
9770
9771/// Add client-side decorations (rounded corners, shadows, resize handling) when
9772/// appropriate.
9773///
9774/// The `border_radius_tiling` parameter allows overriding which corners get
9775/// rounded, independently of the actual window tiling state. This is used
9776/// specifically for the workspace switcher sidebar: when the sidebar is open,
9777/// we want square corners on the left (so the sidebar appears flush with the
9778/// window edge) but we still need the shadow padding for proper visual
9779/// appearance. Unlike actual window tiling, this only affects border radius -
9780/// not padding or shadows.
9781pub fn client_side_decorations(
9782 element: impl IntoElement,
9783 window: &mut Window,
9784 cx: &mut App,
9785 border_radius_tiling: Tiling,
9786) -> Stateful<Div> {
9787 const BORDER_SIZE: Pixels = px(1.0);
9788 let decorations = window.window_decorations();
9789 let tiling = match decorations {
9790 Decorations::Server => Tiling::default(),
9791 Decorations::Client { tiling } => tiling,
9792 };
9793
9794 match decorations {
9795 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9796 Decorations::Server => window.set_client_inset(px(0.0)),
9797 }
9798
9799 struct GlobalResizeEdge(ResizeEdge);
9800 impl Global for GlobalResizeEdge {}
9801
9802 div()
9803 .id("window-backdrop")
9804 .bg(transparent_black())
9805 .map(|div| match decorations {
9806 Decorations::Server => div,
9807 Decorations::Client { .. } => div
9808 .when(
9809 !(tiling.top
9810 || tiling.right
9811 || border_radius_tiling.top
9812 || border_radius_tiling.right),
9813 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9814 )
9815 .when(
9816 !(tiling.top
9817 || tiling.left
9818 || border_radius_tiling.top
9819 || border_radius_tiling.left),
9820 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9821 )
9822 .when(
9823 !(tiling.bottom
9824 || tiling.right
9825 || border_radius_tiling.bottom
9826 || border_radius_tiling.right),
9827 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9828 )
9829 .when(
9830 !(tiling.bottom
9831 || tiling.left
9832 || border_radius_tiling.bottom
9833 || border_radius_tiling.left),
9834 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9835 )
9836 .when(!tiling.top, |div| {
9837 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9838 })
9839 .when(!tiling.bottom, |div| {
9840 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9841 })
9842 .when(!tiling.left, |div| {
9843 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9844 })
9845 .when(!tiling.right, |div| {
9846 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9847 })
9848 .on_mouse_move(move |e, window, cx| {
9849 let size = window.window_bounds().get_bounds().size;
9850 let pos = e.position;
9851
9852 let new_edge =
9853 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9854
9855 let edge = cx.try_global::<GlobalResizeEdge>();
9856 if new_edge != edge.map(|edge| edge.0) {
9857 window
9858 .window_handle()
9859 .update(cx, |workspace, _, cx| {
9860 cx.notify(workspace.entity_id());
9861 })
9862 .ok();
9863 }
9864 })
9865 .on_mouse_down(MouseButton::Left, move |e, window, _| {
9866 let size = window.window_bounds().get_bounds().size;
9867 let pos = e.position;
9868
9869 let edge = match resize_edge(
9870 pos,
9871 theme::CLIENT_SIDE_DECORATION_SHADOW,
9872 size,
9873 tiling,
9874 ) {
9875 Some(value) => value,
9876 None => return,
9877 };
9878
9879 window.start_window_resize(edge);
9880 }),
9881 })
9882 .size_full()
9883 .child(
9884 div()
9885 .cursor(CursorStyle::Arrow)
9886 .map(|div| match decorations {
9887 Decorations::Server => div,
9888 Decorations::Client { .. } => div
9889 .border_color(cx.theme().colors().border)
9890 .when(
9891 !(tiling.top
9892 || tiling.right
9893 || border_radius_tiling.top
9894 || border_radius_tiling.right),
9895 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9896 )
9897 .when(
9898 !(tiling.top
9899 || tiling.left
9900 || border_radius_tiling.top
9901 || border_radius_tiling.left),
9902 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9903 )
9904 .when(
9905 !(tiling.bottom
9906 || tiling.right
9907 || border_radius_tiling.bottom
9908 || border_radius_tiling.right),
9909 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9910 )
9911 .when(
9912 !(tiling.bottom
9913 || tiling.left
9914 || border_radius_tiling.bottom
9915 || border_radius_tiling.left),
9916 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9917 )
9918 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
9919 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
9920 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
9921 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
9922 .when(!tiling.is_tiled(), |div| {
9923 div.shadow(vec![gpui::BoxShadow {
9924 color: Hsla {
9925 h: 0.,
9926 s: 0.,
9927 l: 0.,
9928 a: 0.4,
9929 },
9930 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
9931 spread_radius: px(0.),
9932 offset: point(px(0.0), px(0.0)),
9933 }])
9934 }),
9935 })
9936 .on_mouse_move(|_e, _, cx| {
9937 cx.stop_propagation();
9938 })
9939 .size_full()
9940 .child(element),
9941 )
9942 .map(|div| match decorations {
9943 Decorations::Server => div,
9944 Decorations::Client { tiling, .. } => div.child(
9945 canvas(
9946 |_bounds, window, _| {
9947 window.insert_hitbox(
9948 Bounds::new(
9949 point(px(0.0), px(0.0)),
9950 window.window_bounds().get_bounds().size,
9951 ),
9952 HitboxBehavior::Normal,
9953 )
9954 },
9955 move |_bounds, hitbox, window, cx| {
9956 let mouse = window.mouse_position();
9957 let size = window.window_bounds().get_bounds().size;
9958 let Some(edge) =
9959 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
9960 else {
9961 return;
9962 };
9963 cx.set_global(GlobalResizeEdge(edge));
9964 window.set_cursor_style(
9965 match edge {
9966 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
9967 ResizeEdge::Left | ResizeEdge::Right => {
9968 CursorStyle::ResizeLeftRight
9969 }
9970 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
9971 CursorStyle::ResizeUpLeftDownRight
9972 }
9973 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
9974 CursorStyle::ResizeUpRightDownLeft
9975 }
9976 },
9977 &hitbox,
9978 );
9979 },
9980 )
9981 .size_full()
9982 .absolute(),
9983 ),
9984 })
9985}
9986
9987fn resize_edge(
9988 pos: Point<Pixels>,
9989 shadow_size: Pixels,
9990 window_size: Size<Pixels>,
9991 tiling: Tiling,
9992) -> Option<ResizeEdge> {
9993 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
9994 if bounds.contains(&pos) {
9995 return None;
9996 }
9997
9998 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
9999 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10000 if !tiling.top && top_left_bounds.contains(&pos) {
10001 return Some(ResizeEdge::TopLeft);
10002 }
10003
10004 let top_right_bounds = Bounds::new(
10005 Point::new(window_size.width - corner_size.width, px(0.)),
10006 corner_size,
10007 );
10008 if !tiling.top && top_right_bounds.contains(&pos) {
10009 return Some(ResizeEdge::TopRight);
10010 }
10011
10012 let bottom_left_bounds = Bounds::new(
10013 Point::new(px(0.), window_size.height - corner_size.height),
10014 corner_size,
10015 );
10016 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10017 return Some(ResizeEdge::BottomLeft);
10018 }
10019
10020 let bottom_right_bounds = Bounds::new(
10021 Point::new(
10022 window_size.width - corner_size.width,
10023 window_size.height - corner_size.height,
10024 ),
10025 corner_size,
10026 );
10027 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10028 return Some(ResizeEdge::BottomRight);
10029 }
10030
10031 if !tiling.top && pos.y < shadow_size {
10032 Some(ResizeEdge::Top)
10033 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10034 Some(ResizeEdge::Bottom)
10035 } else if !tiling.left && pos.x < shadow_size {
10036 Some(ResizeEdge::Left)
10037 } else if !tiling.right && pos.x > window_size.width - shadow_size {
10038 Some(ResizeEdge::Right)
10039 } else {
10040 None
10041 }
10042}
10043
10044fn join_pane_into_active(
10045 active_pane: &Entity<Pane>,
10046 pane: &Entity<Pane>,
10047 window: &mut Window,
10048 cx: &mut App,
10049) {
10050 if pane == active_pane {
10051 } else if pane.read(cx).items_len() == 0 {
10052 pane.update(cx, |_, cx| {
10053 cx.emit(pane::Event::Remove {
10054 focus_on_pane: None,
10055 });
10056 })
10057 } else {
10058 move_all_items(pane, active_pane, window, cx);
10059 }
10060}
10061
10062fn move_all_items(
10063 from_pane: &Entity<Pane>,
10064 to_pane: &Entity<Pane>,
10065 window: &mut Window,
10066 cx: &mut App,
10067) {
10068 let destination_is_different = from_pane != to_pane;
10069 let mut moved_items = 0;
10070 for (item_ix, item_handle) in from_pane
10071 .read(cx)
10072 .items()
10073 .enumerate()
10074 .map(|(ix, item)| (ix, item.clone()))
10075 .collect::<Vec<_>>()
10076 {
10077 let ix = item_ix - moved_items;
10078 if destination_is_different {
10079 // Close item from previous pane
10080 from_pane.update(cx, |source, cx| {
10081 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10082 });
10083 moved_items += 1;
10084 }
10085
10086 // This automatically removes duplicate items in the pane
10087 to_pane.update(cx, |destination, cx| {
10088 destination.add_item(item_handle, true, true, None, window, cx);
10089 window.focus(&destination.focus_handle(cx), cx)
10090 });
10091 }
10092}
10093
10094pub fn move_item(
10095 source: &Entity<Pane>,
10096 destination: &Entity<Pane>,
10097 item_id_to_move: EntityId,
10098 destination_index: usize,
10099 activate: bool,
10100 window: &mut Window,
10101 cx: &mut App,
10102) {
10103 let Some((item_ix, item_handle)) = source
10104 .read(cx)
10105 .items()
10106 .enumerate()
10107 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10108 .map(|(ix, item)| (ix, item.clone()))
10109 else {
10110 // Tab was closed during drag
10111 return;
10112 };
10113
10114 if source != destination {
10115 // Close item from previous pane
10116 source.update(cx, |source, cx| {
10117 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10118 });
10119 }
10120
10121 // This automatically removes duplicate items in the pane
10122 destination.update(cx, |destination, cx| {
10123 destination.add_item_inner(
10124 item_handle,
10125 activate,
10126 activate,
10127 activate,
10128 Some(destination_index),
10129 window,
10130 cx,
10131 );
10132 if activate {
10133 window.focus(&destination.focus_handle(cx), cx)
10134 }
10135 });
10136}
10137
10138pub fn move_active_item(
10139 source: &Entity<Pane>,
10140 destination: &Entity<Pane>,
10141 focus_destination: bool,
10142 close_if_empty: bool,
10143 window: &mut Window,
10144 cx: &mut App,
10145) {
10146 if source == destination {
10147 return;
10148 }
10149 let Some(active_item) = source.read(cx).active_item() else {
10150 return;
10151 };
10152 source.update(cx, |source_pane, cx| {
10153 let item_id = active_item.item_id();
10154 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10155 destination.update(cx, |target_pane, cx| {
10156 target_pane.add_item(
10157 active_item,
10158 focus_destination,
10159 focus_destination,
10160 Some(target_pane.items_len()),
10161 window,
10162 cx,
10163 );
10164 });
10165 });
10166}
10167
10168pub fn clone_active_item(
10169 workspace_id: Option<WorkspaceId>,
10170 source: &Entity<Pane>,
10171 destination: &Entity<Pane>,
10172 focus_destination: bool,
10173 window: &mut Window,
10174 cx: &mut App,
10175) {
10176 if source == destination {
10177 return;
10178 }
10179 let Some(active_item) = source.read(cx).active_item() else {
10180 return;
10181 };
10182 if !active_item.can_split(cx) {
10183 return;
10184 }
10185 let destination = destination.downgrade();
10186 let task = active_item.clone_on_split(workspace_id, window, cx);
10187 window
10188 .spawn(cx, async move |cx| {
10189 let Some(clone) = task.await else {
10190 return;
10191 };
10192 destination
10193 .update_in(cx, |target_pane, window, cx| {
10194 target_pane.add_item(
10195 clone,
10196 focus_destination,
10197 focus_destination,
10198 Some(target_pane.items_len()),
10199 window,
10200 cx,
10201 );
10202 })
10203 .log_err();
10204 })
10205 .detach();
10206}
10207
10208#[derive(Debug)]
10209pub struct WorkspacePosition {
10210 pub window_bounds: Option<WindowBounds>,
10211 pub display: Option<Uuid>,
10212 pub centered_layout: bool,
10213}
10214
10215pub fn remote_workspace_position_from_db(
10216 connection_options: RemoteConnectionOptions,
10217 paths_to_open: &[PathBuf],
10218 cx: &App,
10219) -> Task<Result<WorkspacePosition>> {
10220 let paths = paths_to_open.to_vec();
10221 let db = WorkspaceDb::global(cx);
10222 let kvp = db::kvp::KeyValueStore::global(cx);
10223
10224 cx.background_spawn(async move {
10225 let remote_connection_id = db
10226 .get_or_create_remote_connection(connection_options)
10227 .await
10228 .context("fetching serialized ssh project")?;
10229 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10230
10231 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10232 (Some(WindowBounds::Windowed(bounds)), None)
10233 } else {
10234 let restorable_bounds = serialized_workspace
10235 .as_ref()
10236 .and_then(|workspace| {
10237 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10238 })
10239 .or_else(|| persistence::read_default_window_bounds(&kvp));
10240
10241 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10242 (Some(serialized_bounds), Some(serialized_display))
10243 } else {
10244 (None, None)
10245 }
10246 };
10247
10248 let centered_layout = serialized_workspace
10249 .as_ref()
10250 .map(|w| w.centered_layout)
10251 .unwrap_or(false);
10252
10253 Ok(WorkspacePosition {
10254 window_bounds,
10255 display,
10256 centered_layout,
10257 })
10258 })
10259}
10260
10261pub fn with_active_or_new_workspace(
10262 cx: &mut App,
10263 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10264) {
10265 match cx
10266 .active_window()
10267 .and_then(|w| w.downcast::<MultiWorkspace>())
10268 {
10269 Some(multi_workspace) => {
10270 cx.defer(move |cx| {
10271 multi_workspace
10272 .update(cx, |multi_workspace, window, cx| {
10273 let workspace = multi_workspace.workspace().clone();
10274 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10275 })
10276 .log_err();
10277 });
10278 }
10279 None => {
10280 let app_state = AppState::global(cx);
10281 if let Some(app_state) = app_state.upgrade() {
10282 open_new(
10283 OpenOptions::default(),
10284 app_state,
10285 cx,
10286 move |workspace, window, cx| f(workspace, window, cx),
10287 )
10288 .detach_and_log_err(cx);
10289 }
10290 }
10291 }
10292}
10293
10294/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10295/// key. This migration path only runs once per panel per workspace.
10296fn load_legacy_panel_size(
10297 panel_key: &str,
10298 dock_position: DockPosition,
10299 workspace: &Workspace,
10300 cx: &mut App,
10301) -> Option<Pixels> {
10302 #[derive(Deserialize)]
10303 struct LegacyPanelState {
10304 #[serde(default)]
10305 width: Option<Pixels>,
10306 #[serde(default)]
10307 height: Option<Pixels>,
10308 }
10309
10310 let workspace_id = workspace
10311 .database_id()
10312 .map(|id| i64::from(id).to_string())
10313 .or_else(|| workspace.session_id())?;
10314
10315 let legacy_key = match panel_key {
10316 "ProjectPanel" => {
10317 format!("{}-{:?}", "ProjectPanel", workspace_id)
10318 }
10319 "OutlinePanel" => {
10320 format!("{}-{:?}", "OutlinePanel", workspace_id)
10321 }
10322 "GitPanel" => {
10323 format!("{}-{:?}", "GitPanel", workspace_id)
10324 }
10325 "TerminalPanel" => {
10326 format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10327 }
10328 _ => return None,
10329 };
10330
10331 let kvp = db::kvp::KeyValueStore::global(cx);
10332 let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10333 let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10334 let size = match dock_position {
10335 DockPosition::Bottom => state.height,
10336 DockPosition::Left | DockPosition::Right => state.width,
10337 }?;
10338
10339 cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10340 .detach_and_log_err(cx);
10341
10342 Some(size)
10343}
10344
10345#[cfg(test)]
10346mod tests {
10347 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10348
10349 use super::*;
10350 use crate::{
10351 dock::{PanelEvent, test::TestPanel},
10352 item::{
10353 ItemBufferKind, ItemEvent,
10354 test::{TestItem, TestProjectItem},
10355 },
10356 };
10357 use fs::FakeFs;
10358 use gpui::{
10359 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10360 UpdateGlobal, VisualTestContext, px,
10361 };
10362 use project::{Project, ProjectEntryId};
10363 use serde_json::json;
10364 use settings::SettingsStore;
10365 use util::path;
10366 use util::rel_path::rel_path;
10367
10368 #[gpui::test]
10369 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10370 init_test(cx);
10371
10372 let fs = FakeFs::new(cx.executor());
10373 let project = Project::test(fs, [], cx).await;
10374 let (workspace, cx) =
10375 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10376
10377 // Adding an item with no ambiguity renders the tab without detail.
10378 let item1 = cx.new(|cx| {
10379 let mut item = TestItem::new(cx);
10380 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10381 item
10382 });
10383 workspace.update_in(cx, |workspace, window, cx| {
10384 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10385 });
10386 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10387
10388 // Adding an item that creates ambiguity increases the level of detail on
10389 // both tabs.
10390 let item2 = cx.new_window_entity(|_window, cx| {
10391 let mut item = TestItem::new(cx);
10392 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10393 item
10394 });
10395 workspace.update_in(cx, |workspace, window, cx| {
10396 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10397 });
10398 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10399 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10400
10401 // Adding an item that creates ambiguity increases the level of detail only
10402 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10403 // we stop at the highest detail available.
10404 let item3 = cx.new(|cx| {
10405 let mut item = TestItem::new(cx);
10406 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10407 item
10408 });
10409 workspace.update_in(cx, |workspace, window, cx| {
10410 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10411 });
10412 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10413 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10414 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10415 }
10416
10417 #[gpui::test]
10418 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10419 init_test(cx);
10420
10421 let fs = FakeFs::new(cx.executor());
10422 fs.insert_tree(
10423 "/root1",
10424 json!({
10425 "one.txt": "",
10426 "two.txt": "",
10427 }),
10428 )
10429 .await;
10430 fs.insert_tree(
10431 "/root2",
10432 json!({
10433 "three.txt": "",
10434 }),
10435 )
10436 .await;
10437
10438 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10439 let (workspace, cx) =
10440 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10441 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10442 let worktree_id = project.update(cx, |project, cx| {
10443 project.worktrees(cx).next().unwrap().read(cx).id()
10444 });
10445
10446 let item1 = cx.new(|cx| {
10447 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10448 });
10449 let item2 = cx.new(|cx| {
10450 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10451 });
10452
10453 // Add an item to an empty pane
10454 workspace.update_in(cx, |workspace, window, cx| {
10455 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10456 });
10457 project.update(cx, |project, cx| {
10458 assert_eq!(
10459 project.active_entry(),
10460 project
10461 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10462 .map(|e| e.id)
10463 );
10464 });
10465 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10466
10467 // Add a second item to a non-empty pane
10468 workspace.update_in(cx, |workspace, window, cx| {
10469 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10470 });
10471 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10472 project.update(cx, |project, cx| {
10473 assert_eq!(
10474 project.active_entry(),
10475 project
10476 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10477 .map(|e| e.id)
10478 );
10479 });
10480
10481 // Close the active item
10482 pane.update_in(cx, |pane, window, cx| {
10483 pane.close_active_item(&Default::default(), window, cx)
10484 })
10485 .await
10486 .unwrap();
10487 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10488 project.update(cx, |project, cx| {
10489 assert_eq!(
10490 project.active_entry(),
10491 project
10492 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10493 .map(|e| e.id)
10494 );
10495 });
10496
10497 // Add a project folder
10498 project
10499 .update(cx, |project, cx| {
10500 project.find_or_create_worktree("root2", true, cx)
10501 })
10502 .await
10503 .unwrap();
10504 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10505
10506 // Remove a project folder
10507 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10508 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10509 }
10510
10511 #[gpui::test]
10512 async fn test_close_window(cx: &mut TestAppContext) {
10513 init_test(cx);
10514
10515 let fs = FakeFs::new(cx.executor());
10516 fs.insert_tree("/root", json!({ "one": "" })).await;
10517
10518 let project = Project::test(fs, ["root".as_ref()], cx).await;
10519 let (workspace, cx) =
10520 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10521
10522 // When there are no dirty items, there's nothing to do.
10523 let item1 = cx.new(TestItem::new);
10524 workspace.update_in(cx, |w, window, cx| {
10525 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10526 });
10527 let task = workspace.update_in(cx, |w, window, cx| {
10528 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10529 });
10530 assert!(task.await.unwrap());
10531
10532 // When there are dirty untitled items, prompt to save each one. If the user
10533 // cancels any prompt, then abort.
10534 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10535 let item3 = cx.new(|cx| {
10536 TestItem::new(cx)
10537 .with_dirty(true)
10538 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10539 });
10540 workspace.update_in(cx, |w, window, cx| {
10541 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10542 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10543 });
10544 let task = workspace.update_in(cx, |w, window, cx| {
10545 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10546 });
10547 cx.executor().run_until_parked();
10548 cx.simulate_prompt_answer("Cancel"); // cancel save all
10549 cx.executor().run_until_parked();
10550 assert!(!cx.has_pending_prompt());
10551 assert!(!task.await.unwrap());
10552 }
10553
10554 #[gpui::test]
10555 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10556 init_test(cx);
10557
10558 let fs = FakeFs::new(cx.executor());
10559 fs.insert_tree("/root", json!({ "one": "" })).await;
10560
10561 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10562 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10563 let multi_workspace_handle =
10564 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10565 cx.run_until_parked();
10566
10567 let workspace_a = multi_workspace_handle
10568 .read_with(cx, |mw, _| mw.workspace().clone())
10569 .unwrap();
10570
10571 let workspace_b = multi_workspace_handle
10572 .update(cx, |mw, window, cx| {
10573 mw.test_add_workspace(project_b, window, cx)
10574 })
10575 .unwrap();
10576
10577 // Activate workspace A
10578 multi_workspace_handle
10579 .update(cx, |mw, window, cx| {
10580 mw.activate_index(0, window, cx);
10581 })
10582 .unwrap();
10583
10584 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10585
10586 // Workspace A has a clean item
10587 let item_a = cx.new(TestItem::new);
10588 workspace_a.update_in(cx, |w, window, cx| {
10589 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10590 });
10591
10592 // Workspace B has a dirty item
10593 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10594 workspace_b.update_in(cx, |w, window, cx| {
10595 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10596 });
10597
10598 // Verify workspace A is active
10599 multi_workspace_handle
10600 .read_with(cx, |mw, _| {
10601 assert_eq!(mw.active_workspace_index(), 0);
10602 })
10603 .unwrap();
10604
10605 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10606 multi_workspace_handle
10607 .update(cx, |mw, window, cx| {
10608 mw.close_window(&CloseWindow, window, cx);
10609 })
10610 .unwrap();
10611 cx.run_until_parked();
10612
10613 // Workspace B should now be active since it has dirty items that need attention
10614 multi_workspace_handle
10615 .read_with(cx, |mw, _| {
10616 assert_eq!(
10617 mw.active_workspace_index(),
10618 1,
10619 "workspace B should be activated when it prompts"
10620 );
10621 })
10622 .unwrap();
10623
10624 // User cancels the save prompt from workspace B
10625 cx.simulate_prompt_answer("Cancel");
10626 cx.run_until_parked();
10627
10628 // Window should still exist because workspace B's close was cancelled
10629 assert!(
10630 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10631 "window should still exist after cancelling one workspace's close"
10632 );
10633 }
10634
10635 #[gpui::test]
10636 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10637 init_test(cx);
10638
10639 // Register TestItem as a serializable item
10640 cx.update(|cx| {
10641 register_serializable_item::<TestItem>(cx);
10642 });
10643
10644 let fs = FakeFs::new(cx.executor());
10645 fs.insert_tree("/root", json!({ "one": "" })).await;
10646
10647 let project = Project::test(fs, ["root".as_ref()], cx).await;
10648 let (workspace, cx) =
10649 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10650
10651 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10652 let item1 = cx.new(|cx| {
10653 TestItem::new(cx)
10654 .with_dirty(true)
10655 .with_serialize(|| Some(Task::ready(Ok(()))))
10656 });
10657 let item2 = cx.new(|cx| {
10658 TestItem::new(cx)
10659 .with_dirty(true)
10660 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10661 .with_serialize(|| Some(Task::ready(Ok(()))))
10662 });
10663 workspace.update_in(cx, |w, window, cx| {
10664 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10665 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10666 });
10667 let task = workspace.update_in(cx, |w, window, cx| {
10668 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10669 });
10670 assert!(task.await.unwrap());
10671 }
10672
10673 #[gpui::test]
10674 async fn test_close_pane_items(cx: &mut TestAppContext) {
10675 init_test(cx);
10676
10677 let fs = FakeFs::new(cx.executor());
10678
10679 let project = Project::test(fs, None, cx).await;
10680 let (workspace, cx) =
10681 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10682
10683 let item1 = cx.new(|cx| {
10684 TestItem::new(cx)
10685 .with_dirty(true)
10686 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10687 });
10688 let item2 = cx.new(|cx| {
10689 TestItem::new(cx)
10690 .with_dirty(true)
10691 .with_conflict(true)
10692 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10693 });
10694 let item3 = cx.new(|cx| {
10695 TestItem::new(cx)
10696 .with_dirty(true)
10697 .with_conflict(true)
10698 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10699 });
10700 let item4 = cx.new(|cx| {
10701 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10702 let project_item = TestProjectItem::new_untitled(cx);
10703 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10704 project_item
10705 }])
10706 });
10707 let pane = workspace.update_in(cx, |workspace, window, cx| {
10708 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10709 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10710 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10711 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10712 workspace.active_pane().clone()
10713 });
10714
10715 let close_items = pane.update_in(cx, |pane, window, cx| {
10716 pane.activate_item(1, true, true, window, cx);
10717 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10718 let item1_id = item1.item_id();
10719 let item3_id = item3.item_id();
10720 let item4_id = item4.item_id();
10721 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10722 [item1_id, item3_id, item4_id].contains(&id)
10723 })
10724 });
10725 cx.executor().run_until_parked();
10726
10727 assert!(cx.has_pending_prompt());
10728 cx.simulate_prompt_answer("Save all");
10729
10730 cx.executor().run_until_parked();
10731
10732 // Item 1 is saved. There's a prompt to save item 3.
10733 pane.update(cx, |pane, cx| {
10734 assert_eq!(item1.read(cx).save_count, 1);
10735 assert_eq!(item1.read(cx).save_as_count, 0);
10736 assert_eq!(item1.read(cx).reload_count, 0);
10737 assert_eq!(pane.items_len(), 3);
10738 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10739 });
10740 assert!(cx.has_pending_prompt());
10741
10742 // Cancel saving item 3.
10743 cx.simulate_prompt_answer("Discard");
10744 cx.executor().run_until_parked();
10745
10746 // Item 3 is reloaded. There's a prompt to save item 4.
10747 pane.update(cx, |pane, cx| {
10748 assert_eq!(item3.read(cx).save_count, 0);
10749 assert_eq!(item3.read(cx).save_as_count, 0);
10750 assert_eq!(item3.read(cx).reload_count, 1);
10751 assert_eq!(pane.items_len(), 2);
10752 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10753 });
10754
10755 // There's a prompt for a path for item 4.
10756 cx.simulate_new_path_selection(|_| Some(Default::default()));
10757 close_items.await.unwrap();
10758
10759 // The requested items are closed.
10760 pane.update(cx, |pane, cx| {
10761 assert_eq!(item4.read(cx).save_count, 0);
10762 assert_eq!(item4.read(cx).save_as_count, 1);
10763 assert_eq!(item4.read(cx).reload_count, 0);
10764 assert_eq!(pane.items_len(), 1);
10765 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10766 });
10767 }
10768
10769 #[gpui::test]
10770 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10771 init_test(cx);
10772
10773 let fs = FakeFs::new(cx.executor());
10774 let project = Project::test(fs, [], cx).await;
10775 let (workspace, cx) =
10776 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10777
10778 // Create several workspace items with single project entries, and two
10779 // workspace items with multiple project entries.
10780 let single_entry_items = (0..=4)
10781 .map(|project_entry_id| {
10782 cx.new(|cx| {
10783 TestItem::new(cx)
10784 .with_dirty(true)
10785 .with_project_items(&[dirty_project_item(
10786 project_entry_id,
10787 &format!("{project_entry_id}.txt"),
10788 cx,
10789 )])
10790 })
10791 })
10792 .collect::<Vec<_>>();
10793 let item_2_3 = cx.new(|cx| {
10794 TestItem::new(cx)
10795 .with_dirty(true)
10796 .with_buffer_kind(ItemBufferKind::Multibuffer)
10797 .with_project_items(&[
10798 single_entry_items[2].read(cx).project_items[0].clone(),
10799 single_entry_items[3].read(cx).project_items[0].clone(),
10800 ])
10801 });
10802 let item_3_4 = cx.new(|cx| {
10803 TestItem::new(cx)
10804 .with_dirty(true)
10805 .with_buffer_kind(ItemBufferKind::Multibuffer)
10806 .with_project_items(&[
10807 single_entry_items[3].read(cx).project_items[0].clone(),
10808 single_entry_items[4].read(cx).project_items[0].clone(),
10809 ])
10810 });
10811
10812 // Create two panes that contain the following project entries:
10813 // left pane:
10814 // multi-entry items: (2, 3)
10815 // single-entry items: 0, 2, 3, 4
10816 // right pane:
10817 // single-entry items: 4, 1
10818 // multi-entry items: (3, 4)
10819 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10820 let left_pane = workspace.active_pane().clone();
10821 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10822 workspace.add_item_to_active_pane(
10823 single_entry_items[0].boxed_clone(),
10824 None,
10825 true,
10826 window,
10827 cx,
10828 );
10829 workspace.add_item_to_active_pane(
10830 single_entry_items[2].boxed_clone(),
10831 None,
10832 true,
10833 window,
10834 cx,
10835 );
10836 workspace.add_item_to_active_pane(
10837 single_entry_items[3].boxed_clone(),
10838 None,
10839 true,
10840 window,
10841 cx,
10842 );
10843 workspace.add_item_to_active_pane(
10844 single_entry_items[4].boxed_clone(),
10845 None,
10846 true,
10847 window,
10848 cx,
10849 );
10850
10851 let right_pane =
10852 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10853
10854 let boxed_clone = single_entry_items[1].boxed_clone();
10855 let right_pane = window.spawn(cx, async move |cx| {
10856 right_pane.await.inspect(|right_pane| {
10857 right_pane
10858 .update_in(cx, |pane, window, cx| {
10859 pane.add_item(boxed_clone, true, true, None, window, cx);
10860 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10861 })
10862 .unwrap();
10863 })
10864 });
10865
10866 (left_pane, right_pane)
10867 });
10868 let right_pane = right_pane.await.unwrap();
10869 cx.focus(&right_pane);
10870
10871 let close = right_pane.update_in(cx, |pane, window, cx| {
10872 pane.close_all_items(&CloseAllItems::default(), window, cx)
10873 .unwrap()
10874 });
10875 cx.executor().run_until_parked();
10876
10877 let msg = cx.pending_prompt().unwrap().0;
10878 assert!(msg.contains("1.txt"));
10879 assert!(!msg.contains("2.txt"));
10880 assert!(!msg.contains("3.txt"));
10881 assert!(!msg.contains("4.txt"));
10882
10883 // With best-effort close, cancelling item 1 keeps it open but items 4
10884 // and (3,4) still close since their entries exist in left pane.
10885 cx.simulate_prompt_answer("Cancel");
10886 close.await;
10887
10888 right_pane.read_with(cx, |pane, _| {
10889 assert_eq!(pane.items_len(), 1);
10890 });
10891
10892 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10893 left_pane
10894 .update_in(cx, |left_pane, window, cx| {
10895 left_pane.close_item_by_id(
10896 single_entry_items[3].entity_id(),
10897 SaveIntent::Skip,
10898 window,
10899 cx,
10900 )
10901 })
10902 .await
10903 .unwrap();
10904
10905 let close = left_pane.update_in(cx, |pane, window, cx| {
10906 pane.close_all_items(&CloseAllItems::default(), window, cx)
10907 .unwrap()
10908 });
10909 cx.executor().run_until_parked();
10910
10911 let details = cx.pending_prompt().unwrap().1;
10912 assert!(details.contains("0.txt"));
10913 assert!(details.contains("3.txt"));
10914 assert!(details.contains("4.txt"));
10915 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10916 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10917 // assert!(!details.contains("2.txt"));
10918
10919 cx.simulate_prompt_answer("Save all");
10920 cx.executor().run_until_parked();
10921 close.await;
10922
10923 left_pane.read_with(cx, |pane, _| {
10924 assert_eq!(pane.items_len(), 0);
10925 });
10926 }
10927
10928 #[gpui::test]
10929 async fn test_autosave(cx: &mut gpui::TestAppContext) {
10930 init_test(cx);
10931
10932 let fs = FakeFs::new(cx.executor());
10933 let project = Project::test(fs, [], cx).await;
10934 let (workspace, cx) =
10935 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10936 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10937
10938 let item = cx.new(|cx| {
10939 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10940 });
10941 let item_id = item.entity_id();
10942 workspace.update_in(cx, |workspace, window, cx| {
10943 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10944 });
10945
10946 // Autosave on window change.
10947 item.update(cx, |item, cx| {
10948 SettingsStore::update_global(cx, |settings, cx| {
10949 settings.update_user_settings(cx, |settings| {
10950 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10951 })
10952 });
10953 item.is_dirty = true;
10954 });
10955
10956 // Deactivating the window saves the file.
10957 cx.deactivate_window();
10958 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10959
10960 // Re-activating the window doesn't save the file.
10961 cx.update(|window, _| window.activate_window());
10962 cx.executor().run_until_parked();
10963 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10964
10965 // Autosave on focus change.
10966 item.update_in(cx, |item, window, cx| {
10967 cx.focus_self(window);
10968 SettingsStore::update_global(cx, |settings, cx| {
10969 settings.update_user_settings(cx, |settings| {
10970 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10971 })
10972 });
10973 item.is_dirty = true;
10974 });
10975 // Blurring the item saves the file.
10976 item.update_in(cx, |_, window, _| window.blur());
10977 cx.executor().run_until_parked();
10978 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10979
10980 // Deactivating the window still saves the file.
10981 item.update_in(cx, |item, window, cx| {
10982 cx.focus_self(window);
10983 item.is_dirty = true;
10984 });
10985 cx.deactivate_window();
10986 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10987
10988 // Autosave after delay.
10989 item.update(cx, |item, cx| {
10990 SettingsStore::update_global(cx, |settings, cx| {
10991 settings.update_user_settings(cx, |settings| {
10992 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10993 milliseconds: 500.into(),
10994 });
10995 })
10996 });
10997 item.is_dirty = true;
10998 cx.emit(ItemEvent::Edit);
10999 });
11000
11001 // Delay hasn't fully expired, so the file is still dirty and unsaved.
11002 cx.executor().advance_clock(Duration::from_millis(250));
11003 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11004
11005 // After delay expires, the file is saved.
11006 cx.executor().advance_clock(Duration::from_millis(250));
11007 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11008
11009 // Autosave after delay, should save earlier than delay if tab is closed
11010 item.update(cx, |item, cx| {
11011 item.is_dirty = true;
11012 cx.emit(ItemEvent::Edit);
11013 });
11014 cx.executor().advance_clock(Duration::from_millis(250));
11015 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11016
11017 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11018 pane.update_in(cx, |pane, window, cx| {
11019 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11020 })
11021 .await
11022 .unwrap();
11023 assert!(!cx.has_pending_prompt());
11024 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11025
11026 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11027 workspace.update_in(cx, |workspace, window, cx| {
11028 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11029 });
11030 item.update_in(cx, |item, _window, cx| {
11031 item.is_dirty = true;
11032 for project_item in &mut item.project_items {
11033 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11034 }
11035 });
11036 cx.run_until_parked();
11037 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11038
11039 // Autosave on focus change, ensuring closing the tab counts as such.
11040 item.update(cx, |item, cx| {
11041 SettingsStore::update_global(cx, |settings, cx| {
11042 settings.update_user_settings(cx, |settings| {
11043 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11044 })
11045 });
11046 item.is_dirty = true;
11047 for project_item in &mut item.project_items {
11048 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11049 }
11050 });
11051
11052 pane.update_in(cx, |pane, window, cx| {
11053 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11054 })
11055 .await
11056 .unwrap();
11057 assert!(!cx.has_pending_prompt());
11058 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11059
11060 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11061 workspace.update_in(cx, |workspace, window, cx| {
11062 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11063 });
11064 item.update_in(cx, |item, window, cx| {
11065 item.project_items[0].update(cx, |item, _| {
11066 item.entry_id = None;
11067 });
11068 item.is_dirty = true;
11069 window.blur();
11070 });
11071 cx.run_until_parked();
11072 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11073
11074 // Ensure autosave is prevented for deleted files also when closing the buffer.
11075 let _close_items = pane.update_in(cx, |pane, window, cx| {
11076 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11077 });
11078 cx.run_until_parked();
11079 assert!(cx.has_pending_prompt());
11080 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11081 }
11082
11083 #[gpui::test]
11084 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11085 init_test(cx);
11086
11087 let fs = FakeFs::new(cx.executor());
11088 let project = Project::test(fs, [], cx).await;
11089 let (workspace, cx) =
11090 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11091
11092 // Create a multibuffer-like item with two child focus handles,
11093 // simulating individual buffer editors within a multibuffer.
11094 let item = cx.new(|cx| {
11095 TestItem::new(cx)
11096 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11097 .with_child_focus_handles(2, cx)
11098 });
11099 workspace.update_in(cx, |workspace, window, cx| {
11100 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11101 });
11102
11103 // Set autosave to OnFocusChange and focus the first child handle,
11104 // simulating the user's cursor being inside one of the multibuffer's excerpts.
11105 item.update_in(cx, |item, window, cx| {
11106 SettingsStore::update_global(cx, |settings, cx| {
11107 settings.update_user_settings(cx, |settings| {
11108 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11109 })
11110 });
11111 item.is_dirty = true;
11112 window.focus(&item.child_focus_handles[0], cx);
11113 });
11114 cx.executor().run_until_parked();
11115 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11116
11117 // Moving focus from one child to another within the same item should
11118 // NOT trigger autosave — focus is still within the item's focus hierarchy.
11119 item.update_in(cx, |item, window, cx| {
11120 window.focus(&item.child_focus_handles[1], cx);
11121 });
11122 cx.executor().run_until_parked();
11123 item.read_with(cx, |item, _| {
11124 assert_eq!(
11125 item.save_count, 0,
11126 "Switching focus between children within the same item should not autosave"
11127 );
11128 });
11129
11130 // Blurring the item saves the file. This is the core regression scenario:
11131 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11132 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11133 // the leaf is always a child focus handle, so `on_blur` never detected
11134 // focus leaving the item.
11135 item.update_in(cx, |_, window, _| window.blur());
11136 cx.executor().run_until_parked();
11137 item.read_with(cx, |item, _| {
11138 assert_eq!(
11139 item.save_count, 1,
11140 "Blurring should trigger autosave when focus was on a child of the item"
11141 );
11142 });
11143
11144 // Deactivating the window should also trigger autosave when a child of
11145 // the multibuffer item currently owns focus.
11146 item.update_in(cx, |item, window, cx| {
11147 item.is_dirty = true;
11148 window.focus(&item.child_focus_handles[0], cx);
11149 });
11150 cx.executor().run_until_parked();
11151 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11152
11153 cx.deactivate_window();
11154 item.read_with(cx, |item, _| {
11155 assert_eq!(
11156 item.save_count, 2,
11157 "Deactivating window should trigger autosave when focus was on a child"
11158 );
11159 });
11160 }
11161
11162 #[gpui::test]
11163 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11164 init_test(cx);
11165
11166 let fs = FakeFs::new(cx.executor());
11167
11168 let project = Project::test(fs, [], cx).await;
11169 let (workspace, cx) =
11170 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11171
11172 let item = cx.new(|cx| {
11173 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11174 });
11175 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11176 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11177 let toolbar_notify_count = Rc::new(RefCell::new(0));
11178
11179 workspace.update_in(cx, |workspace, window, cx| {
11180 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11181 let toolbar_notification_count = toolbar_notify_count.clone();
11182 cx.observe_in(&toolbar, window, move |_, _, _, _| {
11183 *toolbar_notification_count.borrow_mut() += 1
11184 })
11185 .detach();
11186 });
11187
11188 pane.read_with(cx, |pane, _| {
11189 assert!(!pane.can_navigate_backward());
11190 assert!(!pane.can_navigate_forward());
11191 });
11192
11193 item.update_in(cx, |item, _, cx| {
11194 item.set_state("one".to_string(), cx);
11195 });
11196
11197 // Toolbar must be notified to re-render the navigation buttons
11198 assert_eq!(*toolbar_notify_count.borrow(), 1);
11199
11200 pane.read_with(cx, |pane, _| {
11201 assert!(pane.can_navigate_backward());
11202 assert!(!pane.can_navigate_forward());
11203 });
11204
11205 workspace
11206 .update_in(cx, |workspace, window, cx| {
11207 workspace.go_back(pane.downgrade(), window, cx)
11208 })
11209 .await
11210 .unwrap();
11211
11212 assert_eq!(*toolbar_notify_count.borrow(), 2);
11213 pane.read_with(cx, |pane, _| {
11214 assert!(!pane.can_navigate_backward());
11215 assert!(pane.can_navigate_forward());
11216 });
11217 }
11218
11219 /// Tests that the navigation history deduplicates entries for the same item.
11220 ///
11221 /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11222 /// the navigation history deduplicates by keeping only the most recent visit to each item,
11223 /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11224 /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11225 /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11226 ///
11227 /// This behavior prevents the navigation history from growing unnecessarily large and provides
11228 /// a better user experience by eliminating redundant navigation steps when jumping between files.
11229 #[gpui::test]
11230 async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11231 init_test(cx);
11232
11233 let fs = FakeFs::new(cx.executor());
11234 let project = Project::test(fs, [], cx).await;
11235 let (workspace, cx) =
11236 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11237
11238 let item_a = cx.new(|cx| {
11239 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11240 });
11241 let item_b = cx.new(|cx| {
11242 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11243 });
11244 let item_c = cx.new(|cx| {
11245 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11246 });
11247
11248 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11249
11250 workspace.update_in(cx, |workspace, window, cx| {
11251 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11252 workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11253 workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11254 });
11255
11256 workspace.update_in(cx, |workspace, window, cx| {
11257 workspace.activate_item(&item_a, false, false, window, cx);
11258 });
11259 cx.run_until_parked();
11260
11261 workspace.update_in(cx, |workspace, window, cx| {
11262 workspace.activate_item(&item_b, false, false, window, cx);
11263 });
11264 cx.run_until_parked();
11265
11266 workspace.update_in(cx, |workspace, window, cx| {
11267 workspace.activate_item(&item_a, false, false, window, cx);
11268 });
11269 cx.run_until_parked();
11270
11271 workspace.update_in(cx, |workspace, window, cx| {
11272 workspace.activate_item(&item_b, false, false, window, cx);
11273 });
11274 cx.run_until_parked();
11275
11276 workspace.update_in(cx, |workspace, window, cx| {
11277 workspace.activate_item(&item_a, false, false, window, cx);
11278 });
11279 cx.run_until_parked();
11280
11281 workspace.update_in(cx, |workspace, window, cx| {
11282 workspace.activate_item(&item_b, false, false, window, cx);
11283 });
11284 cx.run_until_parked();
11285
11286 workspace.update_in(cx, |workspace, window, cx| {
11287 workspace.activate_item(&item_c, false, false, window, cx);
11288 });
11289 cx.run_until_parked();
11290
11291 let backward_count = pane.read_with(cx, |pane, cx| {
11292 let mut count = 0;
11293 pane.nav_history().for_each_entry(cx, &mut |_, _| {
11294 count += 1;
11295 });
11296 count
11297 });
11298 assert!(
11299 backward_count <= 4,
11300 "Should have at most 4 entries, got {}",
11301 backward_count
11302 );
11303
11304 workspace
11305 .update_in(cx, |workspace, window, cx| {
11306 workspace.go_back(pane.downgrade(), window, cx)
11307 })
11308 .await
11309 .unwrap();
11310
11311 let active_item = workspace.read_with(cx, |workspace, cx| {
11312 workspace.active_item(cx).unwrap().item_id()
11313 });
11314 assert_eq!(
11315 active_item,
11316 item_b.entity_id(),
11317 "After first go_back, should be at item B"
11318 );
11319
11320 workspace
11321 .update_in(cx, |workspace, window, cx| {
11322 workspace.go_back(pane.downgrade(), window, cx)
11323 })
11324 .await
11325 .unwrap();
11326
11327 let active_item = workspace.read_with(cx, |workspace, cx| {
11328 workspace.active_item(cx).unwrap().item_id()
11329 });
11330 assert_eq!(
11331 active_item,
11332 item_a.entity_id(),
11333 "After second go_back, should be at item A"
11334 );
11335
11336 pane.read_with(cx, |pane, _| {
11337 assert!(pane.can_navigate_forward(), "Should be able to go forward");
11338 });
11339 }
11340
11341 #[gpui::test]
11342 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11343 init_test(cx);
11344 let fs = FakeFs::new(cx.executor());
11345 let project = Project::test(fs, [], cx).await;
11346 let (multi_workspace, cx) =
11347 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11348 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11349
11350 workspace.update_in(cx, |workspace, window, cx| {
11351 let first_item = cx.new(|cx| {
11352 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11353 });
11354 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11355 workspace.split_pane(
11356 workspace.active_pane().clone(),
11357 SplitDirection::Right,
11358 window,
11359 cx,
11360 );
11361 workspace.split_pane(
11362 workspace.active_pane().clone(),
11363 SplitDirection::Right,
11364 window,
11365 cx,
11366 );
11367 });
11368
11369 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11370 let panes = workspace.center.panes();
11371 assert!(panes.len() >= 2);
11372 (
11373 panes.first().expect("at least one pane").entity_id(),
11374 panes.last().expect("at least one pane").entity_id(),
11375 )
11376 });
11377
11378 workspace.update_in(cx, |workspace, window, cx| {
11379 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11380 });
11381 workspace.update(cx, |workspace, _| {
11382 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11383 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11384 });
11385
11386 cx.dispatch_action(ActivateLastPane);
11387
11388 workspace.update(cx, |workspace, _| {
11389 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11390 });
11391 }
11392
11393 #[gpui::test]
11394 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11395 init_test(cx);
11396 let fs = FakeFs::new(cx.executor());
11397
11398 let project = Project::test(fs, [], cx).await;
11399 let (workspace, cx) =
11400 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11401
11402 let panel = workspace.update_in(cx, |workspace, window, cx| {
11403 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11404 workspace.add_panel(panel.clone(), window, cx);
11405
11406 workspace
11407 .right_dock()
11408 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11409
11410 panel
11411 });
11412
11413 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11414 pane.update_in(cx, |pane, window, cx| {
11415 let item = cx.new(TestItem::new);
11416 pane.add_item(Box::new(item), true, true, None, window, cx);
11417 });
11418
11419 // Transfer focus from center to panel
11420 workspace.update_in(cx, |workspace, window, cx| {
11421 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11422 });
11423
11424 workspace.update_in(cx, |workspace, window, cx| {
11425 assert!(workspace.right_dock().read(cx).is_open());
11426 assert!(!panel.is_zoomed(window, cx));
11427 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11428 });
11429
11430 // Transfer focus from panel to center
11431 workspace.update_in(cx, |workspace, window, cx| {
11432 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11433 });
11434
11435 workspace.update_in(cx, |workspace, window, cx| {
11436 assert!(workspace.right_dock().read(cx).is_open());
11437 assert!(!panel.is_zoomed(window, cx));
11438 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11439 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11440 });
11441
11442 // Close the dock
11443 workspace.update_in(cx, |workspace, window, cx| {
11444 workspace.toggle_dock(DockPosition::Right, window, cx);
11445 });
11446
11447 workspace.update_in(cx, |workspace, window, cx| {
11448 assert!(!workspace.right_dock().read(cx).is_open());
11449 assert!(!panel.is_zoomed(window, cx));
11450 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11451 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11452 });
11453
11454 // Open the dock
11455 workspace.update_in(cx, |workspace, window, cx| {
11456 workspace.toggle_dock(DockPosition::Right, window, cx);
11457 });
11458
11459 workspace.update_in(cx, |workspace, window, cx| {
11460 assert!(workspace.right_dock().read(cx).is_open());
11461 assert!(!panel.is_zoomed(window, cx));
11462 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11463 });
11464
11465 // Focus and zoom panel
11466 panel.update_in(cx, |panel, window, cx| {
11467 cx.focus_self(window);
11468 panel.set_zoomed(true, window, cx)
11469 });
11470
11471 workspace.update_in(cx, |workspace, window, cx| {
11472 assert!(workspace.right_dock().read(cx).is_open());
11473 assert!(panel.is_zoomed(window, cx));
11474 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11475 });
11476
11477 // Transfer focus to the center closes the dock
11478 workspace.update_in(cx, |workspace, window, cx| {
11479 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11480 });
11481
11482 workspace.update_in(cx, |workspace, window, cx| {
11483 assert!(!workspace.right_dock().read(cx).is_open());
11484 assert!(panel.is_zoomed(window, cx));
11485 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11486 });
11487
11488 // Transferring focus back to the panel keeps it zoomed
11489 workspace.update_in(cx, |workspace, window, cx| {
11490 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11491 });
11492
11493 workspace.update_in(cx, |workspace, window, cx| {
11494 assert!(workspace.right_dock().read(cx).is_open());
11495 assert!(panel.is_zoomed(window, cx));
11496 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11497 });
11498
11499 // Close the dock while it is zoomed
11500 workspace.update_in(cx, |workspace, window, cx| {
11501 workspace.toggle_dock(DockPosition::Right, window, cx)
11502 });
11503
11504 workspace.update_in(cx, |workspace, window, cx| {
11505 assert!(!workspace.right_dock().read(cx).is_open());
11506 assert!(panel.is_zoomed(window, cx));
11507 assert!(workspace.zoomed.is_none());
11508 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11509 });
11510
11511 // Opening the dock, when it's zoomed, retains focus
11512 workspace.update_in(cx, |workspace, window, cx| {
11513 workspace.toggle_dock(DockPosition::Right, window, cx)
11514 });
11515
11516 workspace.update_in(cx, |workspace, window, cx| {
11517 assert!(workspace.right_dock().read(cx).is_open());
11518 assert!(panel.is_zoomed(window, cx));
11519 assert!(workspace.zoomed.is_some());
11520 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11521 });
11522
11523 // Unzoom and close the panel, zoom the active pane.
11524 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11525 workspace.update_in(cx, |workspace, window, cx| {
11526 workspace.toggle_dock(DockPosition::Right, window, cx)
11527 });
11528 pane.update_in(cx, |pane, window, cx| {
11529 pane.toggle_zoom(&Default::default(), window, cx)
11530 });
11531
11532 // Opening a dock unzooms the pane.
11533 workspace.update_in(cx, |workspace, window, cx| {
11534 workspace.toggle_dock(DockPosition::Right, window, cx)
11535 });
11536 workspace.update_in(cx, |workspace, window, cx| {
11537 let pane = pane.read(cx);
11538 assert!(!pane.is_zoomed());
11539 assert!(!pane.focus_handle(cx).is_focused(window));
11540 assert!(workspace.right_dock().read(cx).is_open());
11541 assert!(workspace.zoomed.is_none());
11542 });
11543 }
11544
11545 #[gpui::test]
11546 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11547 init_test(cx);
11548 let fs = FakeFs::new(cx.executor());
11549
11550 let project = Project::test(fs, [], cx).await;
11551 let (workspace, cx) =
11552 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11553
11554 let panel = workspace.update_in(cx, |workspace, window, cx| {
11555 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11556 workspace.add_panel(panel.clone(), window, cx);
11557 panel
11558 });
11559
11560 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11561 pane.update_in(cx, |pane, window, cx| {
11562 let item = cx.new(TestItem::new);
11563 pane.add_item(Box::new(item), true, true, None, window, cx);
11564 });
11565
11566 // Enable close_panel_on_toggle
11567 cx.update_global(|store: &mut SettingsStore, cx| {
11568 store.update_user_settings(cx, |settings| {
11569 settings.workspace.close_panel_on_toggle = Some(true);
11570 });
11571 });
11572
11573 // Panel starts closed. Toggling should open and focus it.
11574 workspace.update_in(cx, |workspace, window, cx| {
11575 assert!(!workspace.right_dock().read(cx).is_open());
11576 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11577 });
11578
11579 workspace.update_in(cx, |workspace, window, cx| {
11580 assert!(
11581 workspace.right_dock().read(cx).is_open(),
11582 "Dock should be open after toggling from center"
11583 );
11584 assert!(
11585 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11586 "Panel should be focused after toggling from center"
11587 );
11588 });
11589
11590 // Panel is open and focused. Toggling should close the panel and
11591 // return focus to the center.
11592 workspace.update_in(cx, |workspace, window, cx| {
11593 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11594 });
11595
11596 workspace.update_in(cx, |workspace, window, cx| {
11597 assert!(
11598 !workspace.right_dock().read(cx).is_open(),
11599 "Dock should be closed after toggling from focused panel"
11600 );
11601 assert!(
11602 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11603 "Panel should not be focused after toggling from focused panel"
11604 );
11605 });
11606
11607 // Open the dock and focus something else so the panel is open but not
11608 // focused. Toggling should focus the panel (not close it).
11609 workspace.update_in(cx, |workspace, window, cx| {
11610 workspace
11611 .right_dock()
11612 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11613 window.focus(&pane.read(cx).focus_handle(cx), cx);
11614 });
11615
11616 workspace.update_in(cx, |workspace, window, cx| {
11617 assert!(workspace.right_dock().read(cx).is_open());
11618 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11619 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11620 });
11621
11622 workspace.update_in(cx, |workspace, window, cx| {
11623 assert!(
11624 workspace.right_dock().read(cx).is_open(),
11625 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11626 );
11627 assert!(
11628 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11629 "Panel should be focused after toggling an open-but-unfocused panel"
11630 );
11631 });
11632
11633 // Now disable the setting and verify the original behavior: toggling
11634 // from a focused panel moves focus to center but leaves the dock open.
11635 cx.update_global(|store: &mut SettingsStore, cx| {
11636 store.update_user_settings(cx, |settings| {
11637 settings.workspace.close_panel_on_toggle = Some(false);
11638 });
11639 });
11640
11641 workspace.update_in(cx, |workspace, window, cx| {
11642 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11643 });
11644
11645 workspace.update_in(cx, |workspace, window, cx| {
11646 assert!(
11647 workspace.right_dock().read(cx).is_open(),
11648 "Dock should remain open when setting is disabled"
11649 );
11650 assert!(
11651 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11652 "Panel should not be focused after toggling with setting disabled"
11653 );
11654 });
11655 }
11656
11657 #[gpui::test]
11658 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11659 init_test(cx);
11660 let fs = FakeFs::new(cx.executor());
11661
11662 let project = Project::test(fs, [], cx).await;
11663 let (workspace, cx) =
11664 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11665
11666 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11667 workspace.active_pane().clone()
11668 });
11669
11670 // Add an item to the pane so it can be zoomed
11671 workspace.update_in(cx, |workspace, window, cx| {
11672 let item = cx.new(TestItem::new);
11673 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11674 });
11675
11676 // Initially not zoomed
11677 workspace.update_in(cx, |workspace, _window, cx| {
11678 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11679 assert!(
11680 workspace.zoomed.is_none(),
11681 "Workspace should track no zoomed pane"
11682 );
11683 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11684 });
11685
11686 // Zoom In
11687 pane.update_in(cx, |pane, window, cx| {
11688 pane.zoom_in(&crate::ZoomIn, window, cx);
11689 });
11690
11691 workspace.update_in(cx, |workspace, window, cx| {
11692 assert!(
11693 pane.read(cx).is_zoomed(),
11694 "Pane should be zoomed after ZoomIn"
11695 );
11696 assert!(
11697 workspace.zoomed.is_some(),
11698 "Workspace should track the zoomed pane"
11699 );
11700 assert!(
11701 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11702 "ZoomIn should focus the pane"
11703 );
11704 });
11705
11706 // Zoom In again is a no-op
11707 pane.update_in(cx, |pane, window, cx| {
11708 pane.zoom_in(&crate::ZoomIn, window, cx);
11709 });
11710
11711 workspace.update_in(cx, |workspace, window, cx| {
11712 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11713 assert!(
11714 workspace.zoomed.is_some(),
11715 "Workspace still tracks zoomed pane"
11716 );
11717 assert!(
11718 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11719 "Pane remains focused after repeated ZoomIn"
11720 );
11721 });
11722
11723 // Zoom Out
11724 pane.update_in(cx, |pane, window, cx| {
11725 pane.zoom_out(&crate::ZoomOut, window, cx);
11726 });
11727
11728 workspace.update_in(cx, |workspace, _window, cx| {
11729 assert!(
11730 !pane.read(cx).is_zoomed(),
11731 "Pane should unzoom after ZoomOut"
11732 );
11733 assert!(
11734 workspace.zoomed.is_none(),
11735 "Workspace clears zoom tracking after ZoomOut"
11736 );
11737 });
11738
11739 // Zoom Out again is a no-op
11740 pane.update_in(cx, |pane, window, cx| {
11741 pane.zoom_out(&crate::ZoomOut, window, cx);
11742 });
11743
11744 workspace.update_in(cx, |workspace, _window, cx| {
11745 assert!(
11746 !pane.read(cx).is_zoomed(),
11747 "Second ZoomOut keeps pane unzoomed"
11748 );
11749 assert!(
11750 workspace.zoomed.is_none(),
11751 "Workspace remains without zoomed pane"
11752 );
11753 });
11754 }
11755
11756 #[gpui::test]
11757 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11758 init_test(cx);
11759 let fs = FakeFs::new(cx.executor());
11760
11761 let project = Project::test(fs, [], cx).await;
11762 let (workspace, cx) =
11763 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11764 workspace.update_in(cx, |workspace, window, cx| {
11765 // Open two docks
11766 let left_dock = workspace.dock_at_position(DockPosition::Left);
11767 let right_dock = workspace.dock_at_position(DockPosition::Right);
11768
11769 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11770 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11771
11772 assert!(left_dock.read(cx).is_open());
11773 assert!(right_dock.read(cx).is_open());
11774 });
11775
11776 workspace.update_in(cx, |workspace, window, cx| {
11777 // Toggle all docks - should close both
11778 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11779
11780 let left_dock = workspace.dock_at_position(DockPosition::Left);
11781 let right_dock = workspace.dock_at_position(DockPosition::Right);
11782 assert!(!left_dock.read(cx).is_open());
11783 assert!(!right_dock.read(cx).is_open());
11784 });
11785
11786 workspace.update_in(cx, |workspace, window, cx| {
11787 // Toggle again - should reopen both
11788 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11789
11790 let left_dock = workspace.dock_at_position(DockPosition::Left);
11791 let right_dock = workspace.dock_at_position(DockPosition::Right);
11792 assert!(left_dock.read(cx).is_open());
11793 assert!(right_dock.read(cx).is_open());
11794 });
11795 }
11796
11797 #[gpui::test]
11798 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11799 init_test(cx);
11800 let fs = FakeFs::new(cx.executor());
11801
11802 let project = Project::test(fs, [], cx).await;
11803 let (workspace, cx) =
11804 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11805 workspace.update_in(cx, |workspace, window, cx| {
11806 // Open two docks
11807 let left_dock = workspace.dock_at_position(DockPosition::Left);
11808 let right_dock = workspace.dock_at_position(DockPosition::Right);
11809
11810 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11811 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11812
11813 assert!(left_dock.read(cx).is_open());
11814 assert!(right_dock.read(cx).is_open());
11815 });
11816
11817 workspace.update_in(cx, |workspace, window, cx| {
11818 // Close them manually
11819 workspace.toggle_dock(DockPosition::Left, window, cx);
11820 workspace.toggle_dock(DockPosition::Right, window, cx);
11821
11822 let left_dock = workspace.dock_at_position(DockPosition::Left);
11823 let right_dock = workspace.dock_at_position(DockPosition::Right);
11824 assert!(!left_dock.read(cx).is_open());
11825 assert!(!right_dock.read(cx).is_open());
11826 });
11827
11828 workspace.update_in(cx, |workspace, window, cx| {
11829 // Toggle all docks - only last closed (right dock) should reopen
11830 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11831
11832 let left_dock = workspace.dock_at_position(DockPosition::Left);
11833 let right_dock = workspace.dock_at_position(DockPosition::Right);
11834 assert!(!left_dock.read(cx).is_open());
11835 assert!(right_dock.read(cx).is_open());
11836 });
11837 }
11838
11839 #[gpui::test]
11840 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11841 init_test(cx);
11842 let fs = FakeFs::new(cx.executor());
11843 let project = Project::test(fs, [], cx).await;
11844 let (multi_workspace, cx) =
11845 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11846 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11847
11848 // Open two docks (left and right) with one panel each
11849 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11850 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11851 workspace.add_panel(left_panel.clone(), window, cx);
11852
11853 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11854 workspace.add_panel(right_panel.clone(), window, cx);
11855
11856 workspace.toggle_dock(DockPosition::Left, window, cx);
11857 workspace.toggle_dock(DockPosition::Right, window, cx);
11858
11859 // Verify initial state
11860 assert!(
11861 workspace.left_dock().read(cx).is_open(),
11862 "Left dock should be open"
11863 );
11864 assert_eq!(
11865 workspace
11866 .left_dock()
11867 .read(cx)
11868 .visible_panel()
11869 .unwrap()
11870 .panel_id(),
11871 left_panel.panel_id(),
11872 "Left panel should be visible in left dock"
11873 );
11874 assert!(
11875 workspace.right_dock().read(cx).is_open(),
11876 "Right dock should be open"
11877 );
11878 assert_eq!(
11879 workspace
11880 .right_dock()
11881 .read(cx)
11882 .visible_panel()
11883 .unwrap()
11884 .panel_id(),
11885 right_panel.panel_id(),
11886 "Right panel should be visible in right dock"
11887 );
11888 assert!(
11889 !workspace.bottom_dock().read(cx).is_open(),
11890 "Bottom dock should be closed"
11891 );
11892
11893 (left_panel, right_panel)
11894 });
11895
11896 // Focus the left panel and move it to the next position (bottom dock)
11897 workspace.update_in(cx, |workspace, window, cx| {
11898 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11899 assert!(
11900 left_panel.read(cx).focus_handle(cx).is_focused(window),
11901 "Left panel should be focused"
11902 );
11903 });
11904
11905 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11906
11907 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11908 workspace.update(cx, |workspace, cx| {
11909 assert!(
11910 !workspace.left_dock().read(cx).is_open(),
11911 "Left dock should be closed"
11912 );
11913 assert!(
11914 workspace.bottom_dock().read(cx).is_open(),
11915 "Bottom dock should now be open"
11916 );
11917 assert_eq!(
11918 left_panel.read(cx).position,
11919 DockPosition::Bottom,
11920 "Left panel should now be in the bottom dock"
11921 );
11922 assert_eq!(
11923 workspace
11924 .bottom_dock()
11925 .read(cx)
11926 .visible_panel()
11927 .unwrap()
11928 .panel_id(),
11929 left_panel.panel_id(),
11930 "Left panel should be the visible panel in the bottom dock"
11931 );
11932 });
11933
11934 // Toggle all docks off
11935 workspace.update_in(cx, |workspace, window, cx| {
11936 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11937 assert!(
11938 !workspace.left_dock().read(cx).is_open(),
11939 "Left dock should be closed"
11940 );
11941 assert!(
11942 !workspace.right_dock().read(cx).is_open(),
11943 "Right dock should be closed"
11944 );
11945 assert!(
11946 !workspace.bottom_dock().read(cx).is_open(),
11947 "Bottom dock should be closed"
11948 );
11949 });
11950
11951 // Toggle all docks back on and verify positions are restored
11952 workspace.update_in(cx, |workspace, window, cx| {
11953 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11954 assert!(
11955 !workspace.left_dock().read(cx).is_open(),
11956 "Left dock should remain closed"
11957 );
11958 assert!(
11959 workspace.right_dock().read(cx).is_open(),
11960 "Right dock should remain open"
11961 );
11962 assert!(
11963 workspace.bottom_dock().read(cx).is_open(),
11964 "Bottom dock should remain open"
11965 );
11966 assert_eq!(
11967 left_panel.read(cx).position,
11968 DockPosition::Bottom,
11969 "Left panel should remain in the bottom dock"
11970 );
11971 assert_eq!(
11972 right_panel.read(cx).position,
11973 DockPosition::Right,
11974 "Right panel should remain in the right dock"
11975 );
11976 assert_eq!(
11977 workspace
11978 .bottom_dock()
11979 .read(cx)
11980 .visible_panel()
11981 .unwrap()
11982 .panel_id(),
11983 left_panel.panel_id(),
11984 "Left panel should be the visible panel in the right dock"
11985 );
11986 });
11987 }
11988
11989 #[gpui::test]
11990 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11991 init_test(cx);
11992
11993 let fs = FakeFs::new(cx.executor());
11994
11995 let project = Project::test(fs, None, cx).await;
11996 let (workspace, cx) =
11997 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11998
11999 // Let's arrange the panes like this:
12000 //
12001 // +-----------------------+
12002 // | top |
12003 // +------+--------+-------+
12004 // | left | center | right |
12005 // +------+--------+-------+
12006 // | bottom |
12007 // +-----------------------+
12008
12009 let top_item = cx.new(|cx| {
12010 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12011 });
12012 let bottom_item = cx.new(|cx| {
12013 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12014 });
12015 let left_item = cx.new(|cx| {
12016 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12017 });
12018 let right_item = cx.new(|cx| {
12019 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12020 });
12021 let center_item = cx.new(|cx| {
12022 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12023 });
12024
12025 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12026 let top_pane_id = workspace.active_pane().entity_id();
12027 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12028 workspace.split_pane(
12029 workspace.active_pane().clone(),
12030 SplitDirection::Down,
12031 window,
12032 cx,
12033 );
12034 top_pane_id
12035 });
12036 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12037 let bottom_pane_id = workspace.active_pane().entity_id();
12038 workspace.add_item_to_active_pane(
12039 Box::new(bottom_item.clone()),
12040 None,
12041 false,
12042 window,
12043 cx,
12044 );
12045 workspace.split_pane(
12046 workspace.active_pane().clone(),
12047 SplitDirection::Up,
12048 window,
12049 cx,
12050 );
12051 bottom_pane_id
12052 });
12053 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12054 let left_pane_id = workspace.active_pane().entity_id();
12055 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12056 workspace.split_pane(
12057 workspace.active_pane().clone(),
12058 SplitDirection::Right,
12059 window,
12060 cx,
12061 );
12062 left_pane_id
12063 });
12064 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12065 let right_pane_id = workspace.active_pane().entity_id();
12066 workspace.add_item_to_active_pane(
12067 Box::new(right_item.clone()),
12068 None,
12069 false,
12070 window,
12071 cx,
12072 );
12073 workspace.split_pane(
12074 workspace.active_pane().clone(),
12075 SplitDirection::Left,
12076 window,
12077 cx,
12078 );
12079 right_pane_id
12080 });
12081 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12082 let center_pane_id = workspace.active_pane().entity_id();
12083 workspace.add_item_to_active_pane(
12084 Box::new(center_item.clone()),
12085 None,
12086 false,
12087 window,
12088 cx,
12089 );
12090 center_pane_id
12091 });
12092 cx.executor().run_until_parked();
12093
12094 workspace.update_in(cx, |workspace, window, cx| {
12095 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12096
12097 // Join into next from center pane into right
12098 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12099 });
12100
12101 workspace.update_in(cx, |workspace, window, cx| {
12102 let active_pane = workspace.active_pane();
12103 assert_eq!(right_pane_id, active_pane.entity_id());
12104 assert_eq!(2, active_pane.read(cx).items_len());
12105 let item_ids_in_pane =
12106 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12107 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12108 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12109
12110 // Join into next from right pane into bottom
12111 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12112 });
12113
12114 workspace.update_in(cx, |workspace, window, cx| {
12115 let active_pane = workspace.active_pane();
12116 assert_eq!(bottom_pane_id, active_pane.entity_id());
12117 assert_eq!(3, active_pane.read(cx).items_len());
12118 let item_ids_in_pane =
12119 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12120 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12121 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12122 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12123
12124 // Join into next from bottom pane into left
12125 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12126 });
12127
12128 workspace.update_in(cx, |workspace, window, cx| {
12129 let active_pane = workspace.active_pane();
12130 assert_eq!(left_pane_id, active_pane.entity_id());
12131 assert_eq!(4, active_pane.read(cx).items_len());
12132 let item_ids_in_pane =
12133 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12134 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12135 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12136 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12137 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12138
12139 // Join into next from left pane into top
12140 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12141 });
12142
12143 workspace.update_in(cx, |workspace, window, cx| {
12144 let active_pane = workspace.active_pane();
12145 assert_eq!(top_pane_id, active_pane.entity_id());
12146 assert_eq!(5, active_pane.read(cx).items_len());
12147 let item_ids_in_pane =
12148 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12149 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12150 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12151 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12152 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12153 assert!(item_ids_in_pane.contains(&top_item.item_id()));
12154
12155 // Single pane left: no-op
12156 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12157 });
12158
12159 workspace.update(cx, |workspace, _cx| {
12160 let active_pane = workspace.active_pane();
12161 assert_eq!(top_pane_id, active_pane.entity_id());
12162 });
12163 }
12164
12165 fn add_an_item_to_active_pane(
12166 cx: &mut VisualTestContext,
12167 workspace: &Entity<Workspace>,
12168 item_id: u64,
12169 ) -> Entity<TestItem> {
12170 let item = cx.new(|cx| {
12171 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12172 item_id,
12173 "item{item_id}.txt",
12174 cx,
12175 )])
12176 });
12177 workspace.update_in(cx, |workspace, window, cx| {
12178 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12179 });
12180 item
12181 }
12182
12183 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12184 workspace.update_in(cx, |workspace, window, cx| {
12185 workspace.split_pane(
12186 workspace.active_pane().clone(),
12187 SplitDirection::Right,
12188 window,
12189 cx,
12190 )
12191 })
12192 }
12193
12194 #[gpui::test]
12195 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12196 init_test(cx);
12197 let fs = FakeFs::new(cx.executor());
12198 let project = Project::test(fs, None, cx).await;
12199 let (workspace, cx) =
12200 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12201
12202 add_an_item_to_active_pane(cx, &workspace, 1);
12203 split_pane(cx, &workspace);
12204 add_an_item_to_active_pane(cx, &workspace, 2);
12205 split_pane(cx, &workspace); // empty pane
12206 split_pane(cx, &workspace);
12207 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12208
12209 cx.executor().run_until_parked();
12210
12211 workspace.update(cx, |workspace, cx| {
12212 let num_panes = workspace.panes().len();
12213 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12214 let active_item = workspace
12215 .active_pane()
12216 .read(cx)
12217 .active_item()
12218 .expect("item is in focus");
12219
12220 assert_eq!(num_panes, 4);
12221 assert_eq!(num_items_in_current_pane, 1);
12222 assert_eq!(active_item.item_id(), last_item.item_id());
12223 });
12224
12225 workspace.update_in(cx, |workspace, window, cx| {
12226 workspace.join_all_panes(window, cx);
12227 });
12228
12229 workspace.update(cx, |workspace, cx| {
12230 let num_panes = workspace.panes().len();
12231 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12232 let active_item = workspace
12233 .active_pane()
12234 .read(cx)
12235 .active_item()
12236 .expect("item is in focus");
12237
12238 assert_eq!(num_panes, 1);
12239 assert_eq!(num_items_in_current_pane, 3);
12240 assert_eq!(active_item.item_id(), last_item.item_id());
12241 });
12242 }
12243
12244 #[gpui::test]
12245 async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12246 init_test(cx);
12247 let fs = FakeFs::new(cx.executor());
12248
12249 let project = Project::test(fs, [], cx).await;
12250 let (multi_workspace, cx) =
12251 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12252 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12253
12254 workspace.update(cx, |workspace, _cx| {
12255 workspace.bounds.size.width = px(800.);
12256 });
12257
12258 workspace.update_in(cx, |workspace, window, cx| {
12259 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12260 workspace.add_panel(panel, window, cx);
12261 workspace.toggle_dock(DockPosition::Right, window, cx);
12262 });
12263
12264 let (panel, resized_width, ratio_basis_width) =
12265 workspace.update_in(cx, |workspace, window, cx| {
12266 let item = cx.new(|cx| {
12267 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12268 });
12269 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12270
12271 let dock = workspace.right_dock().read(cx);
12272 let workspace_width = workspace.bounds.size.width;
12273 let initial_width = dock
12274 .active_panel()
12275 .map(|panel| {
12276 workspace.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx)
12277 })
12278 .expect("flexible dock should have an initial width");
12279
12280 assert_eq!(initial_width, workspace_width / 2.);
12281
12282 workspace.resize_right_dock(px(300.), window, cx);
12283
12284 let dock = workspace.right_dock().read(cx);
12285 let resized_width = dock
12286 .active_panel()
12287 .map(|panel| {
12288 workspace.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx)
12289 })
12290 .expect("flexible dock should keep its resized width");
12291
12292 assert_eq!(resized_width, px(300.));
12293
12294 let panel = workspace
12295 .right_dock()
12296 .read(cx)
12297 .visible_panel()
12298 .expect("flexible dock should have a visible panel")
12299 .panel_id();
12300
12301 (panel, resized_width, workspace_width)
12302 });
12303
12304 workspace.update_in(cx, |workspace, window, cx| {
12305 workspace.toggle_dock(DockPosition::Right, window, cx);
12306 workspace.toggle_dock(DockPosition::Right, window, cx);
12307
12308 let dock = workspace.right_dock().read(cx);
12309 let reopened_width = dock
12310 .active_panel()
12311 .map(|panel| workspace.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx))
12312 .expect("flexible dock should restore when reopened");
12313
12314 assert_eq!(reopened_width, resized_width);
12315
12316 let right_dock = workspace.right_dock().read(cx);
12317 let flexible_panel = right_dock
12318 .visible_panel()
12319 .expect("flexible dock should still have a visible panel");
12320 assert_eq!(flexible_panel.panel_id(), panel);
12321 assert_eq!(
12322 right_dock
12323 .stored_panel_size_state(flexible_panel.as_ref())
12324 .and_then(|size_state| size_state.flexible_size_ratio),
12325 Some(resized_width.to_f64() as f32 / workspace.bounds.size.width.to_f64() as f32)
12326 );
12327 });
12328
12329 workspace.update_in(cx, |workspace, window, cx| {
12330 workspace.split_pane(
12331 workspace.active_pane().clone(),
12332 SplitDirection::Right,
12333 window,
12334 cx,
12335 );
12336
12337 let dock = workspace.right_dock().read(cx);
12338 let split_width = dock
12339 .active_panel()
12340 .map(|panel| workspace.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx))
12341 .expect("flexible dock should keep its user-resized proportion");
12342
12343 assert_eq!(split_width, px(300.));
12344
12345 workspace.bounds.size.width = px(1600.);
12346
12347 let dock = workspace.right_dock().read(cx);
12348 let resized_window_width = dock
12349 .active_panel()
12350 .map(|panel| workspace.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx))
12351 .expect("flexible dock should preserve proportional size on window resize");
12352
12353 assert_eq!(
12354 resized_window_width,
12355 workspace.bounds.size.width
12356 * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12357 );
12358 });
12359 }
12360
12361 #[gpui::test]
12362 async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12363 init_test(cx);
12364 let fs = FakeFs::new(cx.executor());
12365
12366 // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12367 {
12368 let project = Project::test(fs.clone(), [], cx).await;
12369 let (multi_workspace, cx) =
12370 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12371 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12372
12373 workspace.update(cx, |workspace, _cx| {
12374 workspace.set_random_database_id();
12375 workspace.bounds.size.width = px(800.);
12376 });
12377
12378 let panel = workspace.update_in(cx, |workspace, window, cx| {
12379 let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12380 workspace.add_panel(panel.clone(), window, cx);
12381 workspace.toggle_dock(DockPosition::Left, window, cx);
12382 panel
12383 });
12384
12385 workspace.update_in(cx, |workspace, window, cx| {
12386 workspace.resize_left_dock(px(350.), window, cx);
12387 });
12388
12389 cx.run_until_parked();
12390
12391 let persisted = workspace.read_with(cx, |workspace, cx| {
12392 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12393 });
12394 assert_eq!(
12395 persisted.and_then(|s| s.size),
12396 Some(px(350.)),
12397 "fixed-width panel size should be persisted to KVP"
12398 );
12399
12400 // Remove the panel and re-add a fresh instance with the same key.
12401 // The new instance should have its size state restored from KVP.
12402 workspace.update_in(cx, |workspace, window, cx| {
12403 workspace.remove_panel(&panel, window, cx);
12404 });
12405
12406 workspace.update_in(cx, |workspace, window, cx| {
12407 let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12408 workspace.add_panel(new_panel, window, cx);
12409
12410 let left_dock = workspace.left_dock().read(cx);
12411 let size_state = left_dock
12412 .panel::<TestPanel>()
12413 .and_then(|p| left_dock.stored_panel_size_state(&p));
12414 assert_eq!(
12415 size_state.and_then(|s| s.size),
12416 Some(px(350.)),
12417 "re-added fixed-width panel should restore persisted size from KVP"
12418 );
12419 });
12420 }
12421
12422 // Flexible panel: both pixel size and ratio are persisted and restored.
12423 {
12424 let project = Project::test(fs.clone(), [], cx).await;
12425 let (multi_workspace, cx) =
12426 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12427 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12428
12429 workspace.update(cx, |workspace, _cx| {
12430 workspace.set_random_database_id();
12431 workspace.bounds.size.width = px(800.);
12432 });
12433
12434 let panel = workspace.update_in(cx, |workspace, window, cx| {
12435 let item = cx.new(|cx| {
12436 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12437 });
12438 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12439
12440 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12441 workspace.add_panel(panel.clone(), window, cx);
12442 workspace.toggle_dock(DockPosition::Right, window, cx);
12443 panel
12444 });
12445
12446 workspace.update_in(cx, |workspace, window, cx| {
12447 workspace.resize_right_dock(px(300.), window, cx);
12448 });
12449
12450 cx.run_until_parked();
12451
12452 let persisted = workspace
12453 .read_with(cx, |workspace, cx| {
12454 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12455 })
12456 .expect("flexible panel state should be persisted to KVP");
12457 assert_eq!(
12458 persisted.size, None,
12459 "flexible panel should not persist a redundant pixel size"
12460 );
12461 let original_ratio = persisted
12462 .flexible_size_ratio
12463 .expect("flexible panel ratio should be persisted");
12464
12465 // Remove the panel and re-add: both size and ratio should be restored.
12466 workspace.update_in(cx, |workspace, window, cx| {
12467 workspace.remove_panel(&panel, window, cx);
12468 });
12469
12470 workspace.update_in(cx, |workspace, window, cx| {
12471 let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12472 workspace.add_panel(new_panel, window, cx);
12473
12474 let right_dock = workspace.right_dock().read(cx);
12475 let size_state = right_dock
12476 .panel::<TestPanel>()
12477 .and_then(|p| right_dock.stored_panel_size_state(&p))
12478 .expect("re-added flexible panel should have restored size state from KVP");
12479 assert_eq!(
12480 size_state.size, None,
12481 "re-added flexible panel should not have a persisted pixel size"
12482 );
12483 assert_eq!(
12484 size_state.flexible_size_ratio,
12485 Some(original_ratio),
12486 "re-added flexible panel should restore persisted ratio"
12487 );
12488 });
12489 }
12490 }
12491
12492 #[gpui::test]
12493 async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12494 init_test(cx);
12495 let fs = FakeFs::new(cx.executor());
12496
12497 let project = Project::test(fs, [], cx).await;
12498 let (multi_workspace, cx) =
12499 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12500 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12501
12502 workspace.update(cx, |workspace, _cx| {
12503 workspace.bounds.size.width = px(900.);
12504 });
12505
12506 // Step 1: Add a tab to the center pane then open a flexible panel in the left
12507 // dock. With one full-width center pane the default ratio is 0.5, so the panel
12508 // and the center pane each take half the workspace width.
12509 workspace.update_in(cx, |workspace, window, cx| {
12510 let item = cx.new(|cx| {
12511 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12512 });
12513 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12514
12515 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12516 workspace.add_panel(panel, window, cx);
12517 workspace.toggle_dock(DockPosition::Left, window, cx);
12518
12519 let left_dock = workspace.left_dock().read(cx);
12520 let left_width = left_dock
12521 .active_panel()
12522 .map(|p| workspace.resolved_dock_panel_size(&left_dock, p.as_ref(), window, cx))
12523 .expect("left dock should have an active panel");
12524
12525 assert_eq!(
12526 left_width,
12527 workspace.bounds.size.width / 2.,
12528 "flexible left panel should split evenly with the center pane"
12529 );
12530 });
12531
12532 // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12533 // change horizontal width fractions, so the flexible panel stays at the same
12534 // width as each half of the split.
12535 workspace.update_in(cx, |workspace, window, cx| {
12536 workspace.split_pane(
12537 workspace.active_pane().clone(),
12538 SplitDirection::Down,
12539 window,
12540 cx,
12541 );
12542
12543 let left_dock = workspace.left_dock().read(cx);
12544 let left_width = left_dock
12545 .active_panel()
12546 .map(|p| workspace.resolved_dock_panel_size(&left_dock, p.as_ref(), window, cx))
12547 .expect("left dock should still have an active panel after vertical split");
12548
12549 assert_eq!(
12550 left_width,
12551 workspace.bounds.size.width / 2.,
12552 "flexible left panel width should match each vertically-split pane"
12553 );
12554 });
12555
12556 // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12557 // size reduces the available width, so the flexible left panel and the center
12558 // panes all shrink proportionally to accommodate it.
12559 workspace.update_in(cx, |workspace, window, cx| {
12560 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12561 workspace.add_panel(panel, window, cx);
12562 workspace.toggle_dock(DockPosition::Right, window, cx);
12563
12564 let right_dock = workspace.right_dock().read(cx);
12565 let right_width = right_dock
12566 .active_panel()
12567 .map(|p| workspace.resolved_dock_panel_size(&right_dock, p.as_ref(), window, cx))
12568 .expect("right dock should have an active panel");
12569
12570 let left_dock = workspace.left_dock().read(cx);
12571 let left_width = left_dock
12572 .active_panel()
12573 .map(|p| workspace.resolved_dock_panel_size(&left_dock, p.as_ref(), window, cx))
12574 .expect("left dock should still have an active panel");
12575
12576 let available_width = workspace.bounds.size.width - right_width;
12577 assert_eq!(
12578 left_width,
12579 available_width / 2.,
12580 "flexible left panel should shrink proportionally as the right dock takes space"
12581 );
12582 });
12583 }
12584
12585 struct TestModal(FocusHandle);
12586
12587 impl TestModal {
12588 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12589 Self(cx.focus_handle())
12590 }
12591 }
12592
12593 impl EventEmitter<DismissEvent> for TestModal {}
12594
12595 impl Focusable for TestModal {
12596 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12597 self.0.clone()
12598 }
12599 }
12600
12601 impl ModalView for TestModal {}
12602
12603 impl Render for TestModal {
12604 fn render(
12605 &mut self,
12606 _window: &mut Window,
12607 _cx: &mut Context<TestModal>,
12608 ) -> impl IntoElement {
12609 div().track_focus(&self.0)
12610 }
12611 }
12612
12613 #[gpui::test]
12614 async fn test_panels(cx: &mut gpui::TestAppContext) {
12615 init_test(cx);
12616 let fs = FakeFs::new(cx.executor());
12617
12618 let project = Project::test(fs, [], cx).await;
12619 let (multi_workspace, cx) =
12620 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12621 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12622
12623 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12624 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12625 workspace.add_panel(panel_1.clone(), window, cx);
12626 workspace.toggle_dock(DockPosition::Left, window, cx);
12627 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12628 workspace.add_panel(panel_2.clone(), window, cx);
12629 workspace.toggle_dock(DockPosition::Right, window, cx);
12630
12631 let left_dock = workspace.left_dock();
12632 assert_eq!(
12633 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12634 panel_1.panel_id()
12635 );
12636 assert_eq!(
12637 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
12638 px(300.)
12639 );
12640
12641 workspace.resize_left_dock(px(1337.), window, cx);
12642 assert_eq!(
12643 workspace
12644 .right_dock()
12645 .read(cx)
12646 .visible_panel()
12647 .unwrap()
12648 .panel_id(),
12649 panel_2.panel_id(),
12650 );
12651
12652 (panel_1, panel_2)
12653 });
12654
12655 // Move panel_1 to the right
12656 panel_1.update_in(cx, |panel_1, window, cx| {
12657 panel_1.set_position(DockPosition::Right, window, cx)
12658 });
12659
12660 workspace.update_in(cx, |workspace, window, cx| {
12661 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12662 // Since it was the only panel on the left, the left dock should now be closed.
12663 assert!(!workspace.left_dock().read(cx).is_open());
12664 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12665 let right_dock = workspace.right_dock();
12666 assert_eq!(
12667 right_dock.read(cx).visible_panel().unwrap().panel_id(),
12668 panel_1.panel_id()
12669 );
12670 assert_eq!(
12671 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
12672 px(1337.)
12673 );
12674
12675 // Now we move panel_2 to the left
12676 panel_2.set_position(DockPosition::Left, window, cx);
12677 });
12678
12679 workspace.update(cx, |workspace, cx| {
12680 // Since panel_2 was not visible on the right, we don't open the left dock.
12681 assert!(!workspace.left_dock().read(cx).is_open());
12682 // And the right dock is unaffected in its displaying of panel_1
12683 assert!(workspace.right_dock().read(cx).is_open());
12684 assert_eq!(
12685 workspace
12686 .right_dock()
12687 .read(cx)
12688 .visible_panel()
12689 .unwrap()
12690 .panel_id(),
12691 panel_1.panel_id(),
12692 );
12693 });
12694
12695 // Move panel_1 back to the left
12696 panel_1.update_in(cx, |panel_1, window, cx| {
12697 panel_1.set_position(DockPosition::Left, window, cx)
12698 });
12699
12700 workspace.update_in(cx, |workspace, window, cx| {
12701 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12702 let left_dock = workspace.left_dock();
12703 assert!(left_dock.read(cx).is_open());
12704 assert_eq!(
12705 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12706 panel_1.panel_id()
12707 );
12708 assert_eq!(
12709 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
12710 px(1337.)
12711 );
12712 // And the right dock should be closed as it no longer has any panels.
12713 assert!(!workspace.right_dock().read(cx).is_open());
12714
12715 // Now we move panel_1 to the bottom
12716 panel_1.set_position(DockPosition::Bottom, window, cx);
12717 });
12718
12719 workspace.update_in(cx, |workspace, window, cx| {
12720 // Since panel_1 was visible on the left, we close the left dock.
12721 assert!(!workspace.left_dock().read(cx).is_open());
12722 // The bottom dock is sized based on the panel's default size,
12723 // since the panel orientation changed from vertical to horizontal.
12724 let bottom_dock = workspace.bottom_dock();
12725 assert_eq!(
12726 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
12727 px(300.),
12728 );
12729 // Close bottom dock and move panel_1 back to the left.
12730 bottom_dock.update(cx, |bottom_dock, cx| {
12731 bottom_dock.set_open(false, window, cx)
12732 });
12733 panel_1.set_position(DockPosition::Left, window, cx);
12734 });
12735
12736 // Emit activated event on panel 1
12737 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12738
12739 // Now the left dock is open and panel_1 is active and focused.
12740 workspace.update_in(cx, |workspace, window, cx| {
12741 let left_dock = workspace.left_dock();
12742 assert!(left_dock.read(cx).is_open());
12743 assert_eq!(
12744 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12745 panel_1.panel_id(),
12746 );
12747 assert!(panel_1.focus_handle(cx).is_focused(window));
12748 });
12749
12750 // Emit closed event on panel 2, which is not active
12751 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12752
12753 // Wo don't close the left dock, because panel_2 wasn't the active panel
12754 workspace.update(cx, |workspace, cx| {
12755 let left_dock = workspace.left_dock();
12756 assert!(left_dock.read(cx).is_open());
12757 assert_eq!(
12758 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12759 panel_1.panel_id(),
12760 );
12761 });
12762
12763 // Emitting a ZoomIn event shows the panel as zoomed.
12764 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12765 workspace.read_with(cx, |workspace, _| {
12766 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12767 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12768 });
12769
12770 // Move panel to another dock while it is zoomed
12771 panel_1.update_in(cx, |panel, window, cx| {
12772 panel.set_position(DockPosition::Right, window, cx)
12773 });
12774 workspace.read_with(cx, |workspace, _| {
12775 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12776
12777 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12778 });
12779
12780 // This is a helper for getting a:
12781 // - valid focus on an element,
12782 // - that isn't a part of the panes and panels system of the Workspace,
12783 // - and doesn't trigger the 'on_focus_lost' API.
12784 let focus_other_view = {
12785 let workspace = workspace.clone();
12786 move |cx: &mut VisualTestContext| {
12787 workspace.update_in(cx, |workspace, window, cx| {
12788 if workspace.active_modal::<TestModal>(cx).is_some() {
12789 workspace.toggle_modal(window, cx, TestModal::new);
12790 workspace.toggle_modal(window, cx, TestModal::new);
12791 } else {
12792 workspace.toggle_modal(window, cx, TestModal::new);
12793 }
12794 })
12795 }
12796 };
12797
12798 // If focus is transferred to another view that's not a panel or another pane, we still show
12799 // the panel as zoomed.
12800 focus_other_view(cx);
12801 workspace.read_with(cx, |workspace, _| {
12802 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12803 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12804 });
12805
12806 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12807 workspace.update_in(cx, |_workspace, window, cx| {
12808 cx.focus_self(window);
12809 });
12810 workspace.read_with(cx, |workspace, _| {
12811 assert_eq!(workspace.zoomed, None);
12812 assert_eq!(workspace.zoomed_position, None);
12813 });
12814
12815 // If focus is transferred again to another view that's not a panel or a pane, we won't
12816 // show the panel as zoomed because it wasn't zoomed before.
12817 focus_other_view(cx);
12818 workspace.read_with(cx, |workspace, _| {
12819 assert_eq!(workspace.zoomed, None);
12820 assert_eq!(workspace.zoomed_position, None);
12821 });
12822
12823 // When the panel is activated, it is zoomed again.
12824 cx.dispatch_action(ToggleRightDock);
12825 workspace.read_with(cx, |workspace, _| {
12826 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12827 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12828 });
12829
12830 // Emitting a ZoomOut event unzooms the panel.
12831 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12832 workspace.read_with(cx, |workspace, _| {
12833 assert_eq!(workspace.zoomed, None);
12834 assert_eq!(workspace.zoomed_position, None);
12835 });
12836
12837 // Emit closed event on panel 1, which is active
12838 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12839
12840 // Now the left dock is closed, because panel_1 was the active panel
12841 workspace.update(cx, |workspace, cx| {
12842 let right_dock = workspace.right_dock();
12843 assert!(!right_dock.read(cx).is_open());
12844 });
12845 }
12846
12847 #[gpui::test]
12848 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12849 init_test(cx);
12850
12851 let fs = FakeFs::new(cx.background_executor.clone());
12852 let project = Project::test(fs, [], cx).await;
12853 let (workspace, cx) =
12854 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12855 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12856
12857 let dirty_regular_buffer = cx.new(|cx| {
12858 TestItem::new(cx)
12859 .with_dirty(true)
12860 .with_label("1.txt")
12861 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12862 });
12863 let dirty_regular_buffer_2 = cx.new(|cx| {
12864 TestItem::new(cx)
12865 .with_dirty(true)
12866 .with_label("2.txt")
12867 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12868 });
12869 let dirty_multi_buffer_with_both = cx.new(|cx| {
12870 TestItem::new(cx)
12871 .with_dirty(true)
12872 .with_buffer_kind(ItemBufferKind::Multibuffer)
12873 .with_label("Fake Project Search")
12874 .with_project_items(&[
12875 dirty_regular_buffer.read(cx).project_items[0].clone(),
12876 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12877 ])
12878 });
12879 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12880 workspace.update_in(cx, |workspace, window, cx| {
12881 workspace.add_item(
12882 pane.clone(),
12883 Box::new(dirty_regular_buffer.clone()),
12884 None,
12885 false,
12886 false,
12887 window,
12888 cx,
12889 );
12890 workspace.add_item(
12891 pane.clone(),
12892 Box::new(dirty_regular_buffer_2.clone()),
12893 None,
12894 false,
12895 false,
12896 window,
12897 cx,
12898 );
12899 workspace.add_item(
12900 pane.clone(),
12901 Box::new(dirty_multi_buffer_with_both.clone()),
12902 None,
12903 false,
12904 false,
12905 window,
12906 cx,
12907 );
12908 });
12909
12910 pane.update_in(cx, |pane, window, cx| {
12911 pane.activate_item(2, true, true, window, cx);
12912 assert_eq!(
12913 pane.active_item().unwrap().item_id(),
12914 multi_buffer_with_both_files_id,
12915 "Should select the multi buffer in the pane"
12916 );
12917 });
12918 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12919 pane.close_other_items(
12920 &CloseOtherItems {
12921 save_intent: Some(SaveIntent::Save),
12922 close_pinned: true,
12923 },
12924 None,
12925 window,
12926 cx,
12927 )
12928 });
12929 cx.background_executor.run_until_parked();
12930 assert!(!cx.has_pending_prompt());
12931 close_all_but_multi_buffer_task
12932 .await
12933 .expect("Closing all buffers but the multi buffer failed");
12934 pane.update(cx, |pane, cx| {
12935 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12936 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12937 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12938 assert_eq!(pane.items_len(), 1);
12939 assert_eq!(
12940 pane.active_item().unwrap().item_id(),
12941 multi_buffer_with_both_files_id,
12942 "Should have only the multi buffer left in the pane"
12943 );
12944 assert!(
12945 dirty_multi_buffer_with_both.read(cx).is_dirty,
12946 "The multi buffer containing the unsaved buffer should still be dirty"
12947 );
12948 });
12949
12950 dirty_regular_buffer.update(cx, |buffer, cx| {
12951 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12952 });
12953
12954 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12955 pane.close_active_item(
12956 &CloseActiveItem {
12957 save_intent: Some(SaveIntent::Close),
12958 close_pinned: false,
12959 },
12960 window,
12961 cx,
12962 )
12963 });
12964 cx.background_executor.run_until_parked();
12965 assert!(
12966 cx.has_pending_prompt(),
12967 "Dirty multi buffer should prompt a save dialog"
12968 );
12969 cx.simulate_prompt_answer("Save");
12970 cx.background_executor.run_until_parked();
12971 close_multi_buffer_task
12972 .await
12973 .expect("Closing the multi buffer failed");
12974 pane.update(cx, |pane, cx| {
12975 assert_eq!(
12976 dirty_multi_buffer_with_both.read(cx).save_count,
12977 1,
12978 "Multi buffer item should get be saved"
12979 );
12980 // Test impl does not save inner items, so we do not assert them
12981 assert_eq!(
12982 pane.items_len(),
12983 0,
12984 "No more items should be left in the pane"
12985 );
12986 assert!(pane.active_item().is_none());
12987 });
12988 }
12989
12990 #[gpui::test]
12991 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
12992 cx: &mut TestAppContext,
12993 ) {
12994 init_test(cx);
12995
12996 let fs = FakeFs::new(cx.background_executor.clone());
12997 let project = Project::test(fs, [], cx).await;
12998 let (workspace, cx) =
12999 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13000 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13001
13002 let dirty_regular_buffer = cx.new(|cx| {
13003 TestItem::new(cx)
13004 .with_dirty(true)
13005 .with_label("1.txt")
13006 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13007 });
13008 let dirty_regular_buffer_2 = cx.new(|cx| {
13009 TestItem::new(cx)
13010 .with_dirty(true)
13011 .with_label("2.txt")
13012 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13013 });
13014 let clear_regular_buffer = cx.new(|cx| {
13015 TestItem::new(cx)
13016 .with_label("3.txt")
13017 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13018 });
13019
13020 let dirty_multi_buffer_with_both = cx.new(|cx| {
13021 TestItem::new(cx)
13022 .with_dirty(true)
13023 .with_buffer_kind(ItemBufferKind::Multibuffer)
13024 .with_label("Fake Project Search")
13025 .with_project_items(&[
13026 dirty_regular_buffer.read(cx).project_items[0].clone(),
13027 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13028 clear_regular_buffer.read(cx).project_items[0].clone(),
13029 ])
13030 });
13031 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13032 workspace.update_in(cx, |workspace, window, cx| {
13033 workspace.add_item(
13034 pane.clone(),
13035 Box::new(dirty_regular_buffer.clone()),
13036 None,
13037 false,
13038 false,
13039 window,
13040 cx,
13041 );
13042 workspace.add_item(
13043 pane.clone(),
13044 Box::new(dirty_multi_buffer_with_both.clone()),
13045 None,
13046 false,
13047 false,
13048 window,
13049 cx,
13050 );
13051 });
13052
13053 pane.update_in(cx, |pane, window, cx| {
13054 pane.activate_item(1, true, true, window, cx);
13055 assert_eq!(
13056 pane.active_item().unwrap().item_id(),
13057 multi_buffer_with_both_files_id,
13058 "Should select the multi buffer in the pane"
13059 );
13060 });
13061 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13062 pane.close_active_item(
13063 &CloseActiveItem {
13064 save_intent: None,
13065 close_pinned: false,
13066 },
13067 window,
13068 cx,
13069 )
13070 });
13071 cx.background_executor.run_until_parked();
13072 assert!(
13073 cx.has_pending_prompt(),
13074 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13075 );
13076 }
13077
13078 /// Tests that when `close_on_file_delete` is enabled, files are automatically
13079 /// closed when they are deleted from disk.
13080 #[gpui::test]
13081 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13082 init_test(cx);
13083
13084 // Enable the close_on_disk_deletion setting
13085 cx.update_global(|store: &mut SettingsStore, cx| {
13086 store.update_user_settings(cx, |settings| {
13087 settings.workspace.close_on_file_delete = Some(true);
13088 });
13089 });
13090
13091 let fs = FakeFs::new(cx.background_executor.clone());
13092 let project = Project::test(fs, [], cx).await;
13093 let (workspace, cx) =
13094 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13095 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13096
13097 // Create a test item that simulates a file
13098 let item = cx.new(|cx| {
13099 TestItem::new(cx)
13100 .with_label("test.txt")
13101 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13102 });
13103
13104 // Add item to workspace
13105 workspace.update_in(cx, |workspace, window, cx| {
13106 workspace.add_item(
13107 pane.clone(),
13108 Box::new(item.clone()),
13109 None,
13110 false,
13111 false,
13112 window,
13113 cx,
13114 );
13115 });
13116
13117 // Verify the item is in the pane
13118 pane.read_with(cx, |pane, _| {
13119 assert_eq!(pane.items().count(), 1);
13120 });
13121
13122 // Simulate file deletion by setting the item's deleted state
13123 item.update(cx, |item, _| {
13124 item.set_has_deleted_file(true);
13125 });
13126
13127 // Emit UpdateTab event to trigger the close behavior
13128 cx.run_until_parked();
13129 item.update(cx, |_, cx| {
13130 cx.emit(ItemEvent::UpdateTab);
13131 });
13132
13133 // Allow the close operation to complete
13134 cx.run_until_parked();
13135
13136 // Verify the item was automatically closed
13137 pane.read_with(cx, |pane, _| {
13138 assert_eq!(
13139 pane.items().count(),
13140 0,
13141 "Item should be automatically closed when file is deleted"
13142 );
13143 });
13144 }
13145
13146 /// Tests that when `close_on_file_delete` is disabled (default), files remain
13147 /// open with a strikethrough when they are deleted from disk.
13148 #[gpui::test]
13149 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13150 init_test(cx);
13151
13152 // Ensure close_on_disk_deletion is disabled (default)
13153 cx.update_global(|store: &mut SettingsStore, cx| {
13154 store.update_user_settings(cx, |settings| {
13155 settings.workspace.close_on_file_delete = Some(false);
13156 });
13157 });
13158
13159 let fs = FakeFs::new(cx.background_executor.clone());
13160 let project = Project::test(fs, [], cx).await;
13161 let (workspace, cx) =
13162 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13163 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13164
13165 // Create a test item that simulates a file
13166 let item = cx.new(|cx| {
13167 TestItem::new(cx)
13168 .with_label("test.txt")
13169 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13170 });
13171
13172 // Add item to workspace
13173 workspace.update_in(cx, |workspace, window, cx| {
13174 workspace.add_item(
13175 pane.clone(),
13176 Box::new(item.clone()),
13177 None,
13178 false,
13179 false,
13180 window,
13181 cx,
13182 );
13183 });
13184
13185 // Verify the item is in the pane
13186 pane.read_with(cx, |pane, _| {
13187 assert_eq!(pane.items().count(), 1);
13188 });
13189
13190 // Simulate file deletion
13191 item.update(cx, |item, _| {
13192 item.set_has_deleted_file(true);
13193 });
13194
13195 // Emit UpdateTab event
13196 cx.run_until_parked();
13197 item.update(cx, |_, cx| {
13198 cx.emit(ItemEvent::UpdateTab);
13199 });
13200
13201 // Allow any potential close operation to complete
13202 cx.run_until_parked();
13203
13204 // Verify the item remains open (with strikethrough)
13205 pane.read_with(cx, |pane, _| {
13206 assert_eq!(
13207 pane.items().count(),
13208 1,
13209 "Item should remain open when close_on_disk_deletion is disabled"
13210 );
13211 });
13212
13213 // Verify the item shows as deleted
13214 item.read_with(cx, |item, _| {
13215 assert!(
13216 item.has_deleted_file,
13217 "Item should be marked as having deleted file"
13218 );
13219 });
13220 }
13221
13222 /// Tests that dirty files are not automatically closed when deleted from disk,
13223 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13224 /// unsaved changes without being prompted.
13225 #[gpui::test]
13226 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13227 init_test(cx);
13228
13229 // Enable the close_on_file_delete setting
13230 cx.update_global(|store: &mut SettingsStore, cx| {
13231 store.update_user_settings(cx, |settings| {
13232 settings.workspace.close_on_file_delete = Some(true);
13233 });
13234 });
13235
13236 let fs = FakeFs::new(cx.background_executor.clone());
13237 let project = Project::test(fs, [], cx).await;
13238 let (workspace, cx) =
13239 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13240 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13241
13242 // Create a dirty test item
13243 let item = cx.new(|cx| {
13244 TestItem::new(cx)
13245 .with_dirty(true)
13246 .with_label("test.txt")
13247 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13248 });
13249
13250 // Add item to workspace
13251 workspace.update_in(cx, |workspace, window, cx| {
13252 workspace.add_item(
13253 pane.clone(),
13254 Box::new(item.clone()),
13255 None,
13256 false,
13257 false,
13258 window,
13259 cx,
13260 );
13261 });
13262
13263 // Simulate file deletion
13264 item.update(cx, |item, _| {
13265 item.set_has_deleted_file(true);
13266 });
13267
13268 // Emit UpdateTab event to trigger the close behavior
13269 cx.run_until_parked();
13270 item.update(cx, |_, cx| {
13271 cx.emit(ItemEvent::UpdateTab);
13272 });
13273
13274 // Allow any potential close operation to complete
13275 cx.run_until_parked();
13276
13277 // Verify the item remains open (dirty files are not auto-closed)
13278 pane.read_with(cx, |pane, _| {
13279 assert_eq!(
13280 pane.items().count(),
13281 1,
13282 "Dirty items should not be automatically closed even when file is deleted"
13283 );
13284 });
13285
13286 // Verify the item is marked as deleted and still dirty
13287 item.read_with(cx, |item, _| {
13288 assert!(
13289 item.has_deleted_file,
13290 "Item should be marked as having deleted file"
13291 );
13292 assert!(item.is_dirty, "Item should still be dirty");
13293 });
13294 }
13295
13296 /// Tests that navigation history is cleaned up when files are auto-closed
13297 /// due to deletion from disk.
13298 #[gpui::test]
13299 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13300 init_test(cx);
13301
13302 // Enable the close_on_file_delete setting
13303 cx.update_global(|store: &mut SettingsStore, cx| {
13304 store.update_user_settings(cx, |settings| {
13305 settings.workspace.close_on_file_delete = Some(true);
13306 });
13307 });
13308
13309 let fs = FakeFs::new(cx.background_executor.clone());
13310 let project = Project::test(fs, [], cx).await;
13311 let (workspace, cx) =
13312 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13313 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13314
13315 // Create test items
13316 let item1 = cx.new(|cx| {
13317 TestItem::new(cx)
13318 .with_label("test1.txt")
13319 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13320 });
13321 let item1_id = item1.item_id();
13322
13323 let item2 = cx.new(|cx| {
13324 TestItem::new(cx)
13325 .with_label("test2.txt")
13326 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13327 });
13328
13329 // Add items to workspace
13330 workspace.update_in(cx, |workspace, window, cx| {
13331 workspace.add_item(
13332 pane.clone(),
13333 Box::new(item1.clone()),
13334 None,
13335 false,
13336 false,
13337 window,
13338 cx,
13339 );
13340 workspace.add_item(
13341 pane.clone(),
13342 Box::new(item2.clone()),
13343 None,
13344 false,
13345 false,
13346 window,
13347 cx,
13348 );
13349 });
13350
13351 // Activate item1 to ensure it gets navigation entries
13352 pane.update_in(cx, |pane, window, cx| {
13353 pane.activate_item(0, true, true, window, cx);
13354 });
13355
13356 // Switch to item2 and back to create navigation history
13357 pane.update_in(cx, |pane, window, cx| {
13358 pane.activate_item(1, true, true, window, cx);
13359 });
13360 cx.run_until_parked();
13361
13362 pane.update_in(cx, |pane, window, cx| {
13363 pane.activate_item(0, true, true, window, cx);
13364 });
13365 cx.run_until_parked();
13366
13367 // Simulate file deletion for item1
13368 item1.update(cx, |item, _| {
13369 item.set_has_deleted_file(true);
13370 });
13371
13372 // Emit UpdateTab event to trigger the close behavior
13373 item1.update(cx, |_, cx| {
13374 cx.emit(ItemEvent::UpdateTab);
13375 });
13376 cx.run_until_parked();
13377
13378 // Verify item1 was closed
13379 pane.read_with(cx, |pane, _| {
13380 assert_eq!(
13381 pane.items().count(),
13382 1,
13383 "Should have 1 item remaining after auto-close"
13384 );
13385 });
13386
13387 // Check navigation history after close
13388 let has_item = pane.read_with(cx, |pane, cx| {
13389 let mut has_item = false;
13390 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13391 if entry.item.id() == item1_id {
13392 has_item = true;
13393 }
13394 });
13395 has_item
13396 });
13397
13398 assert!(
13399 !has_item,
13400 "Navigation history should not contain closed item entries"
13401 );
13402 }
13403
13404 #[gpui::test]
13405 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13406 cx: &mut TestAppContext,
13407 ) {
13408 init_test(cx);
13409
13410 let fs = FakeFs::new(cx.background_executor.clone());
13411 let project = Project::test(fs, [], cx).await;
13412 let (workspace, cx) =
13413 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13414 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13415
13416 let dirty_regular_buffer = cx.new(|cx| {
13417 TestItem::new(cx)
13418 .with_dirty(true)
13419 .with_label("1.txt")
13420 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13421 });
13422 let dirty_regular_buffer_2 = cx.new(|cx| {
13423 TestItem::new(cx)
13424 .with_dirty(true)
13425 .with_label("2.txt")
13426 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13427 });
13428 let clear_regular_buffer = cx.new(|cx| {
13429 TestItem::new(cx)
13430 .with_label("3.txt")
13431 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13432 });
13433
13434 let dirty_multi_buffer = cx.new(|cx| {
13435 TestItem::new(cx)
13436 .with_dirty(true)
13437 .with_buffer_kind(ItemBufferKind::Multibuffer)
13438 .with_label("Fake Project Search")
13439 .with_project_items(&[
13440 dirty_regular_buffer.read(cx).project_items[0].clone(),
13441 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13442 clear_regular_buffer.read(cx).project_items[0].clone(),
13443 ])
13444 });
13445 workspace.update_in(cx, |workspace, window, cx| {
13446 workspace.add_item(
13447 pane.clone(),
13448 Box::new(dirty_regular_buffer.clone()),
13449 None,
13450 false,
13451 false,
13452 window,
13453 cx,
13454 );
13455 workspace.add_item(
13456 pane.clone(),
13457 Box::new(dirty_regular_buffer_2.clone()),
13458 None,
13459 false,
13460 false,
13461 window,
13462 cx,
13463 );
13464 workspace.add_item(
13465 pane.clone(),
13466 Box::new(dirty_multi_buffer.clone()),
13467 None,
13468 false,
13469 false,
13470 window,
13471 cx,
13472 );
13473 });
13474
13475 pane.update_in(cx, |pane, window, cx| {
13476 pane.activate_item(2, true, true, window, cx);
13477 assert_eq!(
13478 pane.active_item().unwrap().item_id(),
13479 dirty_multi_buffer.item_id(),
13480 "Should select the multi buffer in the pane"
13481 );
13482 });
13483 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13484 pane.close_active_item(
13485 &CloseActiveItem {
13486 save_intent: None,
13487 close_pinned: false,
13488 },
13489 window,
13490 cx,
13491 )
13492 });
13493 cx.background_executor.run_until_parked();
13494 assert!(
13495 !cx.has_pending_prompt(),
13496 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13497 );
13498 close_multi_buffer_task
13499 .await
13500 .expect("Closing multi buffer failed");
13501 pane.update(cx, |pane, cx| {
13502 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13503 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13504 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13505 assert_eq!(
13506 pane.items()
13507 .map(|item| item.item_id())
13508 .sorted()
13509 .collect::<Vec<_>>(),
13510 vec![
13511 dirty_regular_buffer.item_id(),
13512 dirty_regular_buffer_2.item_id(),
13513 ],
13514 "Should have no multi buffer left in the pane"
13515 );
13516 assert!(dirty_regular_buffer.read(cx).is_dirty);
13517 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13518 });
13519 }
13520
13521 #[gpui::test]
13522 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13523 init_test(cx);
13524 let fs = FakeFs::new(cx.executor());
13525 let project = Project::test(fs, [], cx).await;
13526 let (multi_workspace, cx) =
13527 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13528 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13529
13530 // Add a new panel to the right dock, opening the dock and setting the
13531 // focus to the new panel.
13532 let panel = workspace.update_in(cx, |workspace, window, cx| {
13533 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13534 workspace.add_panel(panel.clone(), window, cx);
13535
13536 workspace
13537 .right_dock()
13538 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13539
13540 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13541
13542 panel
13543 });
13544
13545 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13546 // panel to the next valid position which, in this case, is the left
13547 // dock.
13548 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13549 workspace.update(cx, |workspace, cx| {
13550 assert!(workspace.left_dock().read(cx).is_open());
13551 assert_eq!(panel.read(cx).position, DockPosition::Left);
13552 });
13553
13554 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13555 // panel to the next valid position which, in this case, is the bottom
13556 // dock.
13557 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13558 workspace.update(cx, |workspace, cx| {
13559 assert!(workspace.bottom_dock().read(cx).is_open());
13560 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13561 });
13562
13563 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13564 // around moving the panel to its initial position, the right dock.
13565 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13566 workspace.update(cx, |workspace, cx| {
13567 assert!(workspace.right_dock().read(cx).is_open());
13568 assert_eq!(panel.read(cx).position, DockPosition::Right);
13569 });
13570
13571 // Remove focus from the panel, ensuring that, if the panel is not
13572 // focused, the `MoveFocusedPanelToNextPosition` action does not update
13573 // the panel's position, so the panel is still in the right dock.
13574 workspace.update_in(cx, |workspace, window, cx| {
13575 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13576 });
13577
13578 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13579 workspace.update(cx, |workspace, cx| {
13580 assert!(workspace.right_dock().read(cx).is_open());
13581 assert_eq!(panel.read(cx).position, DockPosition::Right);
13582 });
13583 }
13584
13585 #[gpui::test]
13586 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13587 init_test(cx);
13588
13589 let fs = FakeFs::new(cx.executor());
13590 let project = Project::test(fs, [], cx).await;
13591 let (workspace, cx) =
13592 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13593
13594 let item_1 = cx.new(|cx| {
13595 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13596 });
13597 workspace.update_in(cx, |workspace, window, cx| {
13598 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13599 workspace.move_item_to_pane_in_direction(
13600 &MoveItemToPaneInDirection {
13601 direction: SplitDirection::Right,
13602 focus: true,
13603 clone: false,
13604 },
13605 window,
13606 cx,
13607 );
13608 workspace.move_item_to_pane_at_index(
13609 &MoveItemToPane {
13610 destination: 3,
13611 focus: true,
13612 clone: false,
13613 },
13614 window,
13615 cx,
13616 );
13617
13618 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13619 assert_eq!(
13620 pane_items_paths(&workspace.active_pane, cx),
13621 vec!["first.txt".to_string()],
13622 "Single item was not moved anywhere"
13623 );
13624 });
13625
13626 let item_2 = cx.new(|cx| {
13627 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13628 });
13629 workspace.update_in(cx, |workspace, window, cx| {
13630 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13631 assert_eq!(
13632 pane_items_paths(&workspace.panes[0], cx),
13633 vec!["first.txt".to_string(), "second.txt".to_string()],
13634 );
13635 workspace.move_item_to_pane_in_direction(
13636 &MoveItemToPaneInDirection {
13637 direction: SplitDirection::Right,
13638 focus: true,
13639 clone: false,
13640 },
13641 window,
13642 cx,
13643 );
13644
13645 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13646 assert_eq!(
13647 pane_items_paths(&workspace.panes[0], cx),
13648 vec!["first.txt".to_string()],
13649 "After moving, one item should be left in the original pane"
13650 );
13651 assert_eq!(
13652 pane_items_paths(&workspace.panes[1], cx),
13653 vec!["second.txt".to_string()],
13654 "New item should have been moved to the new pane"
13655 );
13656 });
13657
13658 let item_3 = cx.new(|cx| {
13659 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13660 });
13661 workspace.update_in(cx, |workspace, window, cx| {
13662 let original_pane = workspace.panes[0].clone();
13663 workspace.set_active_pane(&original_pane, window, cx);
13664 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13665 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13666 assert_eq!(
13667 pane_items_paths(&workspace.active_pane, cx),
13668 vec!["first.txt".to_string(), "third.txt".to_string()],
13669 "New pane should be ready to move one item out"
13670 );
13671
13672 workspace.move_item_to_pane_at_index(
13673 &MoveItemToPane {
13674 destination: 3,
13675 focus: true,
13676 clone: false,
13677 },
13678 window,
13679 cx,
13680 );
13681 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13682 assert_eq!(
13683 pane_items_paths(&workspace.active_pane, cx),
13684 vec!["first.txt".to_string()],
13685 "After moving, one item should be left in the original pane"
13686 );
13687 assert_eq!(
13688 pane_items_paths(&workspace.panes[1], cx),
13689 vec!["second.txt".to_string()],
13690 "Previously created pane should be unchanged"
13691 );
13692 assert_eq!(
13693 pane_items_paths(&workspace.panes[2], cx),
13694 vec!["third.txt".to_string()],
13695 "New item should have been moved to the new pane"
13696 );
13697 });
13698 }
13699
13700 #[gpui::test]
13701 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13702 init_test(cx);
13703
13704 let fs = FakeFs::new(cx.executor());
13705 let project = Project::test(fs, [], cx).await;
13706 let (workspace, cx) =
13707 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13708
13709 let item_1 = cx.new(|cx| {
13710 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13711 });
13712 workspace.update_in(cx, |workspace, window, cx| {
13713 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13714 workspace.move_item_to_pane_in_direction(
13715 &MoveItemToPaneInDirection {
13716 direction: SplitDirection::Right,
13717 focus: true,
13718 clone: true,
13719 },
13720 window,
13721 cx,
13722 );
13723 });
13724 cx.run_until_parked();
13725 workspace.update_in(cx, |workspace, window, cx| {
13726 workspace.move_item_to_pane_at_index(
13727 &MoveItemToPane {
13728 destination: 3,
13729 focus: true,
13730 clone: true,
13731 },
13732 window,
13733 cx,
13734 );
13735 });
13736 cx.run_until_parked();
13737
13738 workspace.update(cx, |workspace, cx| {
13739 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13740 for pane in workspace.panes() {
13741 assert_eq!(
13742 pane_items_paths(pane, cx),
13743 vec!["first.txt".to_string()],
13744 "Single item exists in all panes"
13745 );
13746 }
13747 });
13748
13749 // verify that the active pane has been updated after waiting for the
13750 // pane focus event to fire and resolve
13751 workspace.read_with(cx, |workspace, _app| {
13752 assert_eq!(
13753 workspace.active_pane(),
13754 &workspace.panes[2],
13755 "The third pane should be the active one: {:?}",
13756 workspace.panes
13757 );
13758 })
13759 }
13760
13761 #[gpui::test]
13762 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13763 init_test(cx);
13764
13765 let fs = FakeFs::new(cx.executor());
13766 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13767
13768 let project = Project::test(fs, ["root".as_ref()], cx).await;
13769 let (workspace, cx) =
13770 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13771
13772 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13773 // Add item to pane A with project path
13774 let item_a = cx.new(|cx| {
13775 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13776 });
13777 workspace.update_in(cx, |workspace, window, cx| {
13778 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13779 });
13780
13781 // Split to create pane B
13782 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13783 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13784 });
13785
13786 // Add item with SAME project path to pane B, and pin it
13787 let item_b = cx.new(|cx| {
13788 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13789 });
13790 pane_b.update_in(cx, |pane, window, cx| {
13791 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13792 pane.set_pinned_count(1);
13793 });
13794
13795 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13796 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13797
13798 // close_pinned: false should only close the unpinned copy
13799 workspace.update_in(cx, |workspace, window, cx| {
13800 workspace.close_item_in_all_panes(
13801 &CloseItemInAllPanes {
13802 save_intent: Some(SaveIntent::Close),
13803 close_pinned: false,
13804 },
13805 window,
13806 cx,
13807 )
13808 });
13809 cx.executor().run_until_parked();
13810
13811 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13812 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13813 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13814 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13815
13816 // Split again, seeing as closing the previous item also closed its
13817 // pane, so only pane remains, which does not allow us to properly test
13818 // that both items close when `close_pinned: true`.
13819 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13820 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13821 });
13822
13823 // Add an item with the same project path to pane C so that
13824 // close_item_in_all_panes can determine what to close across all panes
13825 // (it reads the active item from the active pane, and split_pane
13826 // creates an empty pane).
13827 let item_c = cx.new(|cx| {
13828 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13829 });
13830 pane_c.update_in(cx, |pane, window, cx| {
13831 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13832 });
13833
13834 // close_pinned: true should close the pinned copy too
13835 workspace.update_in(cx, |workspace, window, cx| {
13836 let panes_count = workspace.panes().len();
13837 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13838
13839 workspace.close_item_in_all_panes(
13840 &CloseItemInAllPanes {
13841 save_intent: Some(SaveIntent::Close),
13842 close_pinned: true,
13843 },
13844 window,
13845 cx,
13846 )
13847 });
13848 cx.executor().run_until_parked();
13849
13850 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13851 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13852 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13853 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13854 }
13855
13856 mod register_project_item_tests {
13857
13858 use super::*;
13859
13860 // View
13861 struct TestPngItemView {
13862 focus_handle: FocusHandle,
13863 }
13864 // Model
13865 struct TestPngItem {}
13866
13867 impl project::ProjectItem for TestPngItem {
13868 fn try_open(
13869 _project: &Entity<Project>,
13870 path: &ProjectPath,
13871 cx: &mut App,
13872 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13873 if path.path.extension().unwrap() == "png" {
13874 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13875 } else {
13876 None
13877 }
13878 }
13879
13880 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13881 None
13882 }
13883
13884 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13885 None
13886 }
13887
13888 fn is_dirty(&self) -> bool {
13889 false
13890 }
13891 }
13892
13893 impl Item for TestPngItemView {
13894 type Event = ();
13895 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13896 "".into()
13897 }
13898 }
13899 impl EventEmitter<()> for TestPngItemView {}
13900 impl Focusable for TestPngItemView {
13901 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13902 self.focus_handle.clone()
13903 }
13904 }
13905
13906 impl Render for TestPngItemView {
13907 fn render(
13908 &mut self,
13909 _window: &mut Window,
13910 _cx: &mut Context<Self>,
13911 ) -> impl IntoElement {
13912 Empty
13913 }
13914 }
13915
13916 impl ProjectItem for TestPngItemView {
13917 type Item = TestPngItem;
13918
13919 fn for_project_item(
13920 _project: Entity<Project>,
13921 _pane: Option<&Pane>,
13922 _item: Entity<Self::Item>,
13923 _: &mut Window,
13924 cx: &mut Context<Self>,
13925 ) -> Self
13926 where
13927 Self: Sized,
13928 {
13929 Self {
13930 focus_handle: cx.focus_handle(),
13931 }
13932 }
13933 }
13934
13935 // View
13936 struct TestIpynbItemView {
13937 focus_handle: FocusHandle,
13938 }
13939 // Model
13940 struct TestIpynbItem {}
13941
13942 impl project::ProjectItem for TestIpynbItem {
13943 fn try_open(
13944 _project: &Entity<Project>,
13945 path: &ProjectPath,
13946 cx: &mut App,
13947 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13948 if path.path.extension().unwrap() == "ipynb" {
13949 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13950 } else {
13951 None
13952 }
13953 }
13954
13955 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13956 None
13957 }
13958
13959 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13960 None
13961 }
13962
13963 fn is_dirty(&self) -> bool {
13964 false
13965 }
13966 }
13967
13968 impl Item for TestIpynbItemView {
13969 type Event = ();
13970 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13971 "".into()
13972 }
13973 }
13974 impl EventEmitter<()> for TestIpynbItemView {}
13975 impl Focusable for TestIpynbItemView {
13976 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13977 self.focus_handle.clone()
13978 }
13979 }
13980
13981 impl Render for TestIpynbItemView {
13982 fn render(
13983 &mut self,
13984 _window: &mut Window,
13985 _cx: &mut Context<Self>,
13986 ) -> impl IntoElement {
13987 Empty
13988 }
13989 }
13990
13991 impl ProjectItem for TestIpynbItemView {
13992 type Item = TestIpynbItem;
13993
13994 fn for_project_item(
13995 _project: Entity<Project>,
13996 _pane: Option<&Pane>,
13997 _item: Entity<Self::Item>,
13998 _: &mut Window,
13999 cx: &mut Context<Self>,
14000 ) -> Self
14001 where
14002 Self: Sized,
14003 {
14004 Self {
14005 focus_handle: cx.focus_handle(),
14006 }
14007 }
14008 }
14009
14010 struct TestAlternatePngItemView {
14011 focus_handle: FocusHandle,
14012 }
14013
14014 impl Item for TestAlternatePngItemView {
14015 type Event = ();
14016 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14017 "".into()
14018 }
14019 }
14020
14021 impl EventEmitter<()> for TestAlternatePngItemView {}
14022 impl Focusable for TestAlternatePngItemView {
14023 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14024 self.focus_handle.clone()
14025 }
14026 }
14027
14028 impl Render for TestAlternatePngItemView {
14029 fn render(
14030 &mut self,
14031 _window: &mut Window,
14032 _cx: &mut Context<Self>,
14033 ) -> impl IntoElement {
14034 Empty
14035 }
14036 }
14037
14038 impl ProjectItem for TestAlternatePngItemView {
14039 type Item = TestPngItem;
14040
14041 fn for_project_item(
14042 _project: Entity<Project>,
14043 _pane: Option<&Pane>,
14044 _item: Entity<Self::Item>,
14045 _: &mut Window,
14046 cx: &mut Context<Self>,
14047 ) -> Self
14048 where
14049 Self: Sized,
14050 {
14051 Self {
14052 focus_handle: cx.focus_handle(),
14053 }
14054 }
14055 }
14056
14057 #[gpui::test]
14058 async fn test_register_project_item(cx: &mut TestAppContext) {
14059 init_test(cx);
14060
14061 cx.update(|cx| {
14062 register_project_item::<TestPngItemView>(cx);
14063 register_project_item::<TestIpynbItemView>(cx);
14064 });
14065
14066 let fs = FakeFs::new(cx.executor());
14067 fs.insert_tree(
14068 "/root1",
14069 json!({
14070 "one.png": "BINARYDATAHERE",
14071 "two.ipynb": "{ totally a notebook }",
14072 "three.txt": "editing text, sure why not?"
14073 }),
14074 )
14075 .await;
14076
14077 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14078 let (workspace, cx) =
14079 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14080
14081 let worktree_id = project.update(cx, |project, cx| {
14082 project.worktrees(cx).next().unwrap().read(cx).id()
14083 });
14084
14085 let handle = workspace
14086 .update_in(cx, |workspace, window, cx| {
14087 let project_path = (worktree_id, rel_path("one.png"));
14088 workspace.open_path(project_path, None, true, window, cx)
14089 })
14090 .await
14091 .unwrap();
14092
14093 // Now we can check if the handle we got back errored or not
14094 assert_eq!(
14095 handle.to_any_view().entity_type(),
14096 TypeId::of::<TestPngItemView>()
14097 );
14098
14099 let handle = workspace
14100 .update_in(cx, |workspace, window, cx| {
14101 let project_path = (worktree_id, rel_path("two.ipynb"));
14102 workspace.open_path(project_path, None, true, window, cx)
14103 })
14104 .await
14105 .unwrap();
14106
14107 assert_eq!(
14108 handle.to_any_view().entity_type(),
14109 TypeId::of::<TestIpynbItemView>()
14110 );
14111
14112 let handle = workspace
14113 .update_in(cx, |workspace, window, cx| {
14114 let project_path = (worktree_id, rel_path("three.txt"));
14115 workspace.open_path(project_path, None, true, window, cx)
14116 })
14117 .await;
14118 assert!(handle.is_err());
14119 }
14120
14121 #[gpui::test]
14122 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14123 init_test(cx);
14124
14125 cx.update(|cx| {
14126 register_project_item::<TestPngItemView>(cx);
14127 register_project_item::<TestAlternatePngItemView>(cx);
14128 });
14129
14130 let fs = FakeFs::new(cx.executor());
14131 fs.insert_tree(
14132 "/root1",
14133 json!({
14134 "one.png": "BINARYDATAHERE",
14135 "two.ipynb": "{ totally a notebook }",
14136 "three.txt": "editing text, sure why not?"
14137 }),
14138 )
14139 .await;
14140 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14141 let (workspace, cx) =
14142 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14143 let worktree_id = project.update(cx, |project, cx| {
14144 project.worktrees(cx).next().unwrap().read(cx).id()
14145 });
14146
14147 let handle = workspace
14148 .update_in(cx, |workspace, window, cx| {
14149 let project_path = (worktree_id, rel_path("one.png"));
14150 workspace.open_path(project_path, None, true, window, cx)
14151 })
14152 .await
14153 .unwrap();
14154
14155 // This _must_ be the second item registered
14156 assert_eq!(
14157 handle.to_any_view().entity_type(),
14158 TypeId::of::<TestAlternatePngItemView>()
14159 );
14160
14161 let handle = workspace
14162 .update_in(cx, |workspace, window, cx| {
14163 let project_path = (worktree_id, rel_path("three.txt"));
14164 workspace.open_path(project_path, None, true, window, cx)
14165 })
14166 .await;
14167 assert!(handle.is_err());
14168 }
14169 }
14170
14171 #[gpui::test]
14172 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14173 init_test(cx);
14174
14175 let fs = FakeFs::new(cx.executor());
14176 let project = Project::test(fs, [], cx).await;
14177 let (workspace, _cx) =
14178 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14179
14180 // Test with status bar shown (default)
14181 workspace.read_with(cx, |workspace, cx| {
14182 let visible = workspace.status_bar_visible(cx);
14183 assert!(visible, "Status bar should be visible by default");
14184 });
14185
14186 // Test with status bar hidden
14187 cx.update_global(|store: &mut SettingsStore, cx| {
14188 store.update_user_settings(cx, |settings| {
14189 settings.status_bar.get_or_insert_default().show = Some(false);
14190 });
14191 });
14192
14193 workspace.read_with(cx, |workspace, cx| {
14194 let visible = workspace.status_bar_visible(cx);
14195 assert!(!visible, "Status bar should be hidden when show is false");
14196 });
14197
14198 // Test with status bar shown explicitly
14199 cx.update_global(|store: &mut SettingsStore, cx| {
14200 store.update_user_settings(cx, |settings| {
14201 settings.status_bar.get_or_insert_default().show = Some(true);
14202 });
14203 });
14204
14205 workspace.read_with(cx, |workspace, cx| {
14206 let visible = workspace.status_bar_visible(cx);
14207 assert!(visible, "Status bar should be visible when show is true");
14208 });
14209 }
14210
14211 #[gpui::test]
14212 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14213 init_test(cx);
14214
14215 let fs = FakeFs::new(cx.executor());
14216 let project = Project::test(fs, [], cx).await;
14217 let (multi_workspace, cx) =
14218 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14219 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14220 let panel = workspace.update_in(cx, |workspace, window, cx| {
14221 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14222 workspace.add_panel(panel.clone(), window, cx);
14223
14224 workspace
14225 .right_dock()
14226 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14227
14228 panel
14229 });
14230
14231 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14232 let item_a = cx.new(TestItem::new);
14233 let item_b = cx.new(TestItem::new);
14234 let item_a_id = item_a.entity_id();
14235 let item_b_id = item_b.entity_id();
14236
14237 pane.update_in(cx, |pane, window, cx| {
14238 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14239 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14240 });
14241
14242 pane.read_with(cx, |pane, _| {
14243 assert_eq!(pane.items_len(), 2);
14244 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14245 });
14246
14247 workspace.update_in(cx, |workspace, window, cx| {
14248 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14249 });
14250
14251 workspace.update_in(cx, |_, window, cx| {
14252 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14253 });
14254
14255 // Assert that the `pane::CloseActiveItem` action is handled at the
14256 // workspace level when one of the dock panels is focused and, in that
14257 // case, the center pane's active item is closed but the focus is not
14258 // moved.
14259 cx.dispatch_action(pane::CloseActiveItem::default());
14260 cx.run_until_parked();
14261
14262 pane.read_with(cx, |pane, _| {
14263 assert_eq!(pane.items_len(), 1);
14264 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14265 });
14266
14267 workspace.update_in(cx, |workspace, window, cx| {
14268 assert!(workspace.right_dock().read(cx).is_open());
14269 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14270 });
14271 }
14272
14273 #[gpui::test]
14274 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14275 init_test(cx);
14276 let fs = FakeFs::new(cx.executor());
14277
14278 let project_a = Project::test(fs.clone(), [], cx).await;
14279 let project_b = Project::test(fs, [], cx).await;
14280
14281 let multi_workspace_handle =
14282 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14283 cx.run_until_parked();
14284
14285 let workspace_a = multi_workspace_handle
14286 .read_with(cx, |mw, _| mw.workspace().clone())
14287 .unwrap();
14288
14289 let _workspace_b = multi_workspace_handle
14290 .update(cx, |mw, window, cx| {
14291 mw.test_add_workspace(project_b, window, cx)
14292 })
14293 .unwrap();
14294
14295 // Switch to workspace A
14296 multi_workspace_handle
14297 .update(cx, |mw, window, cx| {
14298 mw.activate_index(0, window, cx);
14299 })
14300 .unwrap();
14301
14302 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14303
14304 // Add a panel to workspace A's right dock and open the dock
14305 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14306 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14307 workspace.add_panel(panel.clone(), window, cx);
14308 workspace
14309 .right_dock()
14310 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14311 panel
14312 });
14313
14314 // Focus the panel through the workspace (matching existing test pattern)
14315 workspace_a.update_in(cx, |workspace, window, cx| {
14316 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14317 });
14318
14319 // Zoom the panel
14320 panel.update_in(cx, |panel, window, cx| {
14321 panel.set_zoomed(true, window, cx);
14322 });
14323
14324 // Verify the panel is zoomed and the dock is open
14325 workspace_a.update_in(cx, |workspace, window, cx| {
14326 assert!(
14327 workspace.right_dock().read(cx).is_open(),
14328 "dock should be open before switch"
14329 );
14330 assert!(
14331 panel.is_zoomed(window, cx),
14332 "panel should be zoomed before switch"
14333 );
14334 assert!(
14335 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14336 "panel should be focused before switch"
14337 );
14338 });
14339
14340 // Switch to workspace B
14341 multi_workspace_handle
14342 .update(cx, |mw, window, cx| {
14343 mw.activate_index(1, window, cx);
14344 })
14345 .unwrap();
14346 cx.run_until_parked();
14347
14348 // Switch back to workspace A
14349 multi_workspace_handle
14350 .update(cx, |mw, window, cx| {
14351 mw.activate_index(0, window, cx);
14352 })
14353 .unwrap();
14354 cx.run_until_parked();
14355
14356 // Verify the panel is still zoomed and the dock is still open
14357 workspace_a.update_in(cx, |workspace, window, cx| {
14358 assert!(
14359 workspace.right_dock().read(cx).is_open(),
14360 "dock should still be open after switching back"
14361 );
14362 assert!(
14363 panel.is_zoomed(window, cx),
14364 "panel should still be zoomed after switching back"
14365 );
14366 });
14367 }
14368
14369 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14370 pane.read(cx)
14371 .items()
14372 .flat_map(|item| {
14373 item.project_paths(cx)
14374 .into_iter()
14375 .map(|path| path.path.display(PathStyle::local()).into_owned())
14376 })
14377 .collect()
14378 }
14379
14380 pub fn init_test(cx: &mut TestAppContext) {
14381 cx.update(|cx| {
14382 let settings_store = SettingsStore::test(cx);
14383 cx.set_global(settings_store);
14384 cx.set_global(db::AppDatabase::test_new());
14385 theme::init(theme::LoadThemes::JustBase, cx);
14386 });
14387 }
14388
14389 #[gpui::test]
14390 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14391 use settings::{ThemeName, ThemeSelection};
14392 use theme::SystemAppearance;
14393 use zed_actions::theme::ToggleMode;
14394
14395 init_test(cx);
14396
14397 let fs = FakeFs::new(cx.executor());
14398 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14399
14400 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14401 .await;
14402
14403 // Build a test project and workspace view so the test can invoke
14404 // the workspace action handler the same way the UI would.
14405 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14406 let (workspace, cx) =
14407 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14408
14409 // Seed the settings file with a plain static light theme so the
14410 // first toggle always starts from a known persisted state.
14411 workspace.update_in(cx, |_workspace, _window, cx| {
14412 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14413 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14414 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14415 });
14416 });
14417 cx.executor().advance_clock(Duration::from_millis(200));
14418 cx.run_until_parked();
14419
14420 // Confirm the initial persisted settings contain the static theme
14421 // we just wrote before any toggling happens.
14422 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14423 assert!(settings_text.contains(r#""theme": "One Light""#));
14424
14425 // Toggle once. This should migrate the persisted theme settings
14426 // into light/dark slots and enable system mode.
14427 workspace.update_in(cx, |workspace, window, cx| {
14428 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14429 });
14430 cx.executor().advance_clock(Duration::from_millis(200));
14431 cx.run_until_parked();
14432
14433 // 1. Static -> Dynamic
14434 // this assertion checks theme changed from static to dynamic.
14435 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14436 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14437 assert_eq!(
14438 parsed["theme"],
14439 serde_json::json!({
14440 "mode": "system",
14441 "light": "One Light",
14442 "dark": "One Dark"
14443 })
14444 );
14445
14446 // 2. Toggle again, suppose it will change the mode to light
14447 workspace.update_in(cx, |workspace, window, cx| {
14448 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14449 });
14450 cx.executor().advance_clock(Duration::from_millis(200));
14451 cx.run_until_parked();
14452
14453 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14454 assert!(settings_text.contains(r#""mode": "light""#));
14455 }
14456
14457 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14458 let item = TestProjectItem::new(id, path, cx);
14459 item.update(cx, |item, _| {
14460 item.is_dirty = true;
14461 });
14462 item
14463 }
14464
14465 #[gpui::test]
14466 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14467 cx: &mut gpui::TestAppContext,
14468 ) {
14469 init_test(cx);
14470 let fs = FakeFs::new(cx.executor());
14471
14472 let project = Project::test(fs, [], cx).await;
14473 let (workspace, cx) =
14474 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14475
14476 let panel = workspace.update_in(cx, |workspace, window, cx| {
14477 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14478 workspace.add_panel(panel.clone(), window, cx);
14479 workspace
14480 .right_dock()
14481 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14482 panel
14483 });
14484
14485 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14486 pane.update_in(cx, |pane, window, cx| {
14487 let item = cx.new(TestItem::new);
14488 pane.add_item(Box::new(item), true, true, None, window, cx);
14489 });
14490
14491 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14492 // mirrors the real-world flow and avoids side effects from directly
14493 // focusing the panel while the center pane is active.
14494 workspace.update_in(cx, |workspace, window, cx| {
14495 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14496 });
14497
14498 panel.update_in(cx, |panel, window, cx| {
14499 panel.set_zoomed(true, window, cx);
14500 });
14501
14502 workspace.update_in(cx, |workspace, window, cx| {
14503 assert!(workspace.right_dock().read(cx).is_open());
14504 assert!(panel.is_zoomed(window, cx));
14505 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14506 });
14507
14508 // Simulate a spurious pane::Event::Focus on the center pane while the
14509 // panel still has focus. This mirrors what happens during macOS window
14510 // activation: the center pane fires a focus event even though actual
14511 // focus remains on the dock panel.
14512 pane.update_in(cx, |_, _, cx| {
14513 cx.emit(pane::Event::Focus);
14514 });
14515
14516 // The dock must remain open because the panel had focus at the time the
14517 // event was processed. Before the fix, dock_to_preserve was None for
14518 // panels that don't implement pane(), causing the dock to close.
14519 workspace.update_in(cx, |workspace, window, cx| {
14520 assert!(
14521 workspace.right_dock().read(cx).is_open(),
14522 "Dock should stay open when its zoomed panel (without pane()) still has focus"
14523 );
14524 assert!(panel.is_zoomed(window, cx));
14525 });
14526 }
14527
14528 #[gpui::test]
14529 async fn test_panels_stay_open_after_position_change_and_settings_update(
14530 cx: &mut gpui::TestAppContext,
14531 ) {
14532 init_test(cx);
14533 let fs = FakeFs::new(cx.executor());
14534 let project = Project::test(fs, [], cx).await;
14535 let (workspace, cx) =
14536 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14537
14538 // Add two panels to the left dock and open it.
14539 let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14540 let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14541 let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14542 workspace.add_panel(panel_a.clone(), window, cx);
14543 workspace.add_panel(panel_b.clone(), window, cx);
14544 workspace.left_dock().update(cx, |dock, cx| {
14545 dock.set_open(true, window, cx);
14546 dock.activate_panel(0, window, cx);
14547 });
14548 (panel_a, panel_b)
14549 });
14550
14551 workspace.update_in(cx, |workspace, _, cx| {
14552 assert!(workspace.left_dock().read(cx).is_open());
14553 });
14554
14555 // Simulate a feature flag changing default dock positions: both panels
14556 // move from Left to Right.
14557 workspace.update_in(cx, |_workspace, _window, cx| {
14558 panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14559 panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14560 cx.update_global::<SettingsStore, _>(|_, _| {});
14561 });
14562
14563 // Both panels should now be in the right dock.
14564 workspace.update_in(cx, |workspace, _, cx| {
14565 let right_dock = workspace.right_dock().read(cx);
14566 assert_eq!(right_dock.panels_len(), 2);
14567 });
14568
14569 // Open the right dock and activate panel_b (simulating the user
14570 // opening the panel after it moved).
14571 workspace.update_in(cx, |workspace, window, cx| {
14572 workspace.right_dock().update(cx, |dock, cx| {
14573 dock.set_open(true, window, cx);
14574 dock.activate_panel(1, window, cx);
14575 });
14576 });
14577
14578 // Now trigger another SettingsStore change
14579 workspace.update_in(cx, |_workspace, _window, cx| {
14580 cx.update_global::<SettingsStore, _>(|_, _| {});
14581 });
14582
14583 workspace.update_in(cx, |workspace, _, cx| {
14584 assert!(
14585 workspace.right_dock().read(cx).is_open(),
14586 "Right dock should still be open after a settings change"
14587 );
14588 assert_eq!(
14589 workspace.right_dock().read(cx).panels_len(),
14590 2,
14591 "Both panels should still be in the right dock"
14592 );
14593 });
14594 }
14595}