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::{dock::PanelSizeState, 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 toggle_dock_panel_flexible_size(
2197 &self,
2198 dock: &Entity<Dock>,
2199 panel: &dyn PanelHandle,
2200 window: &mut Window,
2201 cx: &mut App,
2202 ) {
2203 let position = dock.read(cx).position();
2204 let current_size = self.dock_size(&dock.read(cx), window, cx);
2205 let current_flex =
2206 current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
2207 dock.update(cx, |dock, cx| {
2208 dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
2209 });
2210 }
2211
2212 fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
2213 let panel = dock.active_panel()?;
2214 let size_state = dock
2215 .stored_panel_size_state(panel.as_ref())
2216 .unwrap_or_default();
2217 let position = dock.position();
2218
2219 let use_flex = panel.has_flexible_size(window, cx);
2220
2221 if position.axis() == Axis::Horizontal
2222 && use_flex
2223 && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
2224 {
2225 let workspace_width = self.bounds.size.width;
2226 if workspace_width <= Pixels::ZERO {
2227 return None;
2228 }
2229 let flex = flex.max(0.001);
2230 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2231 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2232 // Both docks are flex items sharing the full workspace width.
2233 let total_flex = flex + 1.0 + opposite_flex;
2234 return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
2235 } else {
2236 // Opposite dock is fixed-width; flex items share (W - fixed).
2237 let opposite_fixed = opposite
2238 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2239 .unwrap_or_default();
2240 let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
2241 return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
2242 }
2243 }
2244
2245 Some(
2246 size_state
2247 .size
2248 .unwrap_or_else(|| panel.default_size(window, cx)),
2249 )
2250 }
2251
2252 pub fn dock_flex_for_size(
2253 &self,
2254 position: DockPosition,
2255 size: Pixels,
2256 window: &Window,
2257 cx: &App,
2258 ) -> Option<f32> {
2259 if position.axis() != Axis::Horizontal {
2260 return None;
2261 }
2262
2263 let workspace_width = self.bounds.size.width;
2264 if workspace_width <= Pixels::ZERO {
2265 return None;
2266 }
2267
2268 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2269 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2270 let size = size.clamp(px(0.), workspace_width - px(1.));
2271 Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
2272 } else {
2273 let opposite_width = opposite
2274 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2275 .unwrap_or_default();
2276 let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
2277 let remaining = (available - size).max(px(1.));
2278 Some((size / remaining).max(0.0))
2279 }
2280 }
2281
2282 fn opposite_dock_panel_and_size_state(
2283 &self,
2284 position: DockPosition,
2285 window: &Window,
2286 cx: &App,
2287 ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
2288 let opposite_position = match position {
2289 DockPosition::Left => DockPosition::Right,
2290 DockPosition::Right => DockPosition::Left,
2291 DockPosition::Bottom => return None,
2292 };
2293
2294 let opposite_dock = self.dock_at_position(opposite_position).read(cx);
2295 let panel = opposite_dock.visible_panel()?;
2296 let mut size_state = opposite_dock
2297 .stored_panel_size_state(panel.as_ref())
2298 .unwrap_or_default();
2299 if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
2300 size_state.flex = self.default_dock_flex(opposite_position);
2301 }
2302 Some((panel.clone(), size_state))
2303 }
2304
2305 pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
2306 if position.axis() != Axis::Horizontal {
2307 return None;
2308 }
2309
2310 let pane = self.last_active_center_pane.clone()?.upgrade()?;
2311 Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
2312 }
2313
2314 pub fn is_edited(&self) -> bool {
2315 self.window_edited
2316 }
2317
2318 pub fn add_panel<T: Panel>(
2319 &mut self,
2320 panel: Entity<T>,
2321 window: &mut Window,
2322 cx: &mut Context<Self>,
2323 ) {
2324 let focus_handle = panel.panel_focus_handle(cx);
2325 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2326 .detach();
2327
2328 let dock_position = panel.position(window, cx);
2329 let dock = self.dock_at_position(dock_position);
2330 let any_panel = panel.to_any();
2331 let persisted_size_state =
2332 self.persisted_panel_size_state(T::panel_key(), cx)
2333 .or_else(|| {
2334 load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
2335 let state = dock::PanelSizeState {
2336 size: Some(size),
2337 flex: None,
2338 };
2339 self.persist_panel_size_state(T::panel_key(), state, cx);
2340 state
2341 })
2342 });
2343
2344 dock.update(cx, |dock, cx| {
2345 let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
2346 if let Some(size_state) = persisted_size_state {
2347 dock.set_panel_size_state(&panel, size_state, cx);
2348 }
2349 index
2350 });
2351
2352 cx.emit(Event::PanelAdded(any_panel));
2353 }
2354
2355 pub fn remove_panel<T: Panel>(
2356 &mut self,
2357 panel: &Entity<T>,
2358 window: &mut Window,
2359 cx: &mut Context<Self>,
2360 ) {
2361 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2362 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2363 }
2364 }
2365
2366 pub fn status_bar(&self) -> &Entity<StatusBar> {
2367 &self.status_bar
2368 }
2369
2370 pub fn set_workspace_sidebar_open(
2371 &self,
2372 open: bool,
2373 has_notifications: bool,
2374 show_toggle: bool,
2375 cx: &mut App,
2376 ) {
2377 self.status_bar.update(cx, |status_bar, cx| {
2378 status_bar.set_workspace_sidebar_open(open, cx);
2379 status_bar.set_sidebar_has_notifications(has_notifications, cx);
2380 status_bar.set_show_sidebar_toggle(show_toggle, cx);
2381 });
2382 }
2383
2384 pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
2385 self.sidebar_focus_handle = handle;
2386 }
2387
2388 pub fn status_bar_visible(&self, cx: &App) -> bool {
2389 StatusBarSettings::get_global(cx).show
2390 }
2391
2392 pub fn app_state(&self) -> &Arc<AppState> {
2393 &self.app_state
2394 }
2395
2396 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2397 self._panels_task = Some(task);
2398 }
2399
2400 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2401 self._panels_task.take()
2402 }
2403
2404 pub fn user_store(&self) -> &Entity<UserStore> {
2405 &self.app_state.user_store
2406 }
2407
2408 pub fn project(&self) -> &Entity<Project> {
2409 &self.project
2410 }
2411
2412 pub fn path_style(&self, cx: &App) -> PathStyle {
2413 self.project.read(cx).path_style(cx)
2414 }
2415
2416 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2417 let mut history: HashMap<EntityId, usize> = HashMap::default();
2418
2419 for pane_handle in &self.panes {
2420 let pane = pane_handle.read(cx);
2421
2422 for entry in pane.activation_history() {
2423 history.insert(
2424 entry.entity_id,
2425 history
2426 .get(&entry.entity_id)
2427 .cloned()
2428 .unwrap_or(0)
2429 .max(entry.timestamp),
2430 );
2431 }
2432 }
2433
2434 history
2435 }
2436
2437 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2438 let mut recent_item: Option<Entity<T>> = None;
2439 let mut recent_timestamp = 0;
2440 for pane_handle in &self.panes {
2441 let pane = pane_handle.read(cx);
2442 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2443 pane.items().map(|item| (item.item_id(), item)).collect();
2444 for entry in pane.activation_history() {
2445 if entry.timestamp > recent_timestamp
2446 && let Some(&item) = item_map.get(&entry.entity_id)
2447 && let Some(typed_item) = item.act_as::<T>(cx)
2448 {
2449 recent_timestamp = entry.timestamp;
2450 recent_item = Some(typed_item);
2451 }
2452 }
2453 }
2454 recent_item
2455 }
2456
2457 pub fn recent_navigation_history_iter(
2458 &self,
2459 cx: &App,
2460 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2461 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2462 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2463
2464 for pane in &self.panes {
2465 let pane = pane.read(cx);
2466
2467 pane.nav_history()
2468 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2469 if let Some(fs_path) = &fs_path {
2470 abs_paths_opened
2471 .entry(fs_path.clone())
2472 .or_default()
2473 .insert(project_path.clone());
2474 }
2475 let timestamp = entry.timestamp;
2476 match history.entry(project_path) {
2477 hash_map::Entry::Occupied(mut entry) => {
2478 let (_, old_timestamp) = entry.get();
2479 if ×tamp > old_timestamp {
2480 entry.insert((fs_path, timestamp));
2481 }
2482 }
2483 hash_map::Entry::Vacant(entry) => {
2484 entry.insert((fs_path, timestamp));
2485 }
2486 }
2487 });
2488
2489 if let Some(item) = pane.active_item()
2490 && let Some(project_path) = item.project_path(cx)
2491 {
2492 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2493
2494 if let Some(fs_path) = &fs_path {
2495 abs_paths_opened
2496 .entry(fs_path.clone())
2497 .or_default()
2498 .insert(project_path.clone());
2499 }
2500
2501 history.insert(project_path, (fs_path, std::usize::MAX));
2502 }
2503 }
2504
2505 history
2506 .into_iter()
2507 .sorted_by_key(|(_, (_, order))| *order)
2508 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2509 .rev()
2510 .filter(move |(history_path, abs_path)| {
2511 let latest_project_path_opened = abs_path
2512 .as_ref()
2513 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2514 .and_then(|project_paths| {
2515 project_paths
2516 .iter()
2517 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2518 });
2519
2520 latest_project_path_opened.is_none_or(|path| path == history_path)
2521 })
2522 }
2523
2524 pub fn recent_navigation_history(
2525 &self,
2526 limit: Option<usize>,
2527 cx: &App,
2528 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2529 self.recent_navigation_history_iter(cx)
2530 .take(limit.unwrap_or(usize::MAX))
2531 .collect()
2532 }
2533
2534 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2535 for pane in &self.panes {
2536 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2537 }
2538 }
2539
2540 fn navigate_history(
2541 &mut self,
2542 pane: WeakEntity<Pane>,
2543 mode: NavigationMode,
2544 window: &mut Window,
2545 cx: &mut Context<Workspace>,
2546 ) -> Task<Result<()>> {
2547 self.navigate_history_impl(
2548 pane,
2549 mode,
2550 window,
2551 &mut |history, cx| history.pop(mode, cx),
2552 cx,
2553 )
2554 }
2555
2556 fn navigate_tag_history(
2557 &mut self,
2558 pane: WeakEntity<Pane>,
2559 mode: TagNavigationMode,
2560 window: &mut Window,
2561 cx: &mut Context<Workspace>,
2562 ) -> Task<Result<()>> {
2563 self.navigate_history_impl(
2564 pane,
2565 NavigationMode::Normal,
2566 window,
2567 &mut |history, _cx| history.pop_tag(mode),
2568 cx,
2569 )
2570 }
2571
2572 fn navigate_history_impl(
2573 &mut self,
2574 pane: WeakEntity<Pane>,
2575 mode: NavigationMode,
2576 window: &mut Window,
2577 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2578 cx: &mut Context<Workspace>,
2579 ) -> Task<Result<()>> {
2580 let to_load = if let Some(pane) = pane.upgrade() {
2581 pane.update(cx, |pane, cx| {
2582 window.focus(&pane.focus_handle(cx), cx);
2583 loop {
2584 // Retrieve the weak item handle from the history.
2585 let entry = cb(pane.nav_history_mut(), cx)?;
2586
2587 // If the item is still present in this pane, then activate it.
2588 if let Some(index) = entry
2589 .item
2590 .upgrade()
2591 .and_then(|v| pane.index_for_item(v.as_ref()))
2592 {
2593 let prev_active_item_index = pane.active_item_index();
2594 pane.nav_history_mut().set_mode(mode);
2595 pane.activate_item(index, true, true, window, cx);
2596 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2597
2598 let mut navigated = prev_active_item_index != pane.active_item_index();
2599 if let Some(data) = entry.data {
2600 navigated |= pane.active_item()?.navigate(data, window, cx);
2601 }
2602
2603 if navigated {
2604 break None;
2605 }
2606 } else {
2607 // If the item is no longer present in this pane, then retrieve its
2608 // path info in order to reopen it.
2609 break pane
2610 .nav_history()
2611 .path_for_item(entry.item.id())
2612 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2613 }
2614 }
2615 })
2616 } else {
2617 None
2618 };
2619
2620 if let Some((project_path, abs_path, entry)) = to_load {
2621 // If the item was no longer present, then load it again from its previous path, first try the local path
2622 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2623
2624 cx.spawn_in(window, async move |workspace, cx| {
2625 let open_by_project_path = open_by_project_path.await;
2626 let mut navigated = false;
2627 match open_by_project_path
2628 .with_context(|| format!("Navigating to {project_path:?}"))
2629 {
2630 Ok((project_entry_id, build_item)) => {
2631 let prev_active_item_id = pane.update(cx, |pane, _| {
2632 pane.nav_history_mut().set_mode(mode);
2633 pane.active_item().map(|p| p.item_id())
2634 })?;
2635
2636 pane.update_in(cx, |pane, window, cx| {
2637 let item = pane.open_item(
2638 project_entry_id,
2639 project_path,
2640 true,
2641 entry.is_preview,
2642 true,
2643 None,
2644 window, cx,
2645 build_item,
2646 );
2647 navigated |= Some(item.item_id()) != prev_active_item_id;
2648 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2649 if let Some(data) = entry.data {
2650 navigated |= item.navigate(data, window, cx);
2651 }
2652 })?;
2653 }
2654 Err(open_by_project_path_e) => {
2655 // Fall back to opening by abs path, in case an external file was opened and closed,
2656 // and its worktree is now dropped
2657 if let Some(abs_path) = abs_path {
2658 let prev_active_item_id = pane.update(cx, |pane, _| {
2659 pane.nav_history_mut().set_mode(mode);
2660 pane.active_item().map(|p| p.item_id())
2661 })?;
2662 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2663 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2664 })?;
2665 match open_by_abs_path
2666 .await
2667 .with_context(|| format!("Navigating to {abs_path:?}"))
2668 {
2669 Ok(item) => {
2670 pane.update_in(cx, |pane, window, cx| {
2671 navigated |= Some(item.item_id()) != prev_active_item_id;
2672 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2673 if let Some(data) = entry.data {
2674 navigated |= item.navigate(data, window, cx);
2675 }
2676 })?;
2677 }
2678 Err(open_by_abs_path_e) => {
2679 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2680 }
2681 }
2682 }
2683 }
2684 }
2685
2686 if !navigated {
2687 workspace
2688 .update_in(cx, |workspace, window, cx| {
2689 Self::navigate_history(workspace, pane, mode, window, cx)
2690 })?
2691 .await?;
2692 }
2693
2694 Ok(())
2695 })
2696 } else {
2697 Task::ready(Ok(()))
2698 }
2699 }
2700
2701 pub fn go_back(
2702 &mut self,
2703 pane: WeakEntity<Pane>,
2704 window: &mut Window,
2705 cx: &mut Context<Workspace>,
2706 ) -> Task<Result<()>> {
2707 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2708 }
2709
2710 pub fn go_forward(
2711 &mut self,
2712 pane: WeakEntity<Pane>,
2713 window: &mut Window,
2714 cx: &mut Context<Workspace>,
2715 ) -> Task<Result<()>> {
2716 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2717 }
2718
2719 pub fn reopen_closed_item(
2720 &mut self,
2721 window: &mut Window,
2722 cx: &mut Context<Workspace>,
2723 ) -> Task<Result<()>> {
2724 self.navigate_history(
2725 self.active_pane().downgrade(),
2726 NavigationMode::ReopeningClosedItem,
2727 window,
2728 cx,
2729 )
2730 }
2731
2732 pub fn client(&self) -> &Arc<Client> {
2733 &self.app_state.client
2734 }
2735
2736 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2737 self.titlebar_item = Some(item);
2738 cx.notify();
2739 }
2740
2741 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2742 self.on_prompt_for_new_path = Some(prompt)
2743 }
2744
2745 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2746 self.on_prompt_for_open_path = Some(prompt)
2747 }
2748
2749 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2750 self.terminal_provider = Some(Box::new(provider));
2751 }
2752
2753 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2754 self.debugger_provider = Some(Arc::new(provider));
2755 }
2756
2757 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2758 self.debugger_provider.clone()
2759 }
2760
2761 pub fn prompt_for_open_path(
2762 &mut self,
2763 path_prompt_options: PathPromptOptions,
2764 lister: DirectoryLister,
2765 window: &mut Window,
2766 cx: &mut Context<Self>,
2767 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2768 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2769 let prompt = self.on_prompt_for_open_path.take().unwrap();
2770 let rx = prompt(self, lister, window, cx);
2771 self.on_prompt_for_open_path = Some(prompt);
2772 rx
2773 } else {
2774 let (tx, rx) = oneshot::channel();
2775 let abs_path = cx.prompt_for_paths(path_prompt_options);
2776
2777 cx.spawn_in(window, async move |workspace, cx| {
2778 let Ok(result) = abs_path.await else {
2779 return Ok(());
2780 };
2781
2782 match result {
2783 Ok(result) => {
2784 tx.send(result).ok();
2785 }
2786 Err(err) => {
2787 let rx = workspace.update_in(cx, |workspace, window, cx| {
2788 workspace.show_portal_error(err.to_string(), cx);
2789 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2790 let rx = prompt(workspace, lister, window, cx);
2791 workspace.on_prompt_for_open_path = Some(prompt);
2792 rx
2793 })?;
2794 if let Ok(path) = rx.await {
2795 tx.send(path).ok();
2796 }
2797 }
2798 };
2799 anyhow::Ok(())
2800 })
2801 .detach();
2802
2803 rx
2804 }
2805 }
2806
2807 pub fn prompt_for_new_path(
2808 &mut self,
2809 lister: DirectoryLister,
2810 suggested_name: Option<String>,
2811 window: &mut Window,
2812 cx: &mut Context<Self>,
2813 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2814 if self.project.read(cx).is_via_collab()
2815 || self.project.read(cx).is_via_remote_server()
2816 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2817 {
2818 let prompt = self.on_prompt_for_new_path.take().unwrap();
2819 let rx = prompt(self, lister, suggested_name, window, cx);
2820 self.on_prompt_for_new_path = Some(prompt);
2821 return rx;
2822 }
2823
2824 let (tx, rx) = oneshot::channel();
2825 cx.spawn_in(window, async move |workspace, cx| {
2826 let abs_path = workspace.update(cx, |workspace, cx| {
2827 let relative_to = workspace
2828 .most_recent_active_path(cx)
2829 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2830 .or_else(|| {
2831 let project = workspace.project.read(cx);
2832 project.visible_worktrees(cx).find_map(|worktree| {
2833 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2834 })
2835 })
2836 .or_else(std::env::home_dir)
2837 .unwrap_or_else(|| PathBuf::from(""));
2838 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2839 })?;
2840 let abs_path = match abs_path.await? {
2841 Ok(path) => path,
2842 Err(err) => {
2843 let rx = workspace.update_in(cx, |workspace, window, cx| {
2844 workspace.show_portal_error(err.to_string(), cx);
2845
2846 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2847 let rx = prompt(workspace, lister, suggested_name, window, cx);
2848 workspace.on_prompt_for_new_path = Some(prompt);
2849 rx
2850 })?;
2851 if let Ok(path) = rx.await {
2852 tx.send(path).ok();
2853 }
2854 return anyhow::Ok(());
2855 }
2856 };
2857
2858 tx.send(abs_path.map(|path| vec![path])).ok();
2859 anyhow::Ok(())
2860 })
2861 .detach();
2862
2863 rx
2864 }
2865
2866 pub fn titlebar_item(&self) -> Option<AnyView> {
2867 self.titlebar_item.clone()
2868 }
2869
2870 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2871 /// When set, git-related operations should use this worktree instead of deriving
2872 /// the active worktree from the focused file.
2873 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2874 self.active_worktree_override
2875 }
2876
2877 pub fn set_active_worktree_override(
2878 &mut self,
2879 worktree_id: Option<WorktreeId>,
2880 cx: &mut Context<Self>,
2881 ) {
2882 self.active_worktree_override = worktree_id;
2883 cx.notify();
2884 }
2885
2886 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2887 self.active_worktree_override = None;
2888 cx.notify();
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_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 if self.project.read(cx).is_local() {
2906 Task::ready(Ok(callback(self, window, cx)))
2907 } else {
2908 let env = self.project.read(cx).cli_environment(cx);
2909 let task = Self::new_local(
2910 Vec::new(),
2911 self.app_state.clone(),
2912 None,
2913 env,
2914 None,
2915 true,
2916 cx,
2917 );
2918 cx.spawn_in(window, async move |_vh, cx| {
2919 let OpenResult {
2920 window: multi_workspace_window,
2921 ..
2922 } = task.await?;
2923 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2924 let workspace = multi_workspace.workspace().clone();
2925 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2926 })
2927 })
2928 }
2929 }
2930
2931 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2932 ///
2933 /// If the given workspace has a local project, then it will be passed
2934 /// to the callback. Otherwise, a new empty window will be created.
2935 pub fn with_local_or_wsl_workspace<T, F>(
2936 &mut self,
2937 window: &mut Window,
2938 cx: &mut Context<Self>,
2939 callback: F,
2940 ) -> Task<Result<T>>
2941 where
2942 T: 'static,
2943 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2944 {
2945 let project = self.project.read(cx);
2946 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
2947 Task::ready(Ok(callback(self, window, cx)))
2948 } else {
2949 let env = self.project.read(cx).cli_environment(cx);
2950 let task = Self::new_local(
2951 Vec::new(),
2952 self.app_state.clone(),
2953 None,
2954 env,
2955 None,
2956 true,
2957 cx,
2958 );
2959 cx.spawn_in(window, async move |_vh, cx| {
2960 let OpenResult {
2961 window: multi_workspace_window,
2962 ..
2963 } = task.await?;
2964 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2965 let workspace = multi_workspace.workspace().clone();
2966 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2967 })
2968 })
2969 }
2970 }
2971
2972 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2973 self.project.read(cx).worktrees(cx)
2974 }
2975
2976 pub fn visible_worktrees<'a>(
2977 &self,
2978 cx: &'a App,
2979 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2980 self.project.read(cx).visible_worktrees(cx)
2981 }
2982
2983 #[cfg(any(test, feature = "test-support"))]
2984 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
2985 let futures = self
2986 .worktrees(cx)
2987 .filter_map(|worktree| worktree.read(cx).as_local())
2988 .map(|worktree| worktree.scan_complete())
2989 .collect::<Vec<_>>();
2990 async move {
2991 for future in futures {
2992 future.await;
2993 }
2994 }
2995 }
2996
2997 pub fn close_global(cx: &mut App) {
2998 cx.defer(|cx| {
2999 cx.windows().iter().find(|window| {
3000 window
3001 .update(cx, |_, window, _| {
3002 if window.is_window_active() {
3003 //This can only get called when the window's project connection has been lost
3004 //so we don't need to prompt the user for anything and instead just close the window
3005 window.remove_window();
3006 true
3007 } else {
3008 false
3009 }
3010 })
3011 .unwrap_or(false)
3012 });
3013 });
3014 }
3015
3016 pub fn move_focused_panel_to_next_position(
3017 &mut self,
3018 _: &MoveFocusedPanelToNextPosition,
3019 window: &mut Window,
3020 cx: &mut Context<Self>,
3021 ) {
3022 let docks = self.all_docks();
3023 let active_dock = docks
3024 .into_iter()
3025 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
3026
3027 if let Some(dock) = active_dock {
3028 dock.update(cx, |dock, cx| {
3029 let active_panel = dock
3030 .active_panel()
3031 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
3032
3033 if let Some(panel) = active_panel {
3034 panel.move_to_next_position(window, cx);
3035 }
3036 })
3037 }
3038 }
3039
3040 pub fn prepare_to_close(
3041 &mut self,
3042 close_intent: CloseIntent,
3043 window: &mut Window,
3044 cx: &mut Context<Self>,
3045 ) -> Task<Result<bool>> {
3046 let active_call = self.active_global_call();
3047
3048 cx.spawn_in(window, async move |this, cx| {
3049 this.update(cx, |this, _| {
3050 if close_intent == CloseIntent::CloseWindow {
3051 this.removing = true;
3052 }
3053 })?;
3054
3055 let workspace_count = cx.update(|_window, cx| {
3056 cx.windows()
3057 .iter()
3058 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
3059 .count()
3060 })?;
3061
3062 #[cfg(target_os = "macos")]
3063 let save_last_workspace = false;
3064
3065 // On Linux and Windows, closing the last window should restore the last workspace.
3066 #[cfg(not(target_os = "macos"))]
3067 let save_last_workspace = {
3068 let remaining_workspaces = cx.update(|_window, cx| {
3069 cx.windows()
3070 .iter()
3071 .filter_map(|window| window.downcast::<MultiWorkspace>())
3072 .filter_map(|multi_workspace| {
3073 multi_workspace
3074 .update(cx, |multi_workspace, _, cx| {
3075 multi_workspace.workspace().read(cx).removing
3076 })
3077 .ok()
3078 })
3079 .filter(|removing| !removing)
3080 .count()
3081 })?;
3082
3083 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
3084 };
3085
3086 if let Some(active_call) = active_call
3087 && workspace_count == 1
3088 && cx
3089 .update(|_window, cx| active_call.0.is_in_room(cx))
3090 .unwrap_or(false)
3091 {
3092 if close_intent == CloseIntent::CloseWindow {
3093 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
3094 let answer = cx.update(|window, cx| {
3095 window.prompt(
3096 PromptLevel::Warning,
3097 "Do you want to leave the current call?",
3098 None,
3099 &["Close window and hang up", "Cancel"],
3100 cx,
3101 )
3102 })?;
3103
3104 if answer.await.log_err() == Some(1) {
3105 return anyhow::Ok(false);
3106 } else {
3107 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
3108 task.await.log_err();
3109 }
3110 }
3111 }
3112 if close_intent == CloseIntent::ReplaceWindow {
3113 _ = cx.update(|_window, cx| {
3114 let multi_workspace = cx
3115 .windows()
3116 .iter()
3117 .filter_map(|window| window.downcast::<MultiWorkspace>())
3118 .next()
3119 .unwrap();
3120 let project = multi_workspace
3121 .read(cx)?
3122 .workspace()
3123 .read(cx)
3124 .project
3125 .clone();
3126 if project.read(cx).is_shared() {
3127 active_call.0.unshare_project(project, cx)?;
3128 }
3129 Ok::<_, anyhow::Error>(())
3130 });
3131 }
3132 }
3133
3134 let save_result = this
3135 .update_in(cx, |this, window, cx| {
3136 this.save_all_internal(SaveIntent::Close, window, cx)
3137 })?
3138 .await;
3139
3140 // If we're not quitting, but closing, we remove the workspace from
3141 // the current session.
3142 if close_intent != CloseIntent::Quit
3143 && !save_last_workspace
3144 && save_result.as_ref().is_ok_and(|&res| res)
3145 {
3146 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
3147 .await;
3148 }
3149
3150 save_result
3151 })
3152 }
3153
3154 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
3155 self.save_all_internal(
3156 action.save_intent.unwrap_or(SaveIntent::SaveAll),
3157 window,
3158 cx,
3159 )
3160 .detach_and_log_err(cx);
3161 }
3162
3163 fn send_keystrokes(
3164 &mut self,
3165 action: &SendKeystrokes,
3166 window: &mut Window,
3167 cx: &mut Context<Self>,
3168 ) {
3169 let keystrokes: Vec<Keystroke> = action
3170 .0
3171 .split(' ')
3172 .flat_map(|k| Keystroke::parse(k).log_err())
3173 .map(|k| {
3174 cx.keyboard_mapper()
3175 .map_key_equivalent(k, false)
3176 .inner()
3177 .clone()
3178 })
3179 .collect();
3180 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
3181 }
3182
3183 pub fn send_keystrokes_impl(
3184 &mut self,
3185 keystrokes: Vec<Keystroke>,
3186 window: &mut Window,
3187 cx: &mut Context<Self>,
3188 ) -> Shared<Task<()>> {
3189 let mut state = self.dispatching_keystrokes.borrow_mut();
3190 if !state.dispatched.insert(keystrokes.clone()) {
3191 cx.propagate();
3192 return state.task.clone().unwrap();
3193 }
3194
3195 state.queue.extend(keystrokes);
3196
3197 let keystrokes = self.dispatching_keystrokes.clone();
3198 if state.task.is_none() {
3199 state.task = Some(
3200 window
3201 .spawn(cx, async move |cx| {
3202 // limit to 100 keystrokes to avoid infinite recursion.
3203 for _ in 0..100 {
3204 let keystroke = {
3205 let mut state = keystrokes.borrow_mut();
3206 let Some(keystroke) = state.queue.pop_front() else {
3207 state.dispatched.clear();
3208 state.task.take();
3209 return;
3210 };
3211 keystroke
3212 };
3213 cx.update(|window, cx| {
3214 let focused = window.focused(cx);
3215 window.dispatch_keystroke(keystroke.clone(), cx);
3216 if window.focused(cx) != focused {
3217 // dispatch_keystroke may cause the focus to change.
3218 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
3219 // And we need that to happen before the next keystroke to keep vim mode happy...
3220 // (Note that the tests always do this implicitly, so you must manually test with something like:
3221 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
3222 // )
3223 window.draw(cx).clear();
3224 }
3225 })
3226 .ok();
3227
3228 // Yield between synthetic keystrokes so deferred focus and
3229 // other effects can settle before dispatching the next key.
3230 yield_now().await;
3231 }
3232
3233 *keystrokes.borrow_mut() = Default::default();
3234 log::error!("over 100 keystrokes passed to send_keystrokes");
3235 })
3236 .shared(),
3237 );
3238 }
3239 state.task.clone().unwrap()
3240 }
3241
3242 fn save_all_internal(
3243 &mut self,
3244 mut save_intent: SaveIntent,
3245 window: &mut Window,
3246 cx: &mut Context<Self>,
3247 ) -> Task<Result<bool>> {
3248 if self.project.read(cx).is_disconnected(cx) {
3249 return Task::ready(Ok(true));
3250 }
3251 let dirty_items = self
3252 .panes
3253 .iter()
3254 .flat_map(|pane| {
3255 pane.read(cx).items().filter_map(|item| {
3256 if item.is_dirty(cx) {
3257 item.tab_content_text(0, cx);
3258 Some((pane.downgrade(), item.boxed_clone()))
3259 } else {
3260 None
3261 }
3262 })
3263 })
3264 .collect::<Vec<_>>();
3265
3266 let project = self.project.clone();
3267 cx.spawn_in(window, async move |workspace, cx| {
3268 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3269 let (serialize_tasks, remaining_dirty_items) =
3270 workspace.update_in(cx, |workspace, window, cx| {
3271 let mut remaining_dirty_items = Vec::new();
3272 let mut serialize_tasks = Vec::new();
3273 for (pane, item) in dirty_items {
3274 if let Some(task) = item
3275 .to_serializable_item_handle(cx)
3276 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3277 {
3278 serialize_tasks.push(task);
3279 } else {
3280 remaining_dirty_items.push((pane, item));
3281 }
3282 }
3283 (serialize_tasks, remaining_dirty_items)
3284 })?;
3285
3286 futures::future::try_join_all(serialize_tasks).await?;
3287
3288 if !remaining_dirty_items.is_empty() {
3289 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3290 }
3291
3292 if remaining_dirty_items.len() > 1 {
3293 let answer = workspace.update_in(cx, |_, window, cx| {
3294 let detail = Pane::file_names_for_prompt(
3295 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3296 cx,
3297 );
3298 window.prompt(
3299 PromptLevel::Warning,
3300 "Do you want to save all changes in the following files?",
3301 Some(&detail),
3302 &["Save all", "Discard all", "Cancel"],
3303 cx,
3304 )
3305 })?;
3306 match answer.await.log_err() {
3307 Some(0) => save_intent = SaveIntent::SaveAll,
3308 Some(1) => save_intent = SaveIntent::Skip,
3309 Some(2) => return Ok(false),
3310 _ => {}
3311 }
3312 }
3313
3314 remaining_dirty_items
3315 } else {
3316 dirty_items
3317 };
3318
3319 for (pane, item) in dirty_items {
3320 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3321 (
3322 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3323 item.project_entry_ids(cx),
3324 )
3325 })?;
3326 if (singleton || !project_entry_ids.is_empty())
3327 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3328 {
3329 return Ok(false);
3330 }
3331 }
3332 Ok(true)
3333 })
3334 }
3335
3336 pub fn open_workspace_for_paths(
3337 &mut self,
3338 replace_current_window: bool,
3339 paths: Vec<PathBuf>,
3340 window: &mut Window,
3341 cx: &mut Context<Self>,
3342 ) -> Task<Result<Entity<Workspace>>> {
3343 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
3344 let is_remote = self.project.read(cx).is_via_collab();
3345 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3346 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3347
3348 let window_to_replace = if replace_current_window {
3349 window_handle
3350 } else if is_remote || has_worktree || has_dirty_items {
3351 None
3352 } else {
3353 window_handle
3354 };
3355 let app_state = self.app_state.clone();
3356
3357 cx.spawn(async move |_, cx| {
3358 let OpenResult { workspace, .. } = cx
3359 .update(|cx| {
3360 open_paths(
3361 &paths,
3362 app_state,
3363 OpenOptions {
3364 replace_window: window_to_replace,
3365 ..Default::default()
3366 },
3367 cx,
3368 )
3369 })
3370 .await?;
3371 Ok(workspace)
3372 })
3373 }
3374
3375 #[allow(clippy::type_complexity)]
3376 pub fn open_paths(
3377 &mut self,
3378 mut abs_paths: Vec<PathBuf>,
3379 options: OpenOptions,
3380 pane: Option<WeakEntity<Pane>>,
3381 window: &mut Window,
3382 cx: &mut Context<Self>,
3383 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3384 let fs = self.app_state.fs.clone();
3385
3386 let caller_ordered_abs_paths = abs_paths.clone();
3387
3388 // Sort the paths to ensure we add worktrees for parents before their children.
3389 abs_paths.sort_unstable();
3390 cx.spawn_in(window, async move |this, cx| {
3391 let mut tasks = Vec::with_capacity(abs_paths.len());
3392
3393 for abs_path in &abs_paths {
3394 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3395 OpenVisible::All => Some(true),
3396 OpenVisible::None => Some(false),
3397 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3398 Some(Some(metadata)) => Some(!metadata.is_dir),
3399 Some(None) => Some(true),
3400 None => None,
3401 },
3402 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3403 Some(Some(metadata)) => Some(metadata.is_dir),
3404 Some(None) => Some(false),
3405 None => None,
3406 },
3407 };
3408 let project_path = match visible {
3409 Some(visible) => match this
3410 .update(cx, |this, cx| {
3411 Workspace::project_path_for_path(
3412 this.project.clone(),
3413 abs_path,
3414 visible,
3415 cx,
3416 )
3417 })
3418 .log_err()
3419 {
3420 Some(project_path) => project_path.await.log_err(),
3421 None => None,
3422 },
3423 None => None,
3424 };
3425
3426 let this = this.clone();
3427 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3428 let fs = fs.clone();
3429 let pane = pane.clone();
3430 let task = cx.spawn(async move |cx| {
3431 let (_worktree, project_path) = project_path?;
3432 if fs.is_dir(&abs_path).await {
3433 // Opening a directory should not race to update the active entry.
3434 // We'll select/reveal a deterministic final entry after all paths finish opening.
3435 None
3436 } else {
3437 Some(
3438 this.update_in(cx, |this, window, cx| {
3439 this.open_path(
3440 project_path,
3441 pane,
3442 options.focus.unwrap_or(true),
3443 window,
3444 cx,
3445 )
3446 })
3447 .ok()?
3448 .await,
3449 )
3450 }
3451 });
3452 tasks.push(task);
3453 }
3454
3455 let results = futures::future::join_all(tasks).await;
3456
3457 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3458 let mut winner: Option<(PathBuf, bool)> = None;
3459 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3460 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3461 if !metadata.is_dir {
3462 winner = Some((abs_path, false));
3463 break;
3464 }
3465 if winner.is_none() {
3466 winner = Some((abs_path, true));
3467 }
3468 } else if winner.is_none() {
3469 winner = Some((abs_path, false));
3470 }
3471 }
3472
3473 // Compute the winner entry id on the foreground thread and emit once, after all
3474 // paths finish opening. This avoids races between concurrently-opening paths
3475 // (directories in particular) and makes the resulting project panel selection
3476 // deterministic.
3477 if let Some((winner_abs_path, winner_is_dir)) = winner {
3478 'emit_winner: {
3479 let winner_abs_path: Arc<Path> =
3480 SanitizedPath::new(&winner_abs_path).as_path().into();
3481
3482 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3483 OpenVisible::All => true,
3484 OpenVisible::None => false,
3485 OpenVisible::OnlyFiles => !winner_is_dir,
3486 OpenVisible::OnlyDirectories => winner_is_dir,
3487 };
3488
3489 let Some(worktree_task) = this
3490 .update(cx, |workspace, cx| {
3491 workspace.project.update(cx, |project, cx| {
3492 project.find_or_create_worktree(
3493 winner_abs_path.as_ref(),
3494 visible,
3495 cx,
3496 )
3497 })
3498 })
3499 .ok()
3500 else {
3501 break 'emit_winner;
3502 };
3503
3504 let Ok((worktree, _)) = worktree_task.await else {
3505 break 'emit_winner;
3506 };
3507
3508 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3509 let worktree = worktree.read(cx);
3510 let worktree_abs_path = worktree.abs_path();
3511 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3512 worktree.root_entry()
3513 } else {
3514 winner_abs_path
3515 .strip_prefix(worktree_abs_path.as_ref())
3516 .ok()
3517 .and_then(|relative_path| {
3518 let relative_path =
3519 RelPath::new(relative_path, PathStyle::local())
3520 .log_err()?;
3521 worktree.entry_for_path(&relative_path)
3522 })
3523 }?;
3524 Some(entry.id)
3525 }) else {
3526 break 'emit_winner;
3527 };
3528
3529 this.update(cx, |workspace, cx| {
3530 workspace.project.update(cx, |_, cx| {
3531 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3532 });
3533 })
3534 .ok();
3535 }
3536 }
3537
3538 results
3539 })
3540 }
3541
3542 pub fn open_resolved_path(
3543 &mut self,
3544 path: ResolvedPath,
3545 window: &mut Window,
3546 cx: &mut Context<Self>,
3547 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3548 match path {
3549 ResolvedPath::ProjectPath { project_path, .. } => {
3550 self.open_path(project_path, None, true, window, cx)
3551 }
3552 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3553 PathBuf::from(path),
3554 OpenOptions {
3555 visible: Some(OpenVisible::None),
3556 ..Default::default()
3557 },
3558 window,
3559 cx,
3560 ),
3561 }
3562 }
3563
3564 pub fn absolute_path_of_worktree(
3565 &self,
3566 worktree_id: WorktreeId,
3567 cx: &mut Context<Self>,
3568 ) -> Option<PathBuf> {
3569 self.project
3570 .read(cx)
3571 .worktree_for_id(worktree_id, cx)
3572 // TODO: use `abs_path` or `root_dir`
3573 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3574 }
3575
3576 pub fn add_folder_to_project(
3577 &mut self,
3578 _: &AddFolderToProject,
3579 window: &mut Window,
3580 cx: &mut Context<Self>,
3581 ) {
3582 let project = self.project.read(cx);
3583 if project.is_via_collab() {
3584 self.show_error(
3585 &anyhow!("You cannot add folders to someone else's project"),
3586 cx,
3587 );
3588 return;
3589 }
3590 let paths = self.prompt_for_open_path(
3591 PathPromptOptions {
3592 files: false,
3593 directories: true,
3594 multiple: true,
3595 prompt: None,
3596 },
3597 DirectoryLister::Project(self.project.clone()),
3598 window,
3599 cx,
3600 );
3601 cx.spawn_in(window, async move |this, cx| {
3602 if let Some(paths) = paths.await.log_err().flatten() {
3603 let results = this
3604 .update_in(cx, |this, window, cx| {
3605 this.open_paths(
3606 paths,
3607 OpenOptions {
3608 visible: Some(OpenVisible::All),
3609 ..Default::default()
3610 },
3611 None,
3612 window,
3613 cx,
3614 )
3615 })?
3616 .await;
3617 for result in results.into_iter().flatten() {
3618 result.log_err();
3619 }
3620 }
3621 anyhow::Ok(())
3622 })
3623 .detach_and_log_err(cx);
3624 }
3625
3626 pub fn project_path_for_path(
3627 project: Entity<Project>,
3628 abs_path: &Path,
3629 visible: bool,
3630 cx: &mut App,
3631 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3632 let entry = project.update(cx, |project, cx| {
3633 project.find_or_create_worktree(abs_path, visible, cx)
3634 });
3635 cx.spawn(async move |cx| {
3636 let (worktree, path) = entry.await?;
3637 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3638 Ok((worktree, ProjectPath { worktree_id, path }))
3639 })
3640 }
3641
3642 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3643 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3644 }
3645
3646 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3647 self.items_of_type(cx).max_by_key(|item| item.item_id())
3648 }
3649
3650 pub fn items_of_type<'a, T: Item>(
3651 &'a self,
3652 cx: &'a App,
3653 ) -> impl 'a + Iterator<Item = Entity<T>> {
3654 self.panes
3655 .iter()
3656 .flat_map(|pane| pane.read(cx).items_of_type())
3657 }
3658
3659 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3660 self.active_pane().read(cx).active_item()
3661 }
3662
3663 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3664 let item = self.active_item(cx)?;
3665 item.to_any_view().downcast::<I>().ok()
3666 }
3667
3668 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3669 self.active_item(cx).and_then(|item| item.project_path(cx))
3670 }
3671
3672 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3673 self.recent_navigation_history_iter(cx)
3674 .filter_map(|(path, abs_path)| {
3675 let worktree = self
3676 .project
3677 .read(cx)
3678 .worktree_for_id(path.worktree_id, cx)?;
3679 if worktree.read(cx).is_visible() {
3680 abs_path
3681 } else {
3682 None
3683 }
3684 })
3685 .next()
3686 }
3687
3688 pub fn save_active_item(
3689 &mut self,
3690 save_intent: SaveIntent,
3691 window: &mut Window,
3692 cx: &mut App,
3693 ) -> Task<Result<()>> {
3694 let project = self.project.clone();
3695 let pane = self.active_pane();
3696 let item = pane.read(cx).active_item();
3697 let pane = pane.downgrade();
3698
3699 window.spawn(cx, async move |cx| {
3700 if let Some(item) = item {
3701 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3702 .await
3703 .map(|_| ())
3704 } else {
3705 Ok(())
3706 }
3707 })
3708 }
3709
3710 pub fn close_inactive_items_and_panes(
3711 &mut self,
3712 action: &CloseInactiveTabsAndPanes,
3713 window: &mut Window,
3714 cx: &mut Context<Self>,
3715 ) {
3716 if let Some(task) = self.close_all_internal(
3717 true,
3718 action.save_intent.unwrap_or(SaveIntent::Close),
3719 window,
3720 cx,
3721 ) {
3722 task.detach_and_log_err(cx)
3723 }
3724 }
3725
3726 pub fn close_all_items_and_panes(
3727 &mut self,
3728 action: &CloseAllItemsAndPanes,
3729 window: &mut Window,
3730 cx: &mut Context<Self>,
3731 ) {
3732 if let Some(task) = self.close_all_internal(
3733 false,
3734 action.save_intent.unwrap_or(SaveIntent::Close),
3735 window,
3736 cx,
3737 ) {
3738 task.detach_and_log_err(cx)
3739 }
3740 }
3741
3742 /// Closes the active item across all panes.
3743 pub fn close_item_in_all_panes(
3744 &mut self,
3745 action: &CloseItemInAllPanes,
3746 window: &mut Window,
3747 cx: &mut Context<Self>,
3748 ) {
3749 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3750 return;
3751 };
3752
3753 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3754 let close_pinned = action.close_pinned;
3755
3756 if let Some(project_path) = active_item.project_path(cx) {
3757 self.close_items_with_project_path(
3758 &project_path,
3759 save_intent,
3760 close_pinned,
3761 window,
3762 cx,
3763 );
3764 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3765 let item_id = active_item.item_id();
3766 self.active_pane().update(cx, |pane, cx| {
3767 pane.close_item_by_id(item_id, save_intent, window, cx)
3768 .detach_and_log_err(cx);
3769 });
3770 }
3771 }
3772
3773 /// Closes all items with the given project path across all panes.
3774 pub fn close_items_with_project_path(
3775 &mut self,
3776 project_path: &ProjectPath,
3777 save_intent: SaveIntent,
3778 close_pinned: bool,
3779 window: &mut Window,
3780 cx: &mut Context<Self>,
3781 ) {
3782 let panes = self.panes().to_vec();
3783 for pane in panes {
3784 pane.update(cx, |pane, cx| {
3785 pane.close_items_for_project_path(
3786 project_path,
3787 save_intent,
3788 close_pinned,
3789 window,
3790 cx,
3791 )
3792 .detach_and_log_err(cx);
3793 });
3794 }
3795 }
3796
3797 fn close_all_internal(
3798 &mut self,
3799 retain_active_pane: bool,
3800 save_intent: SaveIntent,
3801 window: &mut Window,
3802 cx: &mut Context<Self>,
3803 ) -> Option<Task<Result<()>>> {
3804 let current_pane = self.active_pane();
3805
3806 let mut tasks = Vec::new();
3807
3808 if retain_active_pane {
3809 let current_pane_close = current_pane.update(cx, |pane, cx| {
3810 pane.close_other_items(
3811 &CloseOtherItems {
3812 save_intent: None,
3813 close_pinned: false,
3814 },
3815 None,
3816 window,
3817 cx,
3818 )
3819 });
3820
3821 tasks.push(current_pane_close);
3822 }
3823
3824 for pane in self.panes() {
3825 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3826 continue;
3827 }
3828
3829 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3830 pane.close_all_items(
3831 &CloseAllItems {
3832 save_intent: Some(save_intent),
3833 close_pinned: false,
3834 },
3835 window,
3836 cx,
3837 )
3838 });
3839
3840 tasks.push(close_pane_items)
3841 }
3842
3843 if tasks.is_empty() {
3844 None
3845 } else {
3846 Some(cx.spawn_in(window, async move |_, _| {
3847 for task in tasks {
3848 task.await?
3849 }
3850 Ok(())
3851 }))
3852 }
3853 }
3854
3855 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3856 self.dock_at_position(position).read(cx).is_open()
3857 }
3858
3859 pub fn toggle_dock(
3860 &mut self,
3861 dock_side: DockPosition,
3862 window: &mut Window,
3863 cx: &mut Context<Self>,
3864 ) {
3865 let mut focus_center = false;
3866 let mut reveal_dock = false;
3867
3868 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3869 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3870
3871 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3872 telemetry::event!(
3873 "Panel Button Clicked",
3874 name = panel.persistent_name(),
3875 toggle_state = !was_visible
3876 );
3877 }
3878 if was_visible {
3879 self.save_open_dock_positions(cx);
3880 }
3881
3882 let dock = self.dock_at_position(dock_side);
3883 dock.update(cx, |dock, cx| {
3884 dock.set_open(!was_visible, window, cx);
3885
3886 if dock.active_panel().is_none() {
3887 let Some(panel_ix) = dock
3888 .first_enabled_panel_idx(cx)
3889 .log_with_level(log::Level::Info)
3890 else {
3891 return;
3892 };
3893 dock.activate_panel(panel_ix, window, cx);
3894 }
3895
3896 if let Some(active_panel) = dock.active_panel() {
3897 if was_visible {
3898 if active_panel
3899 .panel_focus_handle(cx)
3900 .contains_focused(window, cx)
3901 {
3902 focus_center = true;
3903 }
3904 } else {
3905 let focus_handle = &active_panel.panel_focus_handle(cx);
3906 window.focus(focus_handle, cx);
3907 reveal_dock = true;
3908 }
3909 }
3910 });
3911
3912 if reveal_dock {
3913 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3914 }
3915
3916 if focus_center {
3917 self.active_pane
3918 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3919 }
3920
3921 cx.notify();
3922 self.serialize_workspace(window, cx);
3923 }
3924
3925 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3926 self.all_docks().into_iter().find(|&dock| {
3927 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3928 })
3929 }
3930
3931 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3932 if let Some(dock) = self.active_dock(window, cx).cloned() {
3933 self.save_open_dock_positions(cx);
3934 dock.update(cx, |dock, cx| {
3935 dock.set_open(false, window, cx);
3936 });
3937 return true;
3938 }
3939 false
3940 }
3941
3942 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3943 self.save_open_dock_positions(cx);
3944 for dock in self.all_docks() {
3945 dock.update(cx, |dock, cx| {
3946 dock.set_open(false, window, cx);
3947 });
3948 }
3949
3950 cx.focus_self(window);
3951 cx.notify();
3952 self.serialize_workspace(window, cx);
3953 }
3954
3955 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
3956 self.all_docks()
3957 .into_iter()
3958 .filter_map(|dock| {
3959 let dock_ref = dock.read(cx);
3960 if dock_ref.is_open() {
3961 Some(dock_ref.position())
3962 } else {
3963 None
3964 }
3965 })
3966 .collect()
3967 }
3968
3969 /// Saves the positions of currently open docks.
3970 ///
3971 /// Updates `last_open_dock_positions` with positions of all currently open
3972 /// docks, to later be restored by the 'Toggle All Docks' action.
3973 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
3974 let open_dock_positions = self.get_open_dock_positions(cx);
3975 if !open_dock_positions.is_empty() {
3976 self.last_open_dock_positions = open_dock_positions;
3977 }
3978 }
3979
3980 /// Toggles all docks between open and closed states.
3981 ///
3982 /// If any docks are open, closes all and remembers their positions. If all
3983 /// docks are closed, restores the last remembered dock configuration.
3984 fn toggle_all_docks(
3985 &mut self,
3986 _: &ToggleAllDocks,
3987 window: &mut Window,
3988 cx: &mut Context<Self>,
3989 ) {
3990 let open_dock_positions = self.get_open_dock_positions(cx);
3991
3992 if !open_dock_positions.is_empty() {
3993 self.close_all_docks(window, cx);
3994 } else if !self.last_open_dock_positions.is_empty() {
3995 self.restore_last_open_docks(window, cx);
3996 }
3997 }
3998
3999 /// Reopens docks from the most recently remembered configuration.
4000 ///
4001 /// Opens all docks whose positions are stored in `last_open_dock_positions`
4002 /// and clears the stored positions.
4003 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4004 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
4005
4006 for position in positions_to_open {
4007 let dock = self.dock_at_position(position);
4008 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
4009 }
4010
4011 cx.focus_self(window);
4012 cx.notify();
4013 self.serialize_workspace(window, cx);
4014 }
4015
4016 /// Transfer focus to the panel of the given type.
4017 pub fn focus_panel<T: Panel>(
4018 &mut self,
4019 window: &mut Window,
4020 cx: &mut Context<Self>,
4021 ) -> Option<Entity<T>> {
4022 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
4023 panel.to_any().downcast().ok()
4024 }
4025
4026 /// Focus the panel of the given type if it isn't already focused. If it is
4027 /// already focused, then transfer focus back to the workspace center.
4028 /// When the `close_panel_on_toggle` setting is enabled, also closes the
4029 /// panel when transferring focus back to the center.
4030 pub fn toggle_panel_focus<T: Panel>(
4031 &mut self,
4032 window: &mut Window,
4033 cx: &mut Context<Self>,
4034 ) -> bool {
4035 let mut did_focus_panel = false;
4036 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
4037 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
4038 did_focus_panel
4039 });
4040
4041 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
4042 self.close_panel::<T>(window, cx);
4043 }
4044
4045 telemetry::event!(
4046 "Panel Button Clicked",
4047 name = T::persistent_name(),
4048 toggle_state = did_focus_panel
4049 );
4050
4051 did_focus_panel
4052 }
4053
4054 pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4055 if let Some(item) = self.active_item(cx) {
4056 item.item_focus_handle(cx).focus(window, cx);
4057 } else {
4058 log::error!("Could not find a focus target when switching focus to the center panes",);
4059 }
4060 }
4061
4062 pub fn activate_panel_for_proto_id(
4063 &mut self,
4064 panel_id: PanelId,
4065 window: &mut Window,
4066 cx: &mut Context<Self>,
4067 ) -> Option<Arc<dyn PanelHandle>> {
4068 let mut panel = None;
4069 for dock in self.all_docks() {
4070 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
4071 panel = dock.update(cx, |dock, cx| {
4072 dock.activate_panel(panel_index, window, cx);
4073 dock.set_open(true, window, cx);
4074 dock.active_panel().cloned()
4075 });
4076 break;
4077 }
4078 }
4079
4080 if panel.is_some() {
4081 cx.notify();
4082 self.serialize_workspace(window, cx);
4083 }
4084
4085 panel
4086 }
4087
4088 /// Focus or unfocus the given panel type, depending on the given callback.
4089 fn focus_or_unfocus_panel<T: Panel>(
4090 &mut self,
4091 window: &mut Window,
4092 cx: &mut Context<Self>,
4093 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
4094 ) -> Option<Arc<dyn PanelHandle>> {
4095 let mut result_panel = None;
4096 let mut serialize = false;
4097 for dock in self.all_docks() {
4098 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4099 let mut focus_center = false;
4100 let panel = dock.update(cx, |dock, cx| {
4101 dock.activate_panel(panel_index, window, cx);
4102
4103 let panel = dock.active_panel().cloned();
4104 if let Some(panel) = panel.as_ref() {
4105 if should_focus(&**panel, window, cx) {
4106 dock.set_open(true, window, cx);
4107 panel.panel_focus_handle(cx).focus(window, cx);
4108 } else {
4109 focus_center = true;
4110 }
4111 }
4112 panel
4113 });
4114
4115 if focus_center {
4116 self.active_pane
4117 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4118 }
4119
4120 result_panel = panel;
4121 serialize = true;
4122 break;
4123 }
4124 }
4125
4126 if serialize {
4127 self.serialize_workspace(window, cx);
4128 }
4129
4130 cx.notify();
4131 result_panel
4132 }
4133
4134 /// Open the panel of the given type
4135 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4136 for dock in self.all_docks() {
4137 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4138 dock.update(cx, |dock, cx| {
4139 dock.activate_panel(panel_index, window, cx);
4140 dock.set_open(true, window, cx);
4141 });
4142 }
4143 }
4144 }
4145
4146 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
4147 for dock in self.all_docks().iter() {
4148 dock.update(cx, |dock, cx| {
4149 if dock.panel::<T>().is_some() {
4150 dock.set_open(false, window, cx)
4151 }
4152 })
4153 }
4154 }
4155
4156 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
4157 self.all_docks()
4158 .iter()
4159 .find_map(|dock| dock.read(cx).panel::<T>())
4160 }
4161
4162 fn dismiss_zoomed_items_to_reveal(
4163 &mut self,
4164 dock_to_reveal: Option<DockPosition>,
4165 window: &mut Window,
4166 cx: &mut Context<Self>,
4167 ) {
4168 // If a center pane is zoomed, unzoom it.
4169 for pane in &self.panes {
4170 if pane != &self.active_pane || dock_to_reveal.is_some() {
4171 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4172 }
4173 }
4174
4175 // If another dock is zoomed, hide it.
4176 let mut focus_center = false;
4177 for dock in self.all_docks() {
4178 dock.update(cx, |dock, cx| {
4179 if Some(dock.position()) != dock_to_reveal
4180 && let Some(panel) = dock.active_panel()
4181 && panel.is_zoomed(window, cx)
4182 {
4183 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
4184 dock.set_open(false, window, cx);
4185 }
4186 });
4187 }
4188
4189 if focus_center {
4190 self.active_pane
4191 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4192 }
4193
4194 if self.zoomed_position != dock_to_reveal {
4195 self.zoomed = None;
4196 self.zoomed_position = None;
4197 cx.emit(Event::ZoomChanged);
4198 }
4199
4200 cx.notify();
4201 }
4202
4203 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4204 let pane = cx.new(|cx| {
4205 let mut pane = Pane::new(
4206 self.weak_handle(),
4207 self.project.clone(),
4208 self.pane_history_timestamp.clone(),
4209 None,
4210 NewFile.boxed_clone(),
4211 true,
4212 window,
4213 cx,
4214 );
4215 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
4216 pane
4217 });
4218 cx.subscribe_in(&pane, window, Self::handle_pane_event)
4219 .detach();
4220 self.panes.push(pane.clone());
4221
4222 window.focus(&pane.focus_handle(cx), cx);
4223
4224 cx.emit(Event::PaneAdded(pane.clone()));
4225 pane
4226 }
4227
4228 pub fn add_item_to_center(
4229 &mut self,
4230 item: Box<dyn ItemHandle>,
4231 window: &mut Window,
4232 cx: &mut Context<Self>,
4233 ) -> bool {
4234 if let Some(center_pane) = self.last_active_center_pane.clone() {
4235 if let Some(center_pane) = center_pane.upgrade() {
4236 center_pane.update(cx, |pane, cx| {
4237 pane.add_item(item, true, true, None, window, cx)
4238 });
4239 true
4240 } else {
4241 false
4242 }
4243 } else {
4244 false
4245 }
4246 }
4247
4248 pub fn add_item_to_active_pane(
4249 &mut self,
4250 item: Box<dyn ItemHandle>,
4251 destination_index: Option<usize>,
4252 focus_item: bool,
4253 window: &mut Window,
4254 cx: &mut App,
4255 ) {
4256 self.add_item(
4257 self.active_pane.clone(),
4258 item,
4259 destination_index,
4260 false,
4261 focus_item,
4262 window,
4263 cx,
4264 )
4265 }
4266
4267 pub fn add_item(
4268 &mut self,
4269 pane: Entity<Pane>,
4270 item: Box<dyn ItemHandle>,
4271 destination_index: Option<usize>,
4272 activate_pane: bool,
4273 focus_item: bool,
4274 window: &mut Window,
4275 cx: &mut App,
4276 ) {
4277 pane.update(cx, |pane, cx| {
4278 pane.add_item(
4279 item,
4280 activate_pane,
4281 focus_item,
4282 destination_index,
4283 window,
4284 cx,
4285 )
4286 });
4287 }
4288
4289 pub fn split_item(
4290 &mut self,
4291 split_direction: SplitDirection,
4292 item: Box<dyn ItemHandle>,
4293 window: &mut Window,
4294 cx: &mut Context<Self>,
4295 ) {
4296 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4297 self.add_item(new_pane, item, None, true, true, window, cx);
4298 }
4299
4300 pub fn open_abs_path(
4301 &mut self,
4302 abs_path: PathBuf,
4303 options: OpenOptions,
4304 window: &mut Window,
4305 cx: &mut Context<Self>,
4306 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4307 cx.spawn_in(window, async move |workspace, cx| {
4308 let open_paths_task_result = workspace
4309 .update_in(cx, |workspace, window, cx| {
4310 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4311 })
4312 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4313 .await;
4314 anyhow::ensure!(
4315 open_paths_task_result.len() == 1,
4316 "open abs path {abs_path:?} task returned incorrect number of results"
4317 );
4318 match open_paths_task_result
4319 .into_iter()
4320 .next()
4321 .expect("ensured single task result")
4322 {
4323 Some(open_result) => {
4324 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4325 }
4326 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4327 }
4328 })
4329 }
4330
4331 pub fn split_abs_path(
4332 &mut self,
4333 abs_path: PathBuf,
4334 visible: bool,
4335 window: &mut Window,
4336 cx: &mut Context<Self>,
4337 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4338 let project_path_task =
4339 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4340 cx.spawn_in(window, async move |this, cx| {
4341 let (_, path) = project_path_task.await?;
4342 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4343 .await
4344 })
4345 }
4346
4347 pub fn open_path(
4348 &mut self,
4349 path: impl Into<ProjectPath>,
4350 pane: Option<WeakEntity<Pane>>,
4351 focus_item: bool,
4352 window: &mut Window,
4353 cx: &mut App,
4354 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4355 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4356 }
4357
4358 pub fn open_path_preview(
4359 &mut self,
4360 path: impl Into<ProjectPath>,
4361 pane: Option<WeakEntity<Pane>>,
4362 focus_item: bool,
4363 allow_preview: bool,
4364 activate: bool,
4365 window: &mut Window,
4366 cx: &mut App,
4367 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4368 let pane = pane.unwrap_or_else(|| {
4369 self.last_active_center_pane.clone().unwrap_or_else(|| {
4370 self.panes
4371 .first()
4372 .expect("There must be an active pane")
4373 .downgrade()
4374 })
4375 });
4376
4377 let project_path = path.into();
4378 let task = self.load_path(project_path.clone(), window, cx);
4379 window.spawn(cx, async move |cx| {
4380 let (project_entry_id, build_item) = task.await?;
4381
4382 pane.update_in(cx, |pane, window, cx| {
4383 pane.open_item(
4384 project_entry_id,
4385 project_path,
4386 focus_item,
4387 allow_preview,
4388 activate,
4389 None,
4390 window,
4391 cx,
4392 build_item,
4393 )
4394 })
4395 })
4396 }
4397
4398 pub fn split_path(
4399 &mut self,
4400 path: impl Into<ProjectPath>,
4401 window: &mut Window,
4402 cx: &mut Context<Self>,
4403 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4404 self.split_path_preview(path, false, None, window, cx)
4405 }
4406
4407 pub fn split_path_preview(
4408 &mut self,
4409 path: impl Into<ProjectPath>,
4410 allow_preview: bool,
4411 split_direction: Option<SplitDirection>,
4412 window: &mut Window,
4413 cx: &mut Context<Self>,
4414 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4415 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4416 self.panes
4417 .first()
4418 .expect("There must be an active pane")
4419 .downgrade()
4420 });
4421
4422 if let Member::Pane(center_pane) = &self.center.root
4423 && center_pane.read(cx).items_len() == 0
4424 {
4425 return self.open_path(path, Some(pane), true, window, cx);
4426 }
4427
4428 let project_path = path.into();
4429 let task = self.load_path(project_path.clone(), window, cx);
4430 cx.spawn_in(window, async move |this, cx| {
4431 let (project_entry_id, build_item) = task.await?;
4432 this.update_in(cx, move |this, window, cx| -> Option<_> {
4433 let pane = pane.upgrade()?;
4434 let new_pane = this.split_pane(
4435 pane,
4436 split_direction.unwrap_or(SplitDirection::Right),
4437 window,
4438 cx,
4439 );
4440 new_pane.update(cx, |new_pane, cx| {
4441 Some(new_pane.open_item(
4442 project_entry_id,
4443 project_path,
4444 true,
4445 allow_preview,
4446 true,
4447 None,
4448 window,
4449 cx,
4450 build_item,
4451 ))
4452 })
4453 })
4454 .map(|option| option.context("pane was dropped"))?
4455 })
4456 }
4457
4458 fn load_path(
4459 &mut self,
4460 path: ProjectPath,
4461 window: &mut Window,
4462 cx: &mut App,
4463 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4464 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4465 registry.open_path(self.project(), &path, window, cx)
4466 }
4467
4468 pub fn find_project_item<T>(
4469 &self,
4470 pane: &Entity<Pane>,
4471 project_item: &Entity<T::Item>,
4472 cx: &App,
4473 ) -> Option<Entity<T>>
4474 where
4475 T: ProjectItem,
4476 {
4477 use project::ProjectItem as _;
4478 let project_item = project_item.read(cx);
4479 let entry_id = project_item.entry_id(cx);
4480 let project_path = project_item.project_path(cx);
4481
4482 let mut item = None;
4483 if let Some(entry_id) = entry_id {
4484 item = pane.read(cx).item_for_entry(entry_id, cx);
4485 }
4486 if item.is_none()
4487 && let Some(project_path) = project_path
4488 {
4489 item = pane.read(cx).item_for_path(project_path, cx);
4490 }
4491
4492 item.and_then(|item| item.downcast::<T>())
4493 }
4494
4495 pub fn is_project_item_open<T>(
4496 &self,
4497 pane: &Entity<Pane>,
4498 project_item: &Entity<T::Item>,
4499 cx: &App,
4500 ) -> bool
4501 where
4502 T: ProjectItem,
4503 {
4504 self.find_project_item::<T>(pane, project_item, cx)
4505 .is_some()
4506 }
4507
4508 pub fn open_project_item<T>(
4509 &mut self,
4510 pane: Entity<Pane>,
4511 project_item: Entity<T::Item>,
4512 activate_pane: bool,
4513 focus_item: bool,
4514 keep_old_preview: bool,
4515 allow_new_preview: bool,
4516 window: &mut Window,
4517 cx: &mut Context<Self>,
4518 ) -> Entity<T>
4519 where
4520 T: ProjectItem,
4521 {
4522 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4523
4524 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4525 if !keep_old_preview
4526 && let Some(old_id) = old_item_id
4527 && old_id != item.item_id()
4528 {
4529 // switching to a different item, so unpreview old active item
4530 pane.update(cx, |pane, _| {
4531 pane.unpreview_item_if_preview(old_id);
4532 });
4533 }
4534
4535 self.activate_item(&item, activate_pane, focus_item, window, cx);
4536 if !allow_new_preview {
4537 pane.update(cx, |pane, _| {
4538 pane.unpreview_item_if_preview(item.item_id());
4539 });
4540 }
4541 return item;
4542 }
4543
4544 let item = pane.update(cx, |pane, cx| {
4545 cx.new(|cx| {
4546 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4547 })
4548 });
4549 let mut destination_index = None;
4550 pane.update(cx, |pane, cx| {
4551 if !keep_old_preview && let Some(old_id) = old_item_id {
4552 pane.unpreview_item_if_preview(old_id);
4553 }
4554 if allow_new_preview {
4555 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4556 }
4557 });
4558
4559 self.add_item(
4560 pane,
4561 Box::new(item.clone()),
4562 destination_index,
4563 activate_pane,
4564 focus_item,
4565 window,
4566 cx,
4567 );
4568 item
4569 }
4570
4571 pub fn open_shared_screen(
4572 &mut self,
4573 peer_id: PeerId,
4574 window: &mut Window,
4575 cx: &mut Context<Self>,
4576 ) {
4577 if let Some(shared_screen) =
4578 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4579 {
4580 self.active_pane.update(cx, |pane, cx| {
4581 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4582 });
4583 }
4584 }
4585
4586 pub fn activate_item(
4587 &mut self,
4588 item: &dyn ItemHandle,
4589 activate_pane: bool,
4590 focus_item: bool,
4591 window: &mut Window,
4592 cx: &mut App,
4593 ) -> bool {
4594 let result = self.panes.iter().find_map(|pane| {
4595 pane.read(cx)
4596 .index_for_item(item)
4597 .map(|ix| (pane.clone(), ix))
4598 });
4599 if let Some((pane, ix)) = result {
4600 pane.update(cx, |pane, cx| {
4601 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4602 });
4603 true
4604 } else {
4605 false
4606 }
4607 }
4608
4609 fn activate_pane_at_index(
4610 &mut self,
4611 action: &ActivatePane,
4612 window: &mut Window,
4613 cx: &mut Context<Self>,
4614 ) {
4615 let panes = self.center.panes();
4616 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4617 window.focus(&pane.focus_handle(cx), cx);
4618 } else {
4619 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4620 .detach();
4621 }
4622 }
4623
4624 fn move_item_to_pane_at_index(
4625 &mut self,
4626 action: &MoveItemToPane,
4627 window: &mut Window,
4628 cx: &mut Context<Self>,
4629 ) {
4630 let panes = self.center.panes();
4631 let destination = match panes.get(action.destination) {
4632 Some(&destination) => destination.clone(),
4633 None => {
4634 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4635 return;
4636 }
4637 let direction = SplitDirection::Right;
4638 let split_off_pane = self
4639 .find_pane_in_direction(direction, cx)
4640 .unwrap_or_else(|| self.active_pane.clone());
4641 let new_pane = self.add_pane(window, cx);
4642 self.center.split(&split_off_pane, &new_pane, direction, cx);
4643 new_pane
4644 }
4645 };
4646
4647 if action.clone {
4648 if self
4649 .active_pane
4650 .read(cx)
4651 .active_item()
4652 .is_some_and(|item| item.can_split(cx))
4653 {
4654 clone_active_item(
4655 self.database_id(),
4656 &self.active_pane,
4657 &destination,
4658 action.focus,
4659 window,
4660 cx,
4661 );
4662 return;
4663 }
4664 }
4665 move_active_item(
4666 &self.active_pane,
4667 &destination,
4668 action.focus,
4669 true,
4670 window,
4671 cx,
4672 )
4673 }
4674
4675 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4676 let panes = self.center.panes();
4677 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4678 let next_ix = (ix + 1) % panes.len();
4679 let next_pane = panes[next_ix].clone();
4680 window.focus(&next_pane.focus_handle(cx), cx);
4681 }
4682 }
4683
4684 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4685 let panes = self.center.panes();
4686 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4687 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4688 let prev_pane = panes[prev_ix].clone();
4689 window.focus(&prev_pane.focus_handle(cx), cx);
4690 }
4691 }
4692
4693 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4694 let last_pane = self.center.last_pane();
4695 window.focus(&last_pane.focus_handle(cx), cx);
4696 }
4697
4698 pub fn activate_pane_in_direction(
4699 &mut self,
4700 direction: SplitDirection,
4701 window: &mut Window,
4702 cx: &mut App,
4703 ) {
4704 use ActivateInDirectionTarget as Target;
4705 enum Origin {
4706 Sidebar,
4707 LeftDock,
4708 RightDock,
4709 BottomDock,
4710 Center,
4711 }
4712
4713 let origin: Origin = if self
4714 .sidebar_focus_handle
4715 .as_ref()
4716 .is_some_and(|h| h.contains_focused(window, cx))
4717 {
4718 Origin::Sidebar
4719 } else {
4720 [
4721 (&self.left_dock, Origin::LeftDock),
4722 (&self.right_dock, Origin::RightDock),
4723 (&self.bottom_dock, Origin::BottomDock),
4724 ]
4725 .into_iter()
4726 .find_map(|(dock, origin)| {
4727 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4728 Some(origin)
4729 } else {
4730 None
4731 }
4732 })
4733 .unwrap_or(Origin::Center)
4734 };
4735
4736 let get_last_active_pane = || {
4737 let pane = self
4738 .last_active_center_pane
4739 .clone()
4740 .unwrap_or_else(|| {
4741 self.panes
4742 .first()
4743 .expect("There must be an active pane")
4744 .downgrade()
4745 })
4746 .upgrade()?;
4747 (pane.read(cx).items_len() != 0).then_some(pane)
4748 };
4749
4750 let try_dock =
4751 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4752
4753 let sidebar_target = self
4754 .sidebar_focus_handle
4755 .as_ref()
4756 .map(|h| Target::Sidebar(h.clone()));
4757
4758 let target = match (origin, direction) {
4759 // From the sidebar, only Right navigates into the workspace.
4760 (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
4761 .or_else(|| get_last_active_pane().map(Target::Pane))
4762 .or_else(|| try_dock(&self.bottom_dock))
4763 .or_else(|| try_dock(&self.right_dock)),
4764
4765 (Origin::Sidebar, _) => None,
4766
4767 // We're in the center, so we first try to go to a different pane,
4768 // otherwise try to go to a dock.
4769 (Origin::Center, direction) => {
4770 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4771 Some(Target::Pane(pane))
4772 } else {
4773 match direction {
4774 SplitDirection::Up => None,
4775 SplitDirection::Down => try_dock(&self.bottom_dock),
4776 SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
4777 SplitDirection::Right => try_dock(&self.right_dock),
4778 }
4779 }
4780 }
4781
4782 (Origin::LeftDock, SplitDirection::Right) => {
4783 if let Some(last_active_pane) = get_last_active_pane() {
4784 Some(Target::Pane(last_active_pane))
4785 } else {
4786 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4787 }
4788 }
4789
4790 (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
4791
4792 (Origin::LeftDock, SplitDirection::Down)
4793 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4794
4795 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4796 (Origin::BottomDock, SplitDirection::Left) => {
4797 try_dock(&self.left_dock).or(sidebar_target)
4798 }
4799 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4800
4801 (Origin::RightDock, SplitDirection::Left) => {
4802 if let Some(last_active_pane) = get_last_active_pane() {
4803 Some(Target::Pane(last_active_pane))
4804 } else {
4805 try_dock(&self.bottom_dock)
4806 .or_else(|| try_dock(&self.left_dock))
4807 .or(sidebar_target)
4808 }
4809 }
4810
4811 _ => None,
4812 };
4813
4814 match target {
4815 Some(ActivateInDirectionTarget::Pane(pane)) => {
4816 let pane = pane.read(cx);
4817 if let Some(item) = pane.active_item() {
4818 item.item_focus_handle(cx).focus(window, cx);
4819 } else {
4820 log::error!(
4821 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4822 );
4823 }
4824 }
4825 Some(ActivateInDirectionTarget::Dock(dock)) => {
4826 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4827 window.defer(cx, move |window, cx| {
4828 let dock = dock.read(cx);
4829 if let Some(panel) = dock.active_panel() {
4830 panel.panel_focus_handle(cx).focus(window, cx);
4831 } else {
4832 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4833 }
4834 })
4835 }
4836 Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
4837 focus_handle.focus(window, cx);
4838 }
4839 None => {}
4840 }
4841 }
4842
4843 pub fn move_item_to_pane_in_direction(
4844 &mut self,
4845 action: &MoveItemToPaneInDirection,
4846 window: &mut Window,
4847 cx: &mut Context<Self>,
4848 ) {
4849 let destination = match self.find_pane_in_direction(action.direction, cx) {
4850 Some(destination) => destination,
4851 None => {
4852 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4853 return;
4854 }
4855 let new_pane = self.add_pane(window, cx);
4856 self.center
4857 .split(&self.active_pane, &new_pane, action.direction, cx);
4858 new_pane
4859 }
4860 };
4861
4862 if action.clone {
4863 if self
4864 .active_pane
4865 .read(cx)
4866 .active_item()
4867 .is_some_and(|item| item.can_split(cx))
4868 {
4869 clone_active_item(
4870 self.database_id(),
4871 &self.active_pane,
4872 &destination,
4873 action.focus,
4874 window,
4875 cx,
4876 );
4877 return;
4878 }
4879 }
4880 move_active_item(
4881 &self.active_pane,
4882 &destination,
4883 action.focus,
4884 true,
4885 window,
4886 cx,
4887 );
4888 }
4889
4890 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4891 self.center.bounding_box_for_pane(pane)
4892 }
4893
4894 pub fn find_pane_in_direction(
4895 &mut self,
4896 direction: SplitDirection,
4897 cx: &App,
4898 ) -> Option<Entity<Pane>> {
4899 self.center
4900 .find_pane_in_direction(&self.active_pane, direction, cx)
4901 .cloned()
4902 }
4903
4904 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4905 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4906 self.center.swap(&self.active_pane, &to, cx);
4907 cx.notify();
4908 }
4909 }
4910
4911 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4912 if self
4913 .center
4914 .move_to_border(&self.active_pane, direction, cx)
4915 .unwrap()
4916 {
4917 cx.notify();
4918 }
4919 }
4920
4921 pub fn resize_pane(
4922 &mut self,
4923 axis: gpui::Axis,
4924 amount: Pixels,
4925 window: &mut Window,
4926 cx: &mut Context<Self>,
4927 ) {
4928 let docks = self.all_docks();
4929 let active_dock = docks
4930 .into_iter()
4931 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4932
4933 if let Some(dock_entity) = active_dock {
4934 let dock = dock_entity.read(cx);
4935 let Some(panel_size) = self.dock_size(&dock, window, cx) else {
4936 return;
4937 };
4938 match dock.position() {
4939 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4940 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4941 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4942 }
4943 } else {
4944 self.center
4945 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
4946 }
4947 cx.notify();
4948 }
4949
4950 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
4951 self.center.reset_pane_sizes(cx);
4952 cx.notify();
4953 }
4954
4955 fn handle_pane_focused(
4956 &mut self,
4957 pane: Entity<Pane>,
4958 window: &mut Window,
4959 cx: &mut Context<Self>,
4960 ) {
4961 // This is explicitly hoisted out of the following check for pane identity as
4962 // terminal panel panes are not registered as a center panes.
4963 self.status_bar.update(cx, |status_bar, cx| {
4964 status_bar.set_active_pane(&pane, window, cx);
4965 });
4966 if self.active_pane != pane {
4967 self.set_active_pane(&pane, window, cx);
4968 }
4969
4970 if self.last_active_center_pane.is_none() {
4971 self.last_active_center_pane = Some(pane.downgrade());
4972 }
4973
4974 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
4975 // This prevents the dock from closing when focus events fire during window activation.
4976 // We also preserve any dock whose active panel itself has focus — this covers
4977 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
4978 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
4979 let dock_read = dock.read(cx);
4980 if let Some(panel) = dock_read.active_panel() {
4981 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
4982 || panel.panel_focus_handle(cx).contains_focused(window, cx)
4983 {
4984 return Some(dock_read.position());
4985 }
4986 }
4987 None
4988 });
4989
4990 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
4991 if pane.read(cx).is_zoomed() {
4992 self.zoomed = Some(pane.downgrade().into());
4993 } else {
4994 self.zoomed = None;
4995 }
4996 self.zoomed_position = None;
4997 cx.emit(Event::ZoomChanged);
4998 self.update_active_view_for_followers(window, cx);
4999 pane.update(cx, |pane, _| {
5000 pane.track_alternate_file_items();
5001 });
5002
5003 cx.notify();
5004 }
5005
5006 fn set_active_pane(
5007 &mut self,
5008 pane: &Entity<Pane>,
5009 window: &mut Window,
5010 cx: &mut Context<Self>,
5011 ) {
5012 self.active_pane = pane.clone();
5013 self.active_item_path_changed(true, window, cx);
5014 self.last_active_center_pane = Some(pane.downgrade());
5015 }
5016
5017 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5018 self.update_active_view_for_followers(window, cx);
5019 }
5020
5021 fn handle_pane_event(
5022 &mut self,
5023 pane: &Entity<Pane>,
5024 event: &pane::Event,
5025 window: &mut Window,
5026 cx: &mut Context<Self>,
5027 ) {
5028 let mut serialize_workspace = true;
5029 match event {
5030 pane::Event::AddItem { item } => {
5031 item.added_to_pane(self, pane.clone(), window, cx);
5032 cx.emit(Event::ItemAdded {
5033 item: item.boxed_clone(),
5034 });
5035 }
5036 pane::Event::Split { direction, mode } => {
5037 match mode {
5038 SplitMode::ClonePane => {
5039 self.split_and_clone(pane.clone(), *direction, window, cx)
5040 .detach();
5041 }
5042 SplitMode::EmptyPane => {
5043 self.split_pane(pane.clone(), *direction, window, cx);
5044 }
5045 SplitMode::MovePane => {
5046 self.split_and_move(pane.clone(), *direction, window, cx);
5047 }
5048 };
5049 }
5050 pane::Event::JoinIntoNext => {
5051 self.join_pane_into_next(pane.clone(), window, cx);
5052 }
5053 pane::Event::JoinAll => {
5054 self.join_all_panes(window, cx);
5055 }
5056 pane::Event::Remove { focus_on_pane } => {
5057 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
5058 }
5059 pane::Event::ActivateItem {
5060 local,
5061 focus_changed,
5062 } => {
5063 window.invalidate_character_coordinates();
5064
5065 pane.update(cx, |pane, _| {
5066 pane.track_alternate_file_items();
5067 });
5068 if *local {
5069 self.unfollow_in_pane(pane, window, cx);
5070 }
5071 serialize_workspace = *focus_changed || pane != self.active_pane();
5072 if pane == self.active_pane() {
5073 self.active_item_path_changed(*focus_changed, window, cx);
5074 self.update_active_view_for_followers(window, cx);
5075 } else if *local {
5076 self.set_active_pane(pane, window, cx);
5077 }
5078 }
5079 pane::Event::UserSavedItem { item, save_intent } => {
5080 cx.emit(Event::UserSavedItem {
5081 pane: pane.downgrade(),
5082 item: item.boxed_clone(),
5083 save_intent: *save_intent,
5084 });
5085 serialize_workspace = false;
5086 }
5087 pane::Event::ChangeItemTitle => {
5088 if *pane == self.active_pane {
5089 self.active_item_path_changed(false, window, cx);
5090 }
5091 serialize_workspace = false;
5092 }
5093 pane::Event::RemovedItem { item } => {
5094 cx.emit(Event::ActiveItemChanged);
5095 self.update_window_edited(window, cx);
5096 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
5097 && entry.get().entity_id() == pane.entity_id()
5098 {
5099 entry.remove();
5100 }
5101 cx.emit(Event::ItemRemoved {
5102 item_id: item.item_id(),
5103 });
5104 }
5105 pane::Event::Focus => {
5106 window.invalidate_character_coordinates();
5107 self.handle_pane_focused(pane.clone(), window, cx);
5108 }
5109 pane::Event::ZoomIn => {
5110 if *pane == self.active_pane {
5111 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
5112 if pane.read(cx).has_focus(window, cx) {
5113 self.zoomed = Some(pane.downgrade().into());
5114 self.zoomed_position = None;
5115 cx.emit(Event::ZoomChanged);
5116 }
5117 cx.notify();
5118 }
5119 }
5120 pane::Event::ZoomOut => {
5121 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
5122 if self.zoomed_position.is_none() {
5123 self.zoomed = None;
5124 cx.emit(Event::ZoomChanged);
5125 }
5126 cx.notify();
5127 }
5128 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
5129 }
5130
5131 if serialize_workspace {
5132 self.serialize_workspace(window, cx);
5133 }
5134 }
5135
5136 pub fn unfollow_in_pane(
5137 &mut self,
5138 pane: &Entity<Pane>,
5139 window: &mut Window,
5140 cx: &mut Context<Workspace>,
5141 ) -> Option<CollaboratorId> {
5142 let leader_id = self.leader_for_pane(pane)?;
5143 self.unfollow(leader_id, window, cx);
5144 Some(leader_id)
5145 }
5146
5147 pub fn split_pane(
5148 &mut self,
5149 pane_to_split: Entity<Pane>,
5150 split_direction: SplitDirection,
5151 window: &mut Window,
5152 cx: &mut Context<Self>,
5153 ) -> Entity<Pane> {
5154 let new_pane = self.add_pane(window, cx);
5155 self.center
5156 .split(&pane_to_split, &new_pane, split_direction, cx);
5157 cx.notify();
5158 new_pane
5159 }
5160
5161 pub fn split_and_move(
5162 &mut self,
5163 pane: Entity<Pane>,
5164 direction: SplitDirection,
5165 window: &mut Window,
5166 cx: &mut Context<Self>,
5167 ) {
5168 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
5169 return;
5170 };
5171 let new_pane = self.add_pane(window, cx);
5172 new_pane.update(cx, |pane, cx| {
5173 pane.add_item(item, true, true, None, window, cx)
5174 });
5175 self.center.split(&pane, &new_pane, direction, cx);
5176 cx.notify();
5177 }
5178
5179 pub fn split_and_clone(
5180 &mut self,
5181 pane: Entity<Pane>,
5182 direction: SplitDirection,
5183 window: &mut Window,
5184 cx: &mut Context<Self>,
5185 ) -> Task<Option<Entity<Pane>>> {
5186 let Some(item) = pane.read(cx).active_item() else {
5187 return Task::ready(None);
5188 };
5189 if !item.can_split(cx) {
5190 return Task::ready(None);
5191 }
5192 let task = item.clone_on_split(self.database_id(), window, cx);
5193 cx.spawn_in(window, async move |this, cx| {
5194 if let Some(clone) = task.await {
5195 this.update_in(cx, |this, window, cx| {
5196 let new_pane = this.add_pane(window, cx);
5197 let nav_history = pane.read(cx).fork_nav_history();
5198 new_pane.update(cx, |pane, cx| {
5199 pane.set_nav_history(nav_history, cx);
5200 pane.add_item(clone, true, true, None, window, cx)
5201 });
5202 this.center.split(&pane, &new_pane, direction, cx);
5203 cx.notify();
5204 new_pane
5205 })
5206 .ok()
5207 } else {
5208 None
5209 }
5210 })
5211 }
5212
5213 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5214 let active_item = self.active_pane.read(cx).active_item();
5215 for pane in &self.panes {
5216 join_pane_into_active(&self.active_pane, pane, window, cx);
5217 }
5218 if let Some(active_item) = active_item {
5219 self.activate_item(active_item.as_ref(), true, true, window, cx);
5220 }
5221 cx.notify();
5222 }
5223
5224 pub fn join_pane_into_next(
5225 &mut self,
5226 pane: Entity<Pane>,
5227 window: &mut Window,
5228 cx: &mut Context<Self>,
5229 ) {
5230 let next_pane = self
5231 .find_pane_in_direction(SplitDirection::Right, cx)
5232 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
5233 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
5234 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
5235 let Some(next_pane) = next_pane else {
5236 return;
5237 };
5238 move_all_items(&pane, &next_pane, window, cx);
5239 cx.notify();
5240 }
5241
5242 fn remove_pane(
5243 &mut self,
5244 pane: Entity<Pane>,
5245 focus_on: Option<Entity<Pane>>,
5246 window: &mut Window,
5247 cx: &mut Context<Self>,
5248 ) {
5249 if self.center.remove(&pane, cx).unwrap() {
5250 self.force_remove_pane(&pane, &focus_on, window, cx);
5251 self.unfollow_in_pane(&pane, window, cx);
5252 self.last_leaders_by_pane.remove(&pane.downgrade());
5253 for removed_item in pane.read(cx).items() {
5254 self.panes_by_item.remove(&removed_item.item_id());
5255 }
5256
5257 cx.notify();
5258 } else {
5259 self.active_item_path_changed(true, window, cx);
5260 }
5261 cx.emit(Event::PaneRemoved);
5262 }
5263
5264 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5265 &mut self.panes
5266 }
5267
5268 pub fn panes(&self) -> &[Entity<Pane>] {
5269 &self.panes
5270 }
5271
5272 pub fn active_pane(&self) -> &Entity<Pane> {
5273 &self.active_pane
5274 }
5275
5276 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5277 for dock in self.all_docks() {
5278 if dock.focus_handle(cx).contains_focused(window, cx)
5279 && let Some(pane) = dock
5280 .read(cx)
5281 .active_panel()
5282 .and_then(|panel| panel.pane(cx))
5283 {
5284 return pane;
5285 }
5286 }
5287 self.active_pane().clone()
5288 }
5289
5290 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5291 self.find_pane_in_direction(SplitDirection::Right, cx)
5292 .unwrap_or_else(|| {
5293 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5294 })
5295 }
5296
5297 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5298 self.pane_for_item_id(handle.item_id())
5299 }
5300
5301 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5302 let weak_pane = self.panes_by_item.get(&item_id)?;
5303 weak_pane.upgrade()
5304 }
5305
5306 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5307 self.panes
5308 .iter()
5309 .find(|pane| pane.entity_id() == entity_id)
5310 .cloned()
5311 }
5312
5313 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5314 self.follower_states.retain(|leader_id, state| {
5315 if *leader_id == CollaboratorId::PeerId(peer_id) {
5316 for item in state.items_by_leader_view_id.values() {
5317 item.view.set_leader_id(None, window, cx);
5318 }
5319 false
5320 } else {
5321 true
5322 }
5323 });
5324 cx.notify();
5325 }
5326
5327 pub fn start_following(
5328 &mut self,
5329 leader_id: impl Into<CollaboratorId>,
5330 window: &mut Window,
5331 cx: &mut Context<Self>,
5332 ) -> Option<Task<Result<()>>> {
5333 let leader_id = leader_id.into();
5334 let pane = self.active_pane().clone();
5335
5336 self.last_leaders_by_pane
5337 .insert(pane.downgrade(), leader_id);
5338 self.unfollow(leader_id, window, cx);
5339 self.unfollow_in_pane(&pane, window, cx);
5340 self.follower_states.insert(
5341 leader_id,
5342 FollowerState {
5343 center_pane: pane.clone(),
5344 dock_pane: None,
5345 active_view_id: None,
5346 items_by_leader_view_id: Default::default(),
5347 },
5348 );
5349 cx.notify();
5350
5351 match leader_id {
5352 CollaboratorId::PeerId(leader_peer_id) => {
5353 let room_id = self.active_call()?.room_id(cx)?;
5354 let project_id = self.project.read(cx).remote_id();
5355 let request = self.app_state.client.request(proto::Follow {
5356 room_id,
5357 project_id,
5358 leader_id: Some(leader_peer_id),
5359 });
5360
5361 Some(cx.spawn_in(window, async move |this, cx| {
5362 let response = request.await?;
5363 this.update(cx, |this, _| {
5364 let state = this
5365 .follower_states
5366 .get_mut(&leader_id)
5367 .context("following interrupted")?;
5368 state.active_view_id = response
5369 .active_view
5370 .as_ref()
5371 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5372 anyhow::Ok(())
5373 })??;
5374 if let Some(view) = response.active_view {
5375 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5376 }
5377 this.update_in(cx, |this, window, cx| {
5378 this.leader_updated(leader_id, window, cx)
5379 })?;
5380 Ok(())
5381 }))
5382 }
5383 CollaboratorId::Agent => {
5384 self.leader_updated(leader_id, window, cx)?;
5385 Some(Task::ready(Ok(())))
5386 }
5387 }
5388 }
5389
5390 pub fn follow_next_collaborator(
5391 &mut self,
5392 _: &FollowNextCollaborator,
5393 window: &mut Window,
5394 cx: &mut Context<Self>,
5395 ) {
5396 let collaborators = self.project.read(cx).collaborators();
5397 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5398 let mut collaborators = collaborators.keys().copied();
5399 for peer_id in collaborators.by_ref() {
5400 if CollaboratorId::PeerId(peer_id) == leader_id {
5401 break;
5402 }
5403 }
5404 collaborators.next().map(CollaboratorId::PeerId)
5405 } else if let Some(last_leader_id) =
5406 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5407 {
5408 match last_leader_id {
5409 CollaboratorId::PeerId(peer_id) => {
5410 if collaborators.contains_key(peer_id) {
5411 Some(*last_leader_id)
5412 } else {
5413 None
5414 }
5415 }
5416 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5417 }
5418 } else {
5419 None
5420 };
5421
5422 let pane = self.active_pane.clone();
5423 let Some(leader_id) = next_leader_id.or_else(|| {
5424 Some(CollaboratorId::PeerId(
5425 collaborators.keys().copied().next()?,
5426 ))
5427 }) else {
5428 return;
5429 };
5430 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5431 return;
5432 }
5433 if let Some(task) = self.start_following(leader_id, window, cx) {
5434 task.detach_and_log_err(cx)
5435 }
5436 }
5437
5438 pub fn follow(
5439 &mut self,
5440 leader_id: impl Into<CollaboratorId>,
5441 window: &mut Window,
5442 cx: &mut Context<Self>,
5443 ) {
5444 let leader_id = leader_id.into();
5445
5446 if let CollaboratorId::PeerId(peer_id) = leader_id {
5447 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5448 return;
5449 };
5450 let Some(remote_participant) =
5451 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5452 else {
5453 return;
5454 };
5455
5456 let project = self.project.read(cx);
5457
5458 let other_project_id = match remote_participant.location {
5459 ParticipantLocation::External => None,
5460 ParticipantLocation::UnsharedProject => None,
5461 ParticipantLocation::SharedProject { project_id } => {
5462 if Some(project_id) == project.remote_id() {
5463 None
5464 } else {
5465 Some(project_id)
5466 }
5467 }
5468 };
5469
5470 // if they are active in another project, follow there.
5471 if let Some(project_id) = other_project_id {
5472 let app_state = self.app_state.clone();
5473 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5474 .detach_and_log_err(cx);
5475 }
5476 }
5477
5478 // if you're already following, find the right pane and focus it.
5479 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5480 window.focus(&follower_state.pane().focus_handle(cx), cx);
5481
5482 return;
5483 }
5484
5485 // Otherwise, follow.
5486 if let Some(task) = self.start_following(leader_id, window, cx) {
5487 task.detach_and_log_err(cx)
5488 }
5489 }
5490
5491 pub fn unfollow(
5492 &mut self,
5493 leader_id: impl Into<CollaboratorId>,
5494 window: &mut Window,
5495 cx: &mut Context<Self>,
5496 ) -> Option<()> {
5497 cx.notify();
5498
5499 let leader_id = leader_id.into();
5500 let state = self.follower_states.remove(&leader_id)?;
5501 for (_, item) in state.items_by_leader_view_id {
5502 item.view.set_leader_id(None, window, cx);
5503 }
5504
5505 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5506 let project_id = self.project.read(cx).remote_id();
5507 let room_id = self.active_call()?.room_id(cx)?;
5508 self.app_state
5509 .client
5510 .send(proto::Unfollow {
5511 room_id,
5512 project_id,
5513 leader_id: Some(leader_peer_id),
5514 })
5515 .log_err();
5516 }
5517
5518 Some(())
5519 }
5520
5521 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5522 self.follower_states.contains_key(&id.into())
5523 }
5524
5525 fn active_item_path_changed(
5526 &mut self,
5527 focus_changed: bool,
5528 window: &mut Window,
5529 cx: &mut Context<Self>,
5530 ) {
5531 cx.emit(Event::ActiveItemChanged);
5532 let active_entry = self.active_project_path(cx);
5533 self.project.update(cx, |project, cx| {
5534 project.set_active_path(active_entry.clone(), cx)
5535 });
5536
5537 if focus_changed && let Some(project_path) = &active_entry {
5538 let git_store_entity = self.project.read(cx).git_store().clone();
5539 git_store_entity.update(cx, |git_store, cx| {
5540 git_store.set_active_repo_for_path(project_path, cx);
5541 });
5542 }
5543
5544 self.update_window_title(window, cx);
5545 }
5546
5547 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5548 let project = self.project().read(cx);
5549 let mut title = String::new();
5550
5551 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5552 let name = {
5553 let settings_location = SettingsLocation {
5554 worktree_id: worktree.read(cx).id(),
5555 path: RelPath::empty(),
5556 };
5557
5558 let settings = WorktreeSettings::get(Some(settings_location), cx);
5559 match &settings.project_name {
5560 Some(name) => name.as_str(),
5561 None => worktree.read(cx).root_name_str(),
5562 }
5563 };
5564 if i > 0 {
5565 title.push_str(", ");
5566 }
5567 title.push_str(name);
5568 }
5569
5570 if title.is_empty() {
5571 title = "empty project".to_string();
5572 }
5573
5574 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5575 let filename = path.path.file_name().or_else(|| {
5576 Some(
5577 project
5578 .worktree_for_id(path.worktree_id, cx)?
5579 .read(cx)
5580 .root_name_str(),
5581 )
5582 });
5583
5584 if let Some(filename) = filename {
5585 title.push_str(" — ");
5586 title.push_str(filename.as_ref());
5587 }
5588 }
5589
5590 if project.is_via_collab() {
5591 title.push_str(" ↙");
5592 } else if project.is_shared() {
5593 title.push_str(" ↗");
5594 }
5595
5596 if let Some(last_title) = self.last_window_title.as_ref()
5597 && &title == last_title
5598 {
5599 return;
5600 }
5601 window.set_window_title(&title);
5602 SystemWindowTabController::update_tab_title(
5603 cx,
5604 window.window_handle().window_id(),
5605 SharedString::from(&title),
5606 );
5607 self.last_window_title = Some(title);
5608 }
5609
5610 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5611 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5612 if is_edited != self.window_edited {
5613 self.window_edited = is_edited;
5614 window.set_window_edited(self.window_edited)
5615 }
5616 }
5617
5618 fn update_item_dirty_state(
5619 &mut self,
5620 item: &dyn ItemHandle,
5621 window: &mut Window,
5622 cx: &mut App,
5623 ) {
5624 let is_dirty = item.is_dirty(cx);
5625 let item_id = item.item_id();
5626 let was_dirty = self.dirty_items.contains_key(&item_id);
5627 if is_dirty == was_dirty {
5628 return;
5629 }
5630 if was_dirty {
5631 self.dirty_items.remove(&item_id);
5632 self.update_window_edited(window, cx);
5633 return;
5634 }
5635
5636 let workspace = self.weak_handle();
5637 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5638 return;
5639 };
5640 let on_release_callback = Box::new(move |cx: &mut App| {
5641 window_handle
5642 .update(cx, |_, window, cx| {
5643 workspace
5644 .update(cx, |workspace, cx| {
5645 workspace.dirty_items.remove(&item_id);
5646 workspace.update_window_edited(window, cx)
5647 })
5648 .ok();
5649 })
5650 .ok();
5651 });
5652
5653 let s = item.on_release(cx, on_release_callback);
5654 self.dirty_items.insert(item_id, s);
5655 self.update_window_edited(window, cx);
5656 }
5657
5658 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5659 if self.notifications.is_empty() {
5660 None
5661 } else {
5662 Some(
5663 div()
5664 .absolute()
5665 .right_3()
5666 .bottom_3()
5667 .w_112()
5668 .h_full()
5669 .flex()
5670 .flex_col()
5671 .justify_end()
5672 .gap_2()
5673 .children(
5674 self.notifications
5675 .iter()
5676 .map(|(_, notification)| notification.clone().into_any()),
5677 ),
5678 )
5679 }
5680 }
5681
5682 // RPC handlers
5683
5684 fn active_view_for_follower(
5685 &self,
5686 follower_project_id: Option<u64>,
5687 window: &mut Window,
5688 cx: &mut Context<Self>,
5689 ) -> Option<proto::View> {
5690 let (item, panel_id) = self.active_item_for_followers(window, cx);
5691 let item = item?;
5692 let leader_id = self
5693 .pane_for(&*item)
5694 .and_then(|pane| self.leader_for_pane(&pane));
5695 let leader_peer_id = match leader_id {
5696 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5697 Some(CollaboratorId::Agent) | None => None,
5698 };
5699
5700 let item_handle = item.to_followable_item_handle(cx)?;
5701 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5702 let variant = item_handle.to_state_proto(window, cx)?;
5703
5704 if item_handle.is_project_item(window, cx)
5705 && (follower_project_id.is_none()
5706 || follower_project_id != self.project.read(cx).remote_id())
5707 {
5708 return None;
5709 }
5710
5711 Some(proto::View {
5712 id: id.to_proto(),
5713 leader_id: leader_peer_id,
5714 variant: Some(variant),
5715 panel_id: panel_id.map(|id| id as i32),
5716 })
5717 }
5718
5719 fn handle_follow(
5720 &mut self,
5721 follower_project_id: Option<u64>,
5722 window: &mut Window,
5723 cx: &mut Context<Self>,
5724 ) -> proto::FollowResponse {
5725 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5726
5727 cx.notify();
5728 proto::FollowResponse {
5729 views: active_view.iter().cloned().collect(),
5730 active_view,
5731 }
5732 }
5733
5734 fn handle_update_followers(
5735 &mut self,
5736 leader_id: PeerId,
5737 message: proto::UpdateFollowers,
5738 _window: &mut Window,
5739 _cx: &mut Context<Self>,
5740 ) {
5741 self.leader_updates_tx
5742 .unbounded_send((leader_id, message))
5743 .ok();
5744 }
5745
5746 async fn process_leader_update(
5747 this: &WeakEntity<Self>,
5748 leader_id: PeerId,
5749 update: proto::UpdateFollowers,
5750 cx: &mut AsyncWindowContext,
5751 ) -> Result<()> {
5752 match update.variant.context("invalid update")? {
5753 proto::update_followers::Variant::CreateView(view) => {
5754 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5755 let should_add_view = this.update(cx, |this, _| {
5756 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5757 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5758 } else {
5759 anyhow::Ok(false)
5760 }
5761 })??;
5762
5763 if should_add_view {
5764 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5765 }
5766 }
5767 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5768 let should_add_view = this.update(cx, |this, _| {
5769 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5770 state.active_view_id = update_active_view
5771 .view
5772 .as_ref()
5773 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5774
5775 if state.active_view_id.is_some_and(|view_id| {
5776 !state.items_by_leader_view_id.contains_key(&view_id)
5777 }) {
5778 anyhow::Ok(true)
5779 } else {
5780 anyhow::Ok(false)
5781 }
5782 } else {
5783 anyhow::Ok(false)
5784 }
5785 })??;
5786
5787 if should_add_view && let Some(view) = update_active_view.view {
5788 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5789 }
5790 }
5791 proto::update_followers::Variant::UpdateView(update_view) => {
5792 let variant = update_view.variant.context("missing update view variant")?;
5793 let id = update_view.id.context("missing update view id")?;
5794 let mut tasks = Vec::new();
5795 this.update_in(cx, |this, window, cx| {
5796 let project = this.project.clone();
5797 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5798 let view_id = ViewId::from_proto(id.clone())?;
5799 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5800 tasks.push(item.view.apply_update_proto(
5801 &project,
5802 variant.clone(),
5803 window,
5804 cx,
5805 ));
5806 }
5807 }
5808 anyhow::Ok(())
5809 })??;
5810 try_join_all(tasks).await.log_err();
5811 }
5812 }
5813 this.update_in(cx, |this, window, cx| {
5814 this.leader_updated(leader_id, window, cx)
5815 })?;
5816 Ok(())
5817 }
5818
5819 async fn add_view_from_leader(
5820 this: WeakEntity<Self>,
5821 leader_id: PeerId,
5822 view: &proto::View,
5823 cx: &mut AsyncWindowContext,
5824 ) -> Result<()> {
5825 let this = this.upgrade().context("workspace dropped")?;
5826
5827 let Some(id) = view.id.clone() else {
5828 anyhow::bail!("no id for view");
5829 };
5830 let id = ViewId::from_proto(id)?;
5831 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5832
5833 let pane = this.update(cx, |this, _cx| {
5834 let state = this
5835 .follower_states
5836 .get(&leader_id.into())
5837 .context("stopped following")?;
5838 anyhow::Ok(state.pane().clone())
5839 })?;
5840 let existing_item = pane.update_in(cx, |pane, window, cx| {
5841 let client = this.read(cx).client().clone();
5842 pane.items().find_map(|item| {
5843 let item = item.to_followable_item_handle(cx)?;
5844 if item.remote_id(&client, window, cx) == Some(id) {
5845 Some(item)
5846 } else {
5847 None
5848 }
5849 })
5850 })?;
5851 let item = if let Some(existing_item) = existing_item {
5852 existing_item
5853 } else {
5854 let variant = view.variant.clone();
5855 anyhow::ensure!(variant.is_some(), "missing view variant");
5856
5857 let task = cx.update(|window, cx| {
5858 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5859 })?;
5860
5861 let Some(task) = task else {
5862 anyhow::bail!(
5863 "failed to construct view from leader (maybe from a different version of zed?)"
5864 );
5865 };
5866
5867 let mut new_item = task.await?;
5868 pane.update_in(cx, |pane, window, cx| {
5869 let mut item_to_remove = None;
5870 for (ix, item) in pane.items().enumerate() {
5871 if let Some(item) = item.to_followable_item_handle(cx) {
5872 match new_item.dedup(item.as_ref(), window, cx) {
5873 Some(item::Dedup::KeepExisting) => {
5874 new_item =
5875 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5876 break;
5877 }
5878 Some(item::Dedup::ReplaceExisting) => {
5879 item_to_remove = Some((ix, item.item_id()));
5880 break;
5881 }
5882 None => {}
5883 }
5884 }
5885 }
5886
5887 if let Some((ix, id)) = item_to_remove {
5888 pane.remove_item(id, false, false, window, cx);
5889 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5890 }
5891 })?;
5892
5893 new_item
5894 };
5895
5896 this.update_in(cx, |this, window, cx| {
5897 let state = this.follower_states.get_mut(&leader_id.into())?;
5898 item.set_leader_id(Some(leader_id.into()), window, cx);
5899 state.items_by_leader_view_id.insert(
5900 id,
5901 FollowerView {
5902 view: item,
5903 location: panel_id,
5904 },
5905 );
5906
5907 Some(())
5908 })
5909 .context("no follower state")?;
5910
5911 Ok(())
5912 }
5913
5914 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5915 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5916 return;
5917 };
5918
5919 if let Some(agent_location) = self.project.read(cx).agent_location() {
5920 let buffer_entity_id = agent_location.buffer.entity_id();
5921 let view_id = ViewId {
5922 creator: CollaboratorId::Agent,
5923 id: buffer_entity_id.as_u64(),
5924 };
5925 follower_state.active_view_id = Some(view_id);
5926
5927 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5928 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5929 hash_map::Entry::Vacant(entry) => {
5930 let existing_view =
5931 follower_state
5932 .center_pane
5933 .read(cx)
5934 .items()
5935 .find_map(|item| {
5936 let item = item.to_followable_item_handle(cx)?;
5937 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5938 && item.project_item_model_ids(cx).as_slice()
5939 == [buffer_entity_id]
5940 {
5941 Some(item)
5942 } else {
5943 None
5944 }
5945 });
5946 let view = existing_view.or_else(|| {
5947 agent_location.buffer.upgrade().and_then(|buffer| {
5948 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
5949 registry.build_item(buffer, self.project.clone(), None, window, cx)
5950 })?
5951 .to_followable_item_handle(cx)
5952 })
5953 });
5954
5955 view.map(|view| {
5956 entry.insert(FollowerView {
5957 view,
5958 location: None,
5959 })
5960 })
5961 }
5962 };
5963
5964 if let Some(item) = item {
5965 item.view
5966 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
5967 item.view
5968 .update_agent_location(agent_location.position, window, cx);
5969 }
5970 } else {
5971 follower_state.active_view_id = None;
5972 }
5973
5974 self.leader_updated(CollaboratorId::Agent, window, cx);
5975 }
5976
5977 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
5978 let mut is_project_item = true;
5979 let mut update = proto::UpdateActiveView::default();
5980 if window.is_window_active() {
5981 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
5982
5983 if let Some(item) = active_item
5984 && item.item_focus_handle(cx).contains_focused(window, cx)
5985 {
5986 let leader_id = self
5987 .pane_for(&*item)
5988 .and_then(|pane| self.leader_for_pane(&pane));
5989 let leader_peer_id = match leader_id {
5990 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5991 Some(CollaboratorId::Agent) | None => None,
5992 };
5993
5994 if let Some(item) = item.to_followable_item_handle(cx) {
5995 let id = item
5996 .remote_id(&self.app_state.client, window, cx)
5997 .map(|id| id.to_proto());
5998
5999 if let Some(id) = id
6000 && let Some(variant) = item.to_state_proto(window, cx)
6001 {
6002 let view = Some(proto::View {
6003 id,
6004 leader_id: leader_peer_id,
6005 variant: Some(variant),
6006 panel_id: panel_id.map(|id| id as i32),
6007 });
6008
6009 is_project_item = item.is_project_item(window, cx);
6010 update = proto::UpdateActiveView { view };
6011 };
6012 }
6013 }
6014 }
6015
6016 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
6017 if active_view_id != self.last_active_view_id.as_ref() {
6018 self.last_active_view_id = active_view_id.cloned();
6019 self.update_followers(
6020 is_project_item,
6021 proto::update_followers::Variant::UpdateActiveView(update),
6022 window,
6023 cx,
6024 );
6025 }
6026 }
6027
6028 fn active_item_for_followers(
6029 &self,
6030 window: &mut Window,
6031 cx: &mut App,
6032 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
6033 let mut active_item = None;
6034 let mut panel_id = None;
6035 for dock in self.all_docks() {
6036 if dock.focus_handle(cx).contains_focused(window, cx)
6037 && let Some(panel) = dock.read(cx).active_panel()
6038 && let Some(pane) = panel.pane(cx)
6039 && let Some(item) = pane.read(cx).active_item()
6040 {
6041 active_item = Some(item);
6042 panel_id = panel.remote_id();
6043 break;
6044 }
6045 }
6046
6047 if active_item.is_none() {
6048 active_item = self.active_pane().read(cx).active_item();
6049 }
6050 (active_item, panel_id)
6051 }
6052
6053 fn update_followers(
6054 &self,
6055 project_only: bool,
6056 update: proto::update_followers::Variant,
6057 _: &mut Window,
6058 cx: &mut App,
6059 ) -> Option<()> {
6060 // If this update only applies to for followers in the current project,
6061 // then skip it unless this project is shared. If it applies to all
6062 // followers, regardless of project, then set `project_id` to none,
6063 // indicating that it goes to all followers.
6064 let project_id = if project_only {
6065 Some(self.project.read(cx).remote_id()?)
6066 } else {
6067 None
6068 };
6069 self.app_state().workspace_store.update(cx, |store, cx| {
6070 store.update_followers(project_id, update, cx)
6071 })
6072 }
6073
6074 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
6075 self.follower_states.iter().find_map(|(leader_id, state)| {
6076 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
6077 Some(*leader_id)
6078 } else {
6079 None
6080 }
6081 })
6082 }
6083
6084 fn leader_updated(
6085 &mut self,
6086 leader_id: impl Into<CollaboratorId>,
6087 window: &mut Window,
6088 cx: &mut Context<Self>,
6089 ) -> Option<Box<dyn ItemHandle>> {
6090 cx.notify();
6091
6092 let leader_id = leader_id.into();
6093 let (panel_id, item) = match leader_id {
6094 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
6095 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
6096 };
6097
6098 let state = self.follower_states.get(&leader_id)?;
6099 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
6100 let pane;
6101 if let Some(panel_id) = panel_id {
6102 pane = self
6103 .activate_panel_for_proto_id(panel_id, window, cx)?
6104 .pane(cx)?;
6105 let state = self.follower_states.get_mut(&leader_id)?;
6106 state.dock_pane = Some(pane.clone());
6107 } else {
6108 pane = state.center_pane.clone();
6109 let state = self.follower_states.get_mut(&leader_id)?;
6110 if let Some(dock_pane) = state.dock_pane.take() {
6111 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
6112 }
6113 }
6114
6115 pane.update(cx, |pane, cx| {
6116 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
6117 if let Some(index) = pane.index_for_item(item.as_ref()) {
6118 pane.activate_item(index, false, false, window, cx);
6119 } else {
6120 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
6121 }
6122
6123 if focus_active_item {
6124 pane.focus_active_item(window, cx)
6125 }
6126 });
6127
6128 Some(item)
6129 }
6130
6131 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
6132 let state = self.follower_states.get(&CollaboratorId::Agent)?;
6133 let active_view_id = state.active_view_id?;
6134 Some(
6135 state
6136 .items_by_leader_view_id
6137 .get(&active_view_id)?
6138 .view
6139 .boxed_clone(),
6140 )
6141 }
6142
6143 fn active_item_for_peer(
6144 &self,
6145 peer_id: PeerId,
6146 window: &mut Window,
6147 cx: &mut Context<Self>,
6148 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
6149 let call = self.active_call()?;
6150 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
6151 let leader_in_this_app;
6152 let leader_in_this_project;
6153 match participant.location {
6154 ParticipantLocation::SharedProject { project_id } => {
6155 leader_in_this_app = true;
6156 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
6157 }
6158 ParticipantLocation::UnsharedProject => {
6159 leader_in_this_app = true;
6160 leader_in_this_project = false;
6161 }
6162 ParticipantLocation::External => {
6163 leader_in_this_app = false;
6164 leader_in_this_project = false;
6165 }
6166 };
6167 let state = self.follower_states.get(&peer_id.into())?;
6168 let mut item_to_activate = None;
6169 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
6170 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
6171 && (leader_in_this_project || !item.view.is_project_item(window, cx))
6172 {
6173 item_to_activate = Some((item.location, item.view.boxed_clone()));
6174 }
6175 } else if let Some(shared_screen) =
6176 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
6177 {
6178 item_to_activate = Some((None, Box::new(shared_screen)));
6179 }
6180 item_to_activate
6181 }
6182
6183 fn shared_screen_for_peer(
6184 &self,
6185 peer_id: PeerId,
6186 pane: &Entity<Pane>,
6187 window: &mut Window,
6188 cx: &mut App,
6189 ) -> Option<Entity<SharedScreen>> {
6190 self.active_call()?
6191 .create_shared_screen(peer_id, pane, window, cx)
6192 }
6193
6194 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6195 if window.is_window_active() {
6196 self.update_active_view_for_followers(window, cx);
6197
6198 if let Some(database_id) = self.database_id {
6199 let db = WorkspaceDb::global(cx);
6200 cx.background_spawn(async move { db.update_timestamp(database_id).await })
6201 .detach();
6202 }
6203 } else {
6204 for pane in &self.panes {
6205 pane.update(cx, |pane, cx| {
6206 if let Some(item) = pane.active_item() {
6207 item.workspace_deactivated(window, cx);
6208 }
6209 for item in pane.items() {
6210 if matches!(
6211 item.workspace_settings(cx).autosave,
6212 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
6213 ) {
6214 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
6215 .detach_and_log_err(cx);
6216 }
6217 }
6218 });
6219 }
6220 }
6221 }
6222
6223 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
6224 self.active_call.as_ref().map(|(call, _)| &*call.0)
6225 }
6226
6227 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
6228 self.active_call.as_ref().map(|(call, _)| call.clone())
6229 }
6230
6231 fn on_active_call_event(
6232 &mut self,
6233 event: &ActiveCallEvent,
6234 window: &mut Window,
6235 cx: &mut Context<Self>,
6236 ) {
6237 match event {
6238 ActiveCallEvent::ParticipantLocationChanged { participant_id }
6239 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
6240 self.leader_updated(participant_id, window, cx);
6241 }
6242 }
6243 }
6244
6245 pub fn database_id(&self) -> Option<WorkspaceId> {
6246 self.database_id
6247 }
6248
6249 #[cfg(any(test, feature = "test-support"))]
6250 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
6251 self.database_id = Some(id);
6252 }
6253
6254 pub fn session_id(&self) -> Option<String> {
6255 self.session_id.clone()
6256 }
6257
6258 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6259 let Some(display) = window.display(cx) else {
6260 return Task::ready(());
6261 };
6262 let Ok(display_uuid) = display.uuid() else {
6263 return Task::ready(());
6264 };
6265
6266 let window_bounds = window.inner_window_bounds();
6267 let database_id = self.database_id;
6268 let has_paths = !self.root_paths(cx).is_empty();
6269 let db = WorkspaceDb::global(cx);
6270 let kvp = db::kvp::KeyValueStore::global(cx);
6271
6272 cx.background_executor().spawn(async move {
6273 if !has_paths {
6274 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6275 .await
6276 .log_err();
6277 }
6278 if let Some(database_id) = database_id {
6279 db.set_window_open_status(
6280 database_id,
6281 SerializedWindowBounds(window_bounds),
6282 display_uuid,
6283 )
6284 .await
6285 .log_err();
6286 } else {
6287 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6288 .await
6289 .log_err();
6290 }
6291 })
6292 }
6293
6294 /// Bypass the 200ms serialization throttle and write workspace state to
6295 /// the DB immediately. Returns a task the caller can await to ensure the
6296 /// write completes. Used by the quit handler so the most recent state
6297 /// isn't lost to a pending throttle timer when the process exits.
6298 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6299 self._schedule_serialize_workspace.take();
6300 self._serialize_workspace_task.take();
6301 self.bounds_save_task_queued.take();
6302
6303 let bounds_task = self.save_window_bounds(window, cx);
6304 let serialize_task = self.serialize_workspace_internal(window, cx);
6305 cx.spawn(async move |_| {
6306 bounds_task.await;
6307 serialize_task.await;
6308 })
6309 }
6310
6311 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6312 let project = self.project().read(cx);
6313 project
6314 .visible_worktrees(cx)
6315 .map(|worktree| worktree.read(cx).abs_path())
6316 .collect::<Vec<_>>()
6317 }
6318
6319 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6320 match member {
6321 Member::Axis(PaneAxis { members, .. }) => {
6322 for child in members.iter() {
6323 self.remove_panes(child.clone(), window, cx)
6324 }
6325 }
6326 Member::Pane(pane) => {
6327 self.force_remove_pane(&pane, &None, window, cx);
6328 }
6329 }
6330 }
6331
6332 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6333 self.session_id.take();
6334 self.serialize_workspace_internal(window, cx)
6335 }
6336
6337 fn force_remove_pane(
6338 &mut self,
6339 pane: &Entity<Pane>,
6340 focus_on: &Option<Entity<Pane>>,
6341 window: &mut Window,
6342 cx: &mut Context<Workspace>,
6343 ) {
6344 self.panes.retain(|p| p != pane);
6345 if let Some(focus_on) = focus_on {
6346 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6347 } else if self.active_pane() == pane {
6348 self.panes
6349 .last()
6350 .unwrap()
6351 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6352 }
6353 if self.last_active_center_pane == Some(pane.downgrade()) {
6354 self.last_active_center_pane = None;
6355 }
6356 cx.notify();
6357 }
6358
6359 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6360 if self._schedule_serialize_workspace.is_none() {
6361 self._schedule_serialize_workspace =
6362 Some(cx.spawn_in(window, async move |this, cx| {
6363 cx.background_executor()
6364 .timer(SERIALIZATION_THROTTLE_TIME)
6365 .await;
6366 this.update_in(cx, |this, window, cx| {
6367 this._serialize_workspace_task =
6368 Some(this.serialize_workspace_internal(window, cx));
6369 this._schedule_serialize_workspace.take();
6370 })
6371 .log_err();
6372 }));
6373 }
6374 }
6375
6376 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6377 let Some(database_id) = self.database_id() else {
6378 return Task::ready(());
6379 };
6380
6381 fn serialize_pane_handle(
6382 pane_handle: &Entity<Pane>,
6383 window: &mut Window,
6384 cx: &mut App,
6385 ) -> SerializedPane {
6386 let (items, active, pinned_count) = {
6387 let pane = pane_handle.read(cx);
6388 let active_item_id = pane.active_item().map(|item| item.item_id());
6389 (
6390 pane.items()
6391 .filter_map(|handle| {
6392 let handle = handle.to_serializable_item_handle(cx)?;
6393
6394 Some(SerializedItem {
6395 kind: Arc::from(handle.serialized_item_kind()),
6396 item_id: handle.item_id().as_u64(),
6397 active: Some(handle.item_id()) == active_item_id,
6398 preview: pane.is_active_preview_item(handle.item_id()),
6399 })
6400 })
6401 .collect::<Vec<_>>(),
6402 pane.has_focus(window, cx),
6403 pane.pinned_count(),
6404 )
6405 };
6406
6407 SerializedPane::new(items, active, pinned_count)
6408 }
6409
6410 fn build_serialized_pane_group(
6411 pane_group: &Member,
6412 window: &mut Window,
6413 cx: &mut App,
6414 ) -> SerializedPaneGroup {
6415 match pane_group {
6416 Member::Axis(PaneAxis {
6417 axis,
6418 members,
6419 flexes,
6420 bounding_boxes: _,
6421 }) => SerializedPaneGroup::Group {
6422 axis: SerializedAxis(*axis),
6423 children: members
6424 .iter()
6425 .map(|member| build_serialized_pane_group(member, window, cx))
6426 .collect::<Vec<_>>(),
6427 flexes: Some(flexes.lock().clone()),
6428 },
6429 Member::Pane(pane_handle) => {
6430 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6431 }
6432 }
6433 }
6434
6435 fn build_serialized_docks(
6436 this: &Workspace,
6437 window: &mut Window,
6438 cx: &mut App,
6439 ) -> DockStructure {
6440 this.capture_dock_state(window, cx)
6441 }
6442
6443 match self.workspace_location(cx) {
6444 WorkspaceLocation::Location(location, paths) => {
6445 let breakpoints = self.project.update(cx, |project, cx| {
6446 project
6447 .breakpoint_store()
6448 .read(cx)
6449 .all_source_breakpoints(cx)
6450 });
6451 let user_toolchains = self
6452 .project
6453 .read(cx)
6454 .user_toolchains(cx)
6455 .unwrap_or_default();
6456
6457 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6458 let docks = build_serialized_docks(self, window, cx);
6459 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6460
6461 let serialized_workspace = SerializedWorkspace {
6462 id: database_id,
6463 location,
6464 paths,
6465 center_group,
6466 window_bounds,
6467 display: Default::default(),
6468 docks,
6469 centered_layout: self.centered_layout,
6470 session_id: self.session_id.clone(),
6471 breakpoints,
6472 window_id: Some(window.window_handle().window_id().as_u64()),
6473 user_toolchains,
6474 };
6475
6476 let db = WorkspaceDb::global(cx);
6477 window.spawn(cx, async move |_| {
6478 db.save_workspace(serialized_workspace).await;
6479 })
6480 }
6481 WorkspaceLocation::DetachFromSession => {
6482 let window_bounds = SerializedWindowBounds(window.window_bounds());
6483 let display = window.display(cx).and_then(|d| d.uuid().ok());
6484 // Save dock state for empty local workspaces
6485 let docks = build_serialized_docks(self, window, cx);
6486 let db = WorkspaceDb::global(cx);
6487 let kvp = db::kvp::KeyValueStore::global(cx);
6488 window.spawn(cx, async move |_| {
6489 db.set_window_open_status(
6490 database_id,
6491 window_bounds,
6492 display.unwrap_or_default(),
6493 )
6494 .await
6495 .log_err();
6496 db.set_session_id(database_id, None).await.log_err();
6497 persistence::write_default_dock_state(&kvp, docks)
6498 .await
6499 .log_err();
6500 })
6501 }
6502 WorkspaceLocation::None => {
6503 // Save dock state for empty non-local workspaces
6504 let docks = build_serialized_docks(self, window, cx);
6505 let kvp = db::kvp::KeyValueStore::global(cx);
6506 window.spawn(cx, async move |_| {
6507 persistence::write_default_dock_state(&kvp, docks)
6508 .await
6509 .log_err();
6510 })
6511 }
6512 }
6513 }
6514
6515 fn has_any_items_open(&self, cx: &App) -> bool {
6516 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6517 }
6518
6519 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6520 let paths = PathList::new(&self.root_paths(cx));
6521 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6522 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6523 } else if self.project.read(cx).is_local() {
6524 if !paths.is_empty() || self.has_any_items_open(cx) {
6525 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6526 } else {
6527 WorkspaceLocation::DetachFromSession
6528 }
6529 } else {
6530 WorkspaceLocation::None
6531 }
6532 }
6533
6534 fn update_history(&self, cx: &mut App) {
6535 let Some(id) = self.database_id() else {
6536 return;
6537 };
6538 if !self.project.read(cx).is_local() {
6539 return;
6540 }
6541 if let Some(manager) = HistoryManager::global(cx) {
6542 let paths = PathList::new(&self.root_paths(cx));
6543 manager.update(cx, |this, cx| {
6544 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6545 });
6546 }
6547 }
6548
6549 async fn serialize_items(
6550 this: &WeakEntity<Self>,
6551 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6552 cx: &mut AsyncWindowContext,
6553 ) -> Result<()> {
6554 const CHUNK_SIZE: usize = 200;
6555
6556 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6557
6558 while let Some(items_received) = serializable_items.next().await {
6559 let unique_items =
6560 items_received
6561 .into_iter()
6562 .fold(HashMap::default(), |mut acc, item| {
6563 acc.entry(item.item_id()).or_insert(item);
6564 acc
6565 });
6566
6567 // We use into_iter() here so that the references to the items are moved into
6568 // the tasks and not kept alive while we're sleeping.
6569 for (_, item) in unique_items.into_iter() {
6570 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6571 item.serialize(workspace, false, window, cx)
6572 }) {
6573 cx.background_spawn(async move { task.await.log_err() })
6574 .detach();
6575 }
6576 }
6577
6578 cx.background_executor()
6579 .timer(SERIALIZATION_THROTTLE_TIME)
6580 .await;
6581 }
6582
6583 Ok(())
6584 }
6585
6586 pub(crate) fn enqueue_item_serialization(
6587 &mut self,
6588 item: Box<dyn SerializableItemHandle>,
6589 ) -> Result<()> {
6590 self.serializable_items_tx
6591 .unbounded_send(item)
6592 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6593 }
6594
6595 pub(crate) fn load_workspace(
6596 serialized_workspace: SerializedWorkspace,
6597 paths_to_open: Vec<Option<ProjectPath>>,
6598 window: &mut Window,
6599 cx: &mut Context<Workspace>,
6600 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6601 cx.spawn_in(window, async move |workspace, cx| {
6602 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6603
6604 let mut center_group = None;
6605 let mut center_items = None;
6606
6607 // Traverse the splits tree and add to things
6608 if let Some((group, active_pane, items)) = serialized_workspace
6609 .center_group
6610 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6611 .await
6612 {
6613 center_items = Some(items);
6614 center_group = Some((group, active_pane))
6615 }
6616
6617 let mut items_by_project_path = HashMap::default();
6618 let mut item_ids_by_kind = HashMap::default();
6619 let mut all_deserialized_items = Vec::default();
6620 cx.update(|_, cx| {
6621 for item in center_items.unwrap_or_default().into_iter().flatten() {
6622 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6623 item_ids_by_kind
6624 .entry(serializable_item_handle.serialized_item_kind())
6625 .or_insert(Vec::new())
6626 .push(item.item_id().as_u64() as ItemId);
6627 }
6628
6629 if let Some(project_path) = item.project_path(cx) {
6630 items_by_project_path.insert(project_path, item.clone());
6631 }
6632 all_deserialized_items.push(item);
6633 }
6634 })?;
6635
6636 let opened_items = paths_to_open
6637 .into_iter()
6638 .map(|path_to_open| {
6639 path_to_open
6640 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6641 })
6642 .collect::<Vec<_>>();
6643
6644 // Remove old panes from workspace panes list
6645 workspace.update_in(cx, |workspace, window, cx| {
6646 if let Some((center_group, active_pane)) = center_group {
6647 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6648
6649 // Swap workspace center group
6650 workspace.center = PaneGroup::with_root(center_group);
6651 workspace.center.set_is_center(true);
6652 workspace.center.mark_positions(cx);
6653
6654 if let Some(active_pane) = active_pane {
6655 workspace.set_active_pane(&active_pane, window, cx);
6656 cx.focus_self(window);
6657 } else {
6658 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6659 }
6660 }
6661
6662 let docks = serialized_workspace.docks;
6663
6664 for (dock, serialized_dock) in [
6665 (&mut workspace.right_dock, docks.right),
6666 (&mut workspace.left_dock, docks.left),
6667 (&mut workspace.bottom_dock, docks.bottom),
6668 ]
6669 .iter_mut()
6670 {
6671 dock.update(cx, |dock, cx| {
6672 dock.serialized_dock = Some(serialized_dock.clone());
6673 dock.restore_state(window, cx);
6674 });
6675 }
6676
6677 cx.notify();
6678 })?;
6679
6680 let _ = project
6681 .update(cx, |project, cx| {
6682 project
6683 .breakpoint_store()
6684 .update(cx, |breakpoint_store, cx| {
6685 breakpoint_store
6686 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6687 })
6688 })
6689 .await;
6690
6691 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6692 // after loading the items, we might have different items and in order to avoid
6693 // the database filling up, we delete items that haven't been loaded now.
6694 //
6695 // The items that have been loaded, have been saved after they've been added to the workspace.
6696 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6697 item_ids_by_kind
6698 .into_iter()
6699 .map(|(item_kind, loaded_items)| {
6700 SerializableItemRegistry::cleanup(
6701 item_kind,
6702 serialized_workspace.id,
6703 loaded_items,
6704 window,
6705 cx,
6706 )
6707 .log_err()
6708 })
6709 .collect::<Vec<_>>()
6710 })?;
6711
6712 futures::future::join_all(clean_up_tasks).await;
6713
6714 workspace
6715 .update_in(cx, |workspace, window, cx| {
6716 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6717 workspace.serialize_workspace_internal(window, cx).detach();
6718
6719 // Ensure that we mark the window as edited if we did load dirty items
6720 workspace.update_window_edited(window, cx);
6721 })
6722 .ok();
6723
6724 Ok(opened_items)
6725 })
6726 }
6727
6728 pub fn key_context(&self, cx: &App) -> KeyContext {
6729 let mut context = KeyContext::new_with_defaults();
6730 context.add("Workspace");
6731 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6732 if let Some(status) = self
6733 .debugger_provider
6734 .as_ref()
6735 .and_then(|provider| provider.active_thread_state(cx))
6736 {
6737 match status {
6738 ThreadStatus::Running | ThreadStatus::Stepping => {
6739 context.add("debugger_running");
6740 }
6741 ThreadStatus::Stopped => context.add("debugger_stopped"),
6742 ThreadStatus::Exited | ThreadStatus::Ended => {}
6743 }
6744 }
6745
6746 if self.left_dock.read(cx).is_open() {
6747 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6748 context.set("left_dock", active_panel.panel_key());
6749 }
6750 }
6751
6752 if self.right_dock.read(cx).is_open() {
6753 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6754 context.set("right_dock", active_panel.panel_key());
6755 }
6756 }
6757
6758 if self.bottom_dock.read(cx).is_open() {
6759 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6760 context.set("bottom_dock", active_panel.panel_key());
6761 }
6762 }
6763
6764 context
6765 }
6766
6767 /// Multiworkspace uses this to add workspace action handling to itself
6768 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6769 self.add_workspace_actions_listeners(div, window, cx)
6770 .on_action(cx.listener(
6771 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6772 for action in &action_sequence.0 {
6773 window.dispatch_action(action.boxed_clone(), cx);
6774 }
6775 },
6776 ))
6777 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6778 .on_action(cx.listener(Self::close_all_items_and_panes))
6779 .on_action(cx.listener(Self::close_item_in_all_panes))
6780 .on_action(cx.listener(Self::save_all))
6781 .on_action(cx.listener(Self::send_keystrokes))
6782 .on_action(cx.listener(Self::add_folder_to_project))
6783 .on_action(cx.listener(Self::follow_next_collaborator))
6784 .on_action(cx.listener(Self::activate_pane_at_index))
6785 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6786 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6787 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6788 .on_action(cx.listener(Self::toggle_theme_mode))
6789 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6790 let pane = workspace.active_pane().clone();
6791 workspace.unfollow_in_pane(&pane, window, cx);
6792 }))
6793 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6794 workspace
6795 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6796 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6797 }))
6798 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6799 workspace
6800 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6801 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6802 }))
6803 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6804 workspace
6805 .save_active_item(SaveIntent::SaveAs, window, cx)
6806 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6807 }))
6808 .on_action(
6809 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6810 workspace.activate_previous_pane(window, cx)
6811 }),
6812 )
6813 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6814 workspace.activate_next_pane(window, cx)
6815 }))
6816 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6817 workspace.activate_last_pane(window, cx)
6818 }))
6819 .on_action(
6820 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6821 workspace.activate_next_window(cx)
6822 }),
6823 )
6824 .on_action(
6825 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6826 workspace.activate_previous_window(cx)
6827 }),
6828 )
6829 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6830 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6831 }))
6832 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6833 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6834 }))
6835 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6836 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6837 }))
6838 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6839 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6840 }))
6841 .on_action(cx.listener(
6842 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6843 workspace.move_item_to_pane_in_direction(action, window, cx)
6844 },
6845 ))
6846 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6847 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6848 }))
6849 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6850 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6851 }))
6852 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6853 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6854 }))
6855 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6856 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6857 }))
6858 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6859 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6860 SplitDirection::Down,
6861 SplitDirection::Up,
6862 SplitDirection::Right,
6863 SplitDirection::Left,
6864 ];
6865 for dir in DIRECTION_PRIORITY {
6866 if workspace.find_pane_in_direction(dir, cx).is_some() {
6867 workspace.swap_pane_in_direction(dir, cx);
6868 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6869 break;
6870 }
6871 }
6872 }))
6873 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6874 workspace.move_pane_to_border(SplitDirection::Left, cx)
6875 }))
6876 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6877 workspace.move_pane_to_border(SplitDirection::Right, cx)
6878 }))
6879 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6880 workspace.move_pane_to_border(SplitDirection::Up, cx)
6881 }))
6882 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6883 workspace.move_pane_to_border(SplitDirection::Down, cx)
6884 }))
6885 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6886 this.toggle_dock(DockPosition::Left, window, cx);
6887 }))
6888 .on_action(cx.listener(
6889 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6890 workspace.toggle_dock(DockPosition::Right, window, cx);
6891 },
6892 ))
6893 .on_action(cx.listener(
6894 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6895 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6896 },
6897 ))
6898 .on_action(cx.listener(
6899 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6900 if !workspace.close_active_dock(window, cx) {
6901 cx.propagate();
6902 }
6903 },
6904 ))
6905 .on_action(
6906 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6907 workspace.close_all_docks(window, cx);
6908 }),
6909 )
6910 .on_action(cx.listener(Self::toggle_all_docks))
6911 .on_action(cx.listener(
6912 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6913 workspace.clear_all_notifications(cx);
6914 },
6915 ))
6916 .on_action(cx.listener(
6917 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6918 workspace.clear_navigation_history(window, cx);
6919 },
6920 ))
6921 .on_action(cx.listener(
6922 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6923 if let Some((notification_id, _)) = workspace.notifications.pop() {
6924 workspace.suppress_notification(¬ification_id, cx);
6925 }
6926 },
6927 ))
6928 .on_action(cx.listener(
6929 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6930 workspace.show_worktree_trust_security_modal(true, window, cx);
6931 },
6932 ))
6933 .on_action(
6934 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6935 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6936 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6937 trusted_worktrees.clear_trusted_paths()
6938 });
6939 let db = WorkspaceDb::global(cx);
6940 cx.spawn(async move |_, cx| {
6941 if db.clear_trusted_worktrees().await.log_err().is_some() {
6942 cx.update(|cx| reload(cx));
6943 }
6944 })
6945 .detach();
6946 }
6947 }),
6948 )
6949 .on_action(cx.listener(
6950 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
6951 workspace.reopen_closed_item(window, cx).detach();
6952 },
6953 ))
6954 .on_action(cx.listener(
6955 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
6956 for dock in workspace.all_docks() {
6957 if dock.focus_handle(cx).contains_focused(window, cx) {
6958 let panel = dock.read(cx).active_panel().cloned();
6959 if let Some(panel) = panel {
6960 dock.update(cx, |dock, cx| {
6961 dock.set_panel_size_state(
6962 panel.as_ref(),
6963 dock::PanelSizeState::default(),
6964 cx,
6965 );
6966 });
6967 }
6968 return;
6969 }
6970 }
6971 },
6972 ))
6973 .on_action(cx.listener(
6974 |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
6975 for dock in workspace.all_docks() {
6976 let panel = dock.read(cx).visible_panel().cloned();
6977 if let Some(panel) = panel {
6978 dock.update(cx, |dock, cx| {
6979 dock.set_panel_size_state(
6980 panel.as_ref(),
6981 dock::PanelSizeState::default(),
6982 cx,
6983 );
6984 });
6985 }
6986 }
6987 },
6988 ))
6989 .on_action(cx.listener(
6990 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
6991 adjust_active_dock_size_by_px(
6992 px_with_ui_font_fallback(act.px, cx),
6993 workspace,
6994 window,
6995 cx,
6996 );
6997 },
6998 ))
6999 .on_action(cx.listener(
7000 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
7001 adjust_active_dock_size_by_px(
7002 px_with_ui_font_fallback(act.px, cx) * -1.,
7003 workspace,
7004 window,
7005 cx,
7006 );
7007 },
7008 ))
7009 .on_action(cx.listener(
7010 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
7011 adjust_open_docks_size_by_px(
7012 px_with_ui_font_fallback(act.px, cx),
7013 workspace,
7014 window,
7015 cx,
7016 );
7017 },
7018 ))
7019 .on_action(cx.listener(
7020 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
7021 adjust_open_docks_size_by_px(
7022 px_with_ui_font_fallback(act.px, cx) * -1.,
7023 workspace,
7024 window,
7025 cx,
7026 );
7027 },
7028 ))
7029 .on_action(cx.listener(Workspace::toggle_centered_layout))
7030 .on_action(cx.listener(
7031 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
7032 if let Some(active_dock) = workspace.active_dock(window, cx) {
7033 let dock = active_dock.read(cx);
7034 if let Some(active_panel) = dock.active_panel() {
7035 if active_panel.pane(cx).is_none() {
7036 let mut recent_pane: Option<Entity<Pane>> = None;
7037 let mut recent_timestamp = 0;
7038 for pane_handle in workspace.panes() {
7039 let pane = pane_handle.read(cx);
7040 for entry in pane.activation_history() {
7041 if entry.timestamp > recent_timestamp {
7042 recent_timestamp = entry.timestamp;
7043 recent_pane = Some(pane_handle.clone());
7044 }
7045 }
7046 }
7047
7048 if let Some(pane) = recent_pane {
7049 pane.update(cx, |pane, cx| {
7050 let current_index = pane.active_item_index();
7051 let items_len = pane.items_len();
7052 if items_len > 0 {
7053 let next_index = if current_index + 1 < items_len {
7054 current_index + 1
7055 } else {
7056 0
7057 };
7058 pane.activate_item(
7059 next_index, false, false, window, cx,
7060 );
7061 }
7062 });
7063 return;
7064 }
7065 }
7066 }
7067 }
7068 cx.propagate();
7069 },
7070 ))
7071 .on_action(cx.listener(
7072 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
7073 if let Some(active_dock) = workspace.active_dock(window, cx) {
7074 let dock = active_dock.read(cx);
7075 if let Some(active_panel) = dock.active_panel() {
7076 if active_panel.pane(cx).is_none() {
7077 let mut recent_pane: Option<Entity<Pane>> = None;
7078 let mut recent_timestamp = 0;
7079 for pane_handle in workspace.panes() {
7080 let pane = pane_handle.read(cx);
7081 for entry in pane.activation_history() {
7082 if entry.timestamp > recent_timestamp {
7083 recent_timestamp = entry.timestamp;
7084 recent_pane = Some(pane_handle.clone());
7085 }
7086 }
7087 }
7088
7089 if let Some(pane) = recent_pane {
7090 pane.update(cx, |pane, cx| {
7091 let current_index = pane.active_item_index();
7092 let items_len = pane.items_len();
7093 if items_len > 0 {
7094 let prev_index = if current_index > 0 {
7095 current_index - 1
7096 } else {
7097 items_len.saturating_sub(1)
7098 };
7099 pane.activate_item(
7100 prev_index, false, false, window, cx,
7101 );
7102 }
7103 });
7104 return;
7105 }
7106 }
7107 }
7108 }
7109 cx.propagate();
7110 },
7111 ))
7112 .on_action(cx.listener(
7113 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
7114 if let Some(active_dock) = workspace.active_dock(window, cx) {
7115 let dock = active_dock.read(cx);
7116 if let Some(active_panel) = dock.active_panel() {
7117 if active_panel.pane(cx).is_none() {
7118 let active_pane = workspace.active_pane().clone();
7119 active_pane.update(cx, |pane, cx| {
7120 pane.close_active_item(action, window, cx)
7121 .detach_and_log_err(cx);
7122 });
7123 return;
7124 }
7125 }
7126 }
7127 cx.propagate();
7128 },
7129 ))
7130 .on_action(
7131 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
7132 let pane = workspace.active_pane().clone();
7133 if let Some(item) = pane.read(cx).active_item() {
7134 item.toggle_read_only(window, cx);
7135 }
7136 }),
7137 )
7138 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
7139 workspace.focus_center_pane(window, cx);
7140 }))
7141 .on_action(cx.listener(Workspace::cancel))
7142 }
7143
7144 #[cfg(any(test, feature = "test-support"))]
7145 pub fn set_random_database_id(&mut self) {
7146 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
7147 }
7148
7149 #[cfg(any(test, feature = "test-support"))]
7150 pub(crate) fn test_new(
7151 project: Entity<Project>,
7152 window: &mut Window,
7153 cx: &mut Context<Self>,
7154 ) -> Self {
7155 use node_runtime::NodeRuntime;
7156 use session::Session;
7157
7158 let client = project.read(cx).client();
7159 let user_store = project.read(cx).user_store();
7160 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
7161 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
7162 window.activate_window();
7163 let app_state = Arc::new(AppState {
7164 languages: project.read(cx).languages().clone(),
7165 workspace_store,
7166 client,
7167 user_store,
7168 fs: project.read(cx).fs().clone(),
7169 build_window_options: |_, _| Default::default(),
7170 node_runtime: NodeRuntime::unavailable(),
7171 session,
7172 });
7173 let workspace = Self::new(Default::default(), project, app_state, window, cx);
7174 workspace
7175 .active_pane
7176 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
7177 workspace
7178 }
7179
7180 pub fn register_action<A: Action>(
7181 &mut self,
7182 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
7183 ) -> &mut Self {
7184 let callback = Arc::new(callback);
7185
7186 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
7187 let callback = callback.clone();
7188 div.on_action(cx.listener(move |workspace, event, window, cx| {
7189 (callback)(workspace, event, window, cx)
7190 }))
7191 }));
7192 self
7193 }
7194 pub fn register_action_renderer(
7195 &mut self,
7196 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
7197 ) -> &mut Self {
7198 self.workspace_actions.push(Box::new(callback));
7199 self
7200 }
7201
7202 fn add_workspace_actions_listeners(
7203 &self,
7204 mut div: Div,
7205 window: &mut Window,
7206 cx: &mut Context<Self>,
7207 ) -> Div {
7208 for action in self.workspace_actions.iter() {
7209 div = (action)(div, self, window, cx)
7210 }
7211 div
7212 }
7213
7214 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
7215 self.modal_layer.read(cx).has_active_modal()
7216 }
7217
7218 pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
7219 self.modal_layer
7220 .read(cx)
7221 .is_active_modal_command_palette(cx)
7222 }
7223
7224 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
7225 self.modal_layer.read(cx).active_modal()
7226 }
7227
7228 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
7229 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
7230 /// If no modal is active, the new modal will be shown.
7231 ///
7232 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
7233 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
7234 /// will not be shown.
7235 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
7236 where
7237 B: FnOnce(&mut Window, &mut Context<V>) -> V,
7238 {
7239 self.modal_layer.update(cx, |modal_layer, cx| {
7240 modal_layer.toggle_modal(window, cx, build)
7241 })
7242 }
7243
7244 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
7245 self.modal_layer
7246 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
7247 }
7248
7249 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
7250 self.toast_layer
7251 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
7252 }
7253
7254 pub fn toggle_centered_layout(
7255 &mut self,
7256 _: &ToggleCenteredLayout,
7257 _: &mut Window,
7258 cx: &mut Context<Self>,
7259 ) {
7260 self.centered_layout = !self.centered_layout;
7261 if let Some(database_id) = self.database_id() {
7262 let db = WorkspaceDb::global(cx);
7263 let centered_layout = self.centered_layout;
7264 cx.background_spawn(async move {
7265 db.set_centered_layout(database_id, centered_layout).await
7266 })
7267 .detach_and_log_err(cx);
7268 }
7269 cx.notify();
7270 }
7271
7272 fn adjust_padding(padding: Option<f32>) -> f32 {
7273 padding
7274 .unwrap_or(CenteredPaddingSettings::default().0)
7275 .clamp(
7276 CenteredPaddingSettings::MIN_PADDING,
7277 CenteredPaddingSettings::MAX_PADDING,
7278 )
7279 }
7280
7281 fn render_dock(
7282 &self,
7283 position: DockPosition,
7284 dock: &Entity<Dock>,
7285 window: &mut Window,
7286 cx: &mut App,
7287 ) -> Option<Div> {
7288 if self.zoomed_position == Some(position) {
7289 return None;
7290 }
7291
7292 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7293 let pane = panel.pane(cx)?;
7294 let follower_states = &self.follower_states;
7295 leader_border_for_pane(follower_states, &pane, window, cx)
7296 });
7297
7298 let mut container = div()
7299 .flex()
7300 .overflow_hidden()
7301 .flex_none()
7302 .child(dock.clone())
7303 .children(leader_border);
7304
7305 // Apply sizing only when the dock is open. When closed the dock is still
7306 // included in the element tree so its focus handle remains mounted — without
7307 // this, toggle_panel_focus cannot focus the panel when the dock is closed.
7308 let dock = dock.read(cx);
7309 if let Some(panel) = dock.visible_panel() {
7310 let size_state = dock.stored_panel_size_state(panel.as_ref());
7311 if position.axis() == Axis::Horizontal {
7312 let use_flexible = panel.has_flexible_size(window, cx);
7313 let flex_grow = if use_flexible {
7314 size_state
7315 .and_then(|state| state.flex)
7316 .or_else(|| self.default_dock_flex(position))
7317 } else {
7318 None
7319 };
7320 if let Some(grow) = flex_grow {
7321 let grow = grow.max(0.001);
7322 let style = container.style();
7323 style.flex_grow = Some(grow);
7324 style.flex_shrink = Some(1.0);
7325 style.flex_basis = Some(relative(0.).into());
7326 } else {
7327 let size = size_state
7328 .and_then(|state| state.size)
7329 .unwrap_or_else(|| panel.default_size(window, cx));
7330 container = container.w(size);
7331 }
7332 } else {
7333 let size = size_state
7334 .and_then(|state| state.size)
7335 .unwrap_or_else(|| panel.default_size(window, cx));
7336 container = container.h(size);
7337 }
7338 }
7339
7340 Some(container)
7341 }
7342
7343 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7344 window
7345 .root::<MultiWorkspace>()
7346 .flatten()
7347 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7348 }
7349
7350 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7351 self.zoomed.as_ref()
7352 }
7353
7354 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7355 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7356 return;
7357 };
7358 let windows = cx.windows();
7359 let next_window =
7360 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7361 || {
7362 windows
7363 .iter()
7364 .cycle()
7365 .skip_while(|window| window.window_id() != current_window_id)
7366 .nth(1)
7367 },
7368 );
7369
7370 if let Some(window) = next_window {
7371 window
7372 .update(cx, |_, window, _| window.activate_window())
7373 .ok();
7374 }
7375 }
7376
7377 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7378 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7379 return;
7380 };
7381 let windows = cx.windows();
7382 let prev_window =
7383 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7384 || {
7385 windows
7386 .iter()
7387 .rev()
7388 .cycle()
7389 .skip_while(|window| window.window_id() != current_window_id)
7390 .nth(1)
7391 },
7392 );
7393
7394 if let Some(window) = prev_window {
7395 window
7396 .update(cx, |_, window, _| window.activate_window())
7397 .ok();
7398 }
7399 }
7400
7401 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7402 if cx.stop_active_drag(window) {
7403 } else if let Some((notification_id, _)) = self.notifications.pop() {
7404 dismiss_app_notification(¬ification_id, cx);
7405 } else {
7406 cx.propagate();
7407 }
7408 }
7409
7410 fn resize_dock(
7411 &mut self,
7412 dock_pos: DockPosition,
7413 new_size: Pixels,
7414 window: &mut Window,
7415 cx: &mut Context<Self>,
7416 ) {
7417 match dock_pos {
7418 DockPosition::Left => self.resize_left_dock(new_size, window, cx),
7419 DockPosition::Right => self.resize_right_dock(new_size, window, cx),
7420 DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
7421 }
7422 }
7423
7424 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7425 let workspace_width = self.bounds.size.width;
7426 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7427
7428 self.right_dock.read_with(cx, |right_dock, cx| {
7429 let right_dock_size = right_dock
7430 .stored_active_panel_size(window, cx)
7431 .unwrap_or(Pixels::ZERO);
7432 if right_dock_size + size > workspace_width {
7433 size = workspace_width - right_dock_size
7434 }
7435 });
7436
7437 let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
7438 self.left_dock.update(cx, |left_dock, cx| {
7439 if WorkspaceSettings::get_global(cx)
7440 .resize_all_panels_in_dock
7441 .contains(&DockPosition::Left)
7442 {
7443 left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7444 } else {
7445 left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7446 }
7447 });
7448 }
7449
7450 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7451 let workspace_width = self.bounds.size.width;
7452 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7453 self.left_dock.read_with(cx, |left_dock, cx| {
7454 let left_dock_size = left_dock
7455 .stored_active_panel_size(window, cx)
7456 .unwrap_or(Pixels::ZERO);
7457 if left_dock_size + size > workspace_width {
7458 size = workspace_width - left_dock_size
7459 }
7460 });
7461 let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
7462 self.right_dock.update(cx, |right_dock, cx| {
7463 if WorkspaceSettings::get_global(cx)
7464 .resize_all_panels_in_dock
7465 .contains(&DockPosition::Right)
7466 {
7467 right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7468 } else {
7469 right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7470 }
7471 });
7472 }
7473
7474 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7475 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7476 self.bottom_dock.update(cx, |bottom_dock, cx| {
7477 if WorkspaceSettings::get_global(cx)
7478 .resize_all_panels_in_dock
7479 .contains(&DockPosition::Bottom)
7480 {
7481 bottom_dock.resize_all_panels(Some(size), None, window, cx);
7482 } else {
7483 bottom_dock.resize_active_panel(Some(size), None, window, cx);
7484 }
7485 });
7486 }
7487
7488 fn toggle_edit_predictions_all_files(
7489 &mut self,
7490 _: &ToggleEditPrediction,
7491 _window: &mut Window,
7492 cx: &mut Context<Self>,
7493 ) {
7494 let fs = self.project().read(cx).fs().clone();
7495 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7496 update_settings_file(fs, cx, move |file, _| {
7497 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7498 });
7499 }
7500
7501 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7502 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7503 let next_mode = match current_mode {
7504 Some(theme::ThemeAppearanceMode::Light) => theme::ThemeAppearanceMode::Dark,
7505 Some(theme::ThemeAppearanceMode::Dark) => theme::ThemeAppearanceMode::Light,
7506 Some(theme::ThemeAppearanceMode::System) | None => match cx.theme().appearance() {
7507 theme::Appearance::Light => theme::ThemeAppearanceMode::Dark,
7508 theme::Appearance::Dark => theme::ThemeAppearanceMode::Light,
7509 },
7510 };
7511
7512 let fs = self.project().read(cx).fs().clone();
7513 settings::update_settings_file(fs, cx, move |settings, _cx| {
7514 theme::set_mode(settings, next_mode);
7515 });
7516 }
7517
7518 pub fn show_worktree_trust_security_modal(
7519 &mut self,
7520 toggle: bool,
7521 window: &mut Window,
7522 cx: &mut Context<Self>,
7523 ) {
7524 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7525 if toggle {
7526 security_modal.update(cx, |security_modal, cx| {
7527 security_modal.dismiss(cx);
7528 })
7529 } else {
7530 security_modal.update(cx, |security_modal, cx| {
7531 security_modal.refresh_restricted_paths(cx);
7532 });
7533 }
7534 } else {
7535 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7536 .map(|trusted_worktrees| {
7537 trusted_worktrees
7538 .read(cx)
7539 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7540 })
7541 .unwrap_or(false);
7542 if has_restricted_worktrees {
7543 let project = self.project().read(cx);
7544 let remote_host = project
7545 .remote_connection_options(cx)
7546 .map(RemoteHostLocation::from);
7547 let worktree_store = project.worktree_store().downgrade();
7548 self.toggle_modal(window, cx, |_, cx| {
7549 SecurityModal::new(worktree_store, remote_host, cx)
7550 });
7551 }
7552 }
7553 }
7554}
7555
7556pub trait AnyActiveCall {
7557 fn entity(&self) -> AnyEntity;
7558 fn is_in_room(&self, _: &App) -> bool;
7559 fn room_id(&self, _: &App) -> Option<u64>;
7560 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7561 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7562 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7563 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7564 fn is_sharing_project(&self, _: &App) -> bool;
7565 fn has_remote_participants(&self, _: &App) -> bool;
7566 fn local_participant_is_guest(&self, _: &App) -> bool;
7567 fn client(&self, _: &App) -> Arc<Client>;
7568 fn share_on_join(&self, _: &App) -> bool;
7569 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7570 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7571 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7572 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7573 fn join_project(
7574 &self,
7575 _: u64,
7576 _: Arc<LanguageRegistry>,
7577 _: Arc<dyn Fs>,
7578 _: &mut App,
7579 ) -> Task<Result<Entity<Project>>>;
7580 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7581 fn subscribe(
7582 &self,
7583 _: &mut Window,
7584 _: &mut Context<Workspace>,
7585 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7586 ) -> Subscription;
7587 fn create_shared_screen(
7588 &self,
7589 _: PeerId,
7590 _: &Entity<Pane>,
7591 _: &mut Window,
7592 _: &mut App,
7593 ) -> Option<Entity<SharedScreen>>;
7594}
7595
7596#[derive(Clone)]
7597pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7598impl Global for GlobalAnyActiveCall {}
7599
7600impl GlobalAnyActiveCall {
7601 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7602 cx.try_global()
7603 }
7604
7605 pub(crate) fn global(cx: &App) -> &Self {
7606 cx.global()
7607 }
7608}
7609
7610pub fn merge_conflict_notification_id() -> NotificationId {
7611 struct MergeConflictNotification;
7612 NotificationId::unique::<MergeConflictNotification>()
7613}
7614
7615/// Workspace-local view of a remote participant's location.
7616#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7617pub enum ParticipantLocation {
7618 SharedProject { project_id: u64 },
7619 UnsharedProject,
7620 External,
7621}
7622
7623impl ParticipantLocation {
7624 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7625 match location
7626 .and_then(|l| l.variant)
7627 .context("participant location was not provided")?
7628 {
7629 proto::participant_location::Variant::SharedProject(project) => {
7630 Ok(Self::SharedProject {
7631 project_id: project.id,
7632 })
7633 }
7634 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7635 proto::participant_location::Variant::External(_) => Ok(Self::External),
7636 }
7637 }
7638}
7639/// Workspace-local view of a remote collaborator's state.
7640/// This is the subset of `call::RemoteParticipant` that workspace needs.
7641#[derive(Clone)]
7642pub struct RemoteCollaborator {
7643 pub user: Arc<User>,
7644 pub peer_id: PeerId,
7645 pub location: ParticipantLocation,
7646 pub participant_index: ParticipantIndex,
7647}
7648
7649pub enum ActiveCallEvent {
7650 ParticipantLocationChanged { participant_id: PeerId },
7651 RemoteVideoTracksChanged { participant_id: PeerId },
7652}
7653
7654fn leader_border_for_pane(
7655 follower_states: &HashMap<CollaboratorId, FollowerState>,
7656 pane: &Entity<Pane>,
7657 _: &Window,
7658 cx: &App,
7659) -> Option<Div> {
7660 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7661 if state.pane() == pane {
7662 Some((*leader_id, state))
7663 } else {
7664 None
7665 }
7666 })?;
7667
7668 let mut leader_color = match leader_id {
7669 CollaboratorId::PeerId(leader_peer_id) => {
7670 let leader = GlobalAnyActiveCall::try_global(cx)?
7671 .0
7672 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7673
7674 cx.theme()
7675 .players()
7676 .color_for_participant(leader.participant_index.0)
7677 .cursor
7678 }
7679 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7680 };
7681 leader_color.fade_out(0.3);
7682 Some(
7683 div()
7684 .absolute()
7685 .size_full()
7686 .left_0()
7687 .top_0()
7688 .border_2()
7689 .border_color(leader_color),
7690 )
7691}
7692
7693fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7694 ZED_WINDOW_POSITION
7695 .zip(*ZED_WINDOW_SIZE)
7696 .map(|(position, size)| Bounds {
7697 origin: position,
7698 size,
7699 })
7700}
7701
7702fn open_items(
7703 serialized_workspace: Option<SerializedWorkspace>,
7704 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7705 window: &mut Window,
7706 cx: &mut Context<Workspace>,
7707) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7708 let restored_items = serialized_workspace.map(|serialized_workspace| {
7709 Workspace::load_workspace(
7710 serialized_workspace,
7711 project_paths_to_open
7712 .iter()
7713 .map(|(_, project_path)| project_path)
7714 .cloned()
7715 .collect(),
7716 window,
7717 cx,
7718 )
7719 });
7720
7721 cx.spawn_in(window, async move |workspace, cx| {
7722 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7723
7724 if let Some(restored_items) = restored_items {
7725 let restored_items = restored_items.await?;
7726
7727 let restored_project_paths = restored_items
7728 .iter()
7729 .filter_map(|item| {
7730 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7731 .ok()
7732 .flatten()
7733 })
7734 .collect::<HashSet<_>>();
7735
7736 for restored_item in restored_items {
7737 opened_items.push(restored_item.map(Ok));
7738 }
7739
7740 project_paths_to_open
7741 .iter_mut()
7742 .for_each(|(_, project_path)| {
7743 if let Some(project_path_to_open) = project_path
7744 && restored_project_paths.contains(project_path_to_open)
7745 {
7746 *project_path = None;
7747 }
7748 });
7749 } else {
7750 for _ in 0..project_paths_to_open.len() {
7751 opened_items.push(None);
7752 }
7753 }
7754 assert!(opened_items.len() == project_paths_to_open.len());
7755
7756 let tasks =
7757 project_paths_to_open
7758 .into_iter()
7759 .enumerate()
7760 .map(|(ix, (abs_path, project_path))| {
7761 let workspace = workspace.clone();
7762 cx.spawn(async move |cx| {
7763 let file_project_path = project_path?;
7764 let abs_path_task = workspace.update(cx, |workspace, cx| {
7765 workspace.project().update(cx, |project, cx| {
7766 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7767 })
7768 });
7769
7770 // We only want to open file paths here. If one of the items
7771 // here is a directory, it was already opened further above
7772 // with a `find_or_create_worktree`.
7773 if let Ok(task) = abs_path_task
7774 && task.await.is_none_or(|p| p.is_file())
7775 {
7776 return Some((
7777 ix,
7778 workspace
7779 .update_in(cx, |workspace, window, cx| {
7780 workspace.open_path(
7781 file_project_path,
7782 None,
7783 true,
7784 window,
7785 cx,
7786 )
7787 })
7788 .log_err()?
7789 .await,
7790 ));
7791 }
7792 None
7793 })
7794 });
7795
7796 let tasks = tasks.collect::<Vec<_>>();
7797
7798 let tasks = futures::future::join_all(tasks);
7799 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7800 opened_items[ix] = Some(path_open_result);
7801 }
7802
7803 Ok(opened_items)
7804 })
7805}
7806
7807#[derive(Clone)]
7808enum ActivateInDirectionTarget {
7809 Pane(Entity<Pane>),
7810 Dock(Entity<Dock>),
7811 Sidebar(FocusHandle),
7812}
7813
7814fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7815 window
7816 .update(cx, |multi_workspace, _, cx| {
7817 let workspace = multi_workspace.workspace().clone();
7818 workspace.update(cx, |workspace, cx| {
7819 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7820 struct DatabaseFailedNotification;
7821
7822 workspace.show_notification(
7823 NotificationId::unique::<DatabaseFailedNotification>(),
7824 cx,
7825 |cx| {
7826 cx.new(|cx| {
7827 MessageNotification::new("Failed to load the database file.", cx)
7828 .primary_message("File an Issue")
7829 .primary_icon(IconName::Plus)
7830 .primary_on_click(|window, cx| {
7831 window.dispatch_action(Box::new(FileBugReport), cx)
7832 })
7833 })
7834 },
7835 );
7836 }
7837 });
7838 })
7839 .log_err();
7840}
7841
7842fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7843 if val == 0 {
7844 ThemeSettings::get_global(cx).ui_font_size(cx)
7845 } else {
7846 px(val as f32)
7847 }
7848}
7849
7850fn adjust_active_dock_size_by_px(
7851 px: Pixels,
7852 workspace: &mut Workspace,
7853 window: &mut Window,
7854 cx: &mut Context<Workspace>,
7855) {
7856 let Some(active_dock) = workspace
7857 .all_docks()
7858 .into_iter()
7859 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7860 else {
7861 return;
7862 };
7863 let dock = active_dock.read(cx);
7864 let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
7865 return;
7866 };
7867 workspace.resize_dock(dock.position(), panel_size + px, window, cx);
7868}
7869
7870fn adjust_open_docks_size_by_px(
7871 px: Pixels,
7872 workspace: &mut Workspace,
7873 window: &mut Window,
7874 cx: &mut Context<Workspace>,
7875) {
7876 let docks = workspace
7877 .all_docks()
7878 .into_iter()
7879 .filter_map(|dock_entity| {
7880 let dock = dock_entity.read(cx);
7881 if dock.is_open() {
7882 let dock_pos = dock.position();
7883 let panel_size = workspace.dock_size(&dock, window, cx)?;
7884 Some((dock_pos, panel_size + px))
7885 } else {
7886 None
7887 }
7888 })
7889 .collect::<Vec<_>>();
7890
7891 for (position, new_size) in docks {
7892 workspace.resize_dock(position, new_size, window, cx);
7893 }
7894}
7895
7896impl Focusable for Workspace {
7897 fn focus_handle(&self, cx: &App) -> FocusHandle {
7898 self.active_pane.focus_handle(cx)
7899 }
7900}
7901
7902#[derive(Clone)]
7903struct DraggedDock(DockPosition);
7904
7905impl Render for DraggedDock {
7906 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7907 gpui::Empty
7908 }
7909}
7910
7911impl Render for Workspace {
7912 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7913 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7914 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7915 log::info!("Rendered first frame");
7916 }
7917
7918 let centered_layout = self.centered_layout
7919 && self.center.panes().len() == 1
7920 && self.active_item(cx).is_some();
7921 let render_padding = |size| {
7922 (size > 0.0).then(|| {
7923 div()
7924 .h_full()
7925 .w(relative(size))
7926 .bg(cx.theme().colors().editor_background)
7927 .border_color(cx.theme().colors().pane_group_border)
7928 })
7929 };
7930 let paddings = if centered_layout {
7931 let settings = WorkspaceSettings::get_global(cx).centered_layout;
7932 (
7933 render_padding(Self::adjust_padding(
7934 settings.left_padding.map(|padding| padding.0),
7935 )),
7936 render_padding(Self::adjust_padding(
7937 settings.right_padding.map(|padding| padding.0),
7938 )),
7939 )
7940 } else {
7941 (None, None)
7942 };
7943 let ui_font = theme::setup_ui_font(window, cx);
7944
7945 let theme = cx.theme().clone();
7946 let colors = theme.colors();
7947 let notification_entities = self
7948 .notifications
7949 .iter()
7950 .map(|(_, notification)| notification.entity_id())
7951 .collect::<Vec<_>>();
7952 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
7953
7954 div()
7955 .relative()
7956 .size_full()
7957 .flex()
7958 .flex_col()
7959 .font(ui_font)
7960 .gap_0()
7961 .justify_start()
7962 .items_start()
7963 .text_color(colors.text)
7964 .overflow_hidden()
7965 .children(self.titlebar_item.clone())
7966 .on_modifiers_changed(move |_, _, cx| {
7967 for &id in ¬ification_entities {
7968 cx.notify(id);
7969 }
7970 })
7971 .child(
7972 div()
7973 .size_full()
7974 .relative()
7975 .flex_1()
7976 .flex()
7977 .flex_col()
7978 .child(
7979 div()
7980 .id("workspace")
7981 .bg(colors.background)
7982 .relative()
7983 .flex_1()
7984 .w_full()
7985 .flex()
7986 .flex_col()
7987 .overflow_hidden()
7988 .border_t_1()
7989 .border_b_1()
7990 .border_color(colors.border)
7991 .child({
7992 let this = cx.entity();
7993 canvas(
7994 move |bounds, window, cx| {
7995 this.update(cx, |this, cx| {
7996 let bounds_changed = this.bounds != bounds;
7997 this.bounds = bounds;
7998
7999 if bounds_changed {
8000 this.left_dock.update(cx, |dock, cx| {
8001 dock.clamp_panel_size(
8002 bounds.size.width,
8003 window,
8004 cx,
8005 )
8006 });
8007
8008 this.right_dock.update(cx, |dock, cx| {
8009 dock.clamp_panel_size(
8010 bounds.size.width,
8011 window,
8012 cx,
8013 )
8014 });
8015
8016 this.bottom_dock.update(cx, |dock, cx| {
8017 dock.clamp_panel_size(
8018 bounds.size.height,
8019 window,
8020 cx,
8021 )
8022 });
8023 }
8024 })
8025 },
8026 |_, _, _, _| {},
8027 )
8028 .absolute()
8029 .size_full()
8030 })
8031 .when(self.zoomed.is_none(), |this| {
8032 this.on_drag_move(cx.listener(
8033 move |workspace,
8034 e: &DragMoveEvent<DraggedDock>,
8035 window,
8036 cx| {
8037 if workspace.previous_dock_drag_coordinates
8038 != Some(e.event.position)
8039 {
8040 workspace.previous_dock_drag_coordinates =
8041 Some(e.event.position);
8042
8043 match e.drag(cx).0 {
8044 DockPosition::Left => {
8045 workspace.resize_left_dock(
8046 e.event.position.x
8047 - workspace.bounds.left(),
8048 window,
8049 cx,
8050 );
8051 }
8052 DockPosition::Right => {
8053 workspace.resize_right_dock(
8054 workspace.bounds.right()
8055 - e.event.position.x,
8056 window,
8057 cx,
8058 );
8059 }
8060 DockPosition::Bottom => {
8061 workspace.resize_bottom_dock(
8062 workspace.bounds.bottom()
8063 - e.event.position.y,
8064 window,
8065 cx,
8066 );
8067 }
8068 };
8069 workspace.serialize_workspace(window, cx);
8070 }
8071 },
8072 ))
8073
8074 })
8075 .child({
8076 match bottom_dock_layout {
8077 BottomDockLayout::Full => div()
8078 .flex()
8079 .flex_col()
8080 .h_full()
8081 .child(
8082 div()
8083 .flex()
8084 .flex_row()
8085 .flex_1()
8086 .overflow_hidden()
8087 .children(self.render_dock(
8088 DockPosition::Left,
8089 &self.left_dock,
8090 window,
8091 cx,
8092 ))
8093
8094 .child(
8095 div()
8096 .flex()
8097 .flex_col()
8098 .flex_1()
8099 .overflow_hidden()
8100 .child(
8101 h_flex()
8102 .flex_1()
8103 .when_some(
8104 paddings.0,
8105 |this, p| {
8106 this.child(
8107 p.border_r_1(),
8108 )
8109 },
8110 )
8111 .child(self.center.render(
8112 self.zoomed.as_ref(),
8113 &PaneRenderContext {
8114 follower_states:
8115 &self.follower_states,
8116 active_call: self.active_call(),
8117 active_pane: &self.active_pane,
8118 app_state: &self.app_state,
8119 project: &self.project,
8120 workspace: &self.weak_self,
8121 },
8122 window,
8123 cx,
8124 ))
8125 .when_some(
8126 paddings.1,
8127 |this, p| {
8128 this.child(
8129 p.border_l_1(),
8130 )
8131 },
8132 ),
8133 ),
8134 )
8135
8136 .children(self.render_dock(
8137 DockPosition::Right,
8138 &self.right_dock,
8139 window,
8140 cx,
8141 )),
8142 )
8143 .child(div().w_full().children(self.render_dock(
8144 DockPosition::Bottom,
8145 &self.bottom_dock,
8146 window,
8147 cx
8148 ))),
8149
8150 BottomDockLayout::LeftAligned => div()
8151 .flex()
8152 .flex_row()
8153 .h_full()
8154 .child(
8155 div()
8156 .flex()
8157 .flex_col()
8158 .flex_1()
8159 .h_full()
8160 .child(
8161 div()
8162 .flex()
8163 .flex_row()
8164 .flex_1()
8165 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
8166
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 )
8196 .child(
8197 div()
8198 .w_full()
8199 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8200 ),
8201 )
8202 .children(self.render_dock(
8203 DockPosition::Right,
8204 &self.right_dock,
8205 window,
8206 cx,
8207 )),
8208 BottomDockLayout::RightAligned => div()
8209 .flex()
8210 .flex_row()
8211 .h_full()
8212 .children(self.render_dock(
8213 DockPosition::Left,
8214 &self.left_dock,
8215 window,
8216 cx,
8217 ))
8218
8219 .child(
8220 div()
8221 .flex()
8222 .flex_col()
8223 .flex_1()
8224 .h_full()
8225 .child(
8226 div()
8227 .flex()
8228 .flex_row()
8229 .flex_1()
8230 .child(
8231 div()
8232 .flex()
8233 .flex_col()
8234 .flex_1()
8235 .overflow_hidden()
8236 .child(
8237 h_flex()
8238 .flex_1()
8239 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8240 .child(self.center.render(
8241 self.zoomed.as_ref(),
8242 &PaneRenderContext {
8243 follower_states:
8244 &self.follower_states,
8245 active_call: self.active_call(),
8246 active_pane: &self.active_pane,
8247 app_state: &self.app_state,
8248 project: &self.project,
8249 workspace: &self.weak_self,
8250 },
8251 window,
8252 cx,
8253 ))
8254 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8255 )
8256 )
8257
8258 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
8259 )
8260 .child(
8261 div()
8262 .w_full()
8263 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8264 ),
8265 ),
8266 BottomDockLayout::Contained => div()
8267 .flex()
8268 .flex_row()
8269 .h_full()
8270 .children(self.render_dock(
8271 DockPosition::Left,
8272 &self.left_dock,
8273 window,
8274 cx,
8275 ))
8276
8277 .child(
8278 div()
8279 .flex()
8280 .flex_col()
8281 .flex_1()
8282 .overflow_hidden()
8283 .child(
8284 h_flex()
8285 .flex_1()
8286 .when_some(paddings.0, |this, p| {
8287 this.child(p.border_r_1())
8288 })
8289 .child(self.center.render(
8290 self.zoomed.as_ref(),
8291 &PaneRenderContext {
8292 follower_states:
8293 &self.follower_states,
8294 active_call: self.active_call(),
8295 active_pane: &self.active_pane,
8296 app_state: &self.app_state,
8297 project: &self.project,
8298 workspace: &self.weak_self,
8299 },
8300 window,
8301 cx,
8302 ))
8303 .when_some(paddings.1, |this, p| {
8304 this.child(p.border_l_1())
8305 }),
8306 )
8307 .children(self.render_dock(
8308 DockPosition::Bottom,
8309 &self.bottom_dock,
8310 window,
8311 cx,
8312 )),
8313 )
8314
8315 .children(self.render_dock(
8316 DockPosition::Right,
8317 &self.right_dock,
8318 window,
8319 cx,
8320 )),
8321 }
8322 })
8323 .children(self.zoomed.as_ref().and_then(|view| {
8324 let zoomed_view = view.upgrade()?;
8325 let div = div()
8326 .occlude()
8327 .absolute()
8328 .overflow_hidden()
8329 .border_color(colors.border)
8330 .bg(colors.background)
8331 .child(zoomed_view)
8332 .inset_0()
8333 .shadow_lg();
8334
8335 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8336 return Some(div);
8337 }
8338
8339 Some(match self.zoomed_position {
8340 Some(DockPosition::Left) => div.right_2().border_r_1(),
8341 Some(DockPosition::Right) => div.left_2().border_l_1(),
8342 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8343 None => {
8344 div.top_2().bottom_2().left_2().right_2().border_1()
8345 }
8346 })
8347 }))
8348 .children(self.render_notifications(window, cx)),
8349 )
8350 .when(self.status_bar_visible(cx), |parent| {
8351 parent.child(self.status_bar.clone())
8352 })
8353 .child(self.toast_layer.clone()),
8354 )
8355 }
8356}
8357
8358impl WorkspaceStore {
8359 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8360 Self {
8361 workspaces: Default::default(),
8362 _subscriptions: vec![
8363 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8364 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8365 ],
8366 client,
8367 }
8368 }
8369
8370 pub fn update_followers(
8371 &self,
8372 project_id: Option<u64>,
8373 update: proto::update_followers::Variant,
8374 cx: &App,
8375 ) -> Option<()> {
8376 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8377 let room_id = active_call.0.room_id(cx)?;
8378 self.client
8379 .send(proto::UpdateFollowers {
8380 room_id,
8381 project_id,
8382 variant: Some(update),
8383 })
8384 .log_err()
8385 }
8386
8387 pub async fn handle_follow(
8388 this: Entity<Self>,
8389 envelope: TypedEnvelope<proto::Follow>,
8390 mut cx: AsyncApp,
8391 ) -> Result<proto::FollowResponse> {
8392 this.update(&mut cx, |this, cx| {
8393 let follower = Follower {
8394 project_id: envelope.payload.project_id,
8395 peer_id: envelope.original_sender_id()?,
8396 };
8397
8398 let mut response = proto::FollowResponse::default();
8399
8400 this.workspaces.retain(|(window_handle, weak_workspace)| {
8401 let Some(workspace) = weak_workspace.upgrade() else {
8402 return false;
8403 };
8404 window_handle
8405 .update(cx, |_, window, cx| {
8406 workspace.update(cx, |workspace, cx| {
8407 let handler_response =
8408 workspace.handle_follow(follower.project_id, window, cx);
8409 if let Some(active_view) = handler_response.active_view
8410 && workspace.project.read(cx).remote_id() == follower.project_id
8411 {
8412 response.active_view = Some(active_view)
8413 }
8414 });
8415 })
8416 .is_ok()
8417 });
8418
8419 Ok(response)
8420 })
8421 }
8422
8423 async fn handle_update_followers(
8424 this: Entity<Self>,
8425 envelope: TypedEnvelope<proto::UpdateFollowers>,
8426 mut cx: AsyncApp,
8427 ) -> Result<()> {
8428 let leader_id = envelope.original_sender_id()?;
8429 let update = envelope.payload;
8430
8431 this.update(&mut cx, |this, cx| {
8432 this.workspaces.retain(|(window_handle, weak_workspace)| {
8433 let Some(workspace) = weak_workspace.upgrade() else {
8434 return false;
8435 };
8436 window_handle
8437 .update(cx, |_, window, cx| {
8438 workspace.update(cx, |workspace, cx| {
8439 let project_id = workspace.project.read(cx).remote_id();
8440 if update.project_id != project_id && update.project_id.is_some() {
8441 return;
8442 }
8443 workspace.handle_update_followers(
8444 leader_id,
8445 update.clone(),
8446 window,
8447 cx,
8448 );
8449 });
8450 })
8451 .is_ok()
8452 });
8453 Ok(())
8454 })
8455 }
8456
8457 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8458 self.workspaces.iter().map(|(_, weak)| weak)
8459 }
8460
8461 pub fn workspaces_with_windows(
8462 &self,
8463 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8464 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8465 }
8466}
8467
8468impl ViewId {
8469 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8470 Ok(Self {
8471 creator: message
8472 .creator
8473 .map(CollaboratorId::PeerId)
8474 .context("creator is missing")?,
8475 id: message.id,
8476 })
8477 }
8478
8479 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8480 if let CollaboratorId::PeerId(peer_id) = self.creator {
8481 Some(proto::ViewId {
8482 creator: Some(peer_id),
8483 id: self.id,
8484 })
8485 } else {
8486 None
8487 }
8488 }
8489}
8490
8491impl FollowerState {
8492 fn pane(&self) -> &Entity<Pane> {
8493 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8494 }
8495}
8496
8497pub trait WorkspaceHandle {
8498 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8499}
8500
8501impl WorkspaceHandle for Entity<Workspace> {
8502 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8503 self.read(cx)
8504 .worktrees(cx)
8505 .flat_map(|worktree| {
8506 let worktree_id = worktree.read(cx).id();
8507 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8508 worktree_id,
8509 path: f.path.clone(),
8510 })
8511 })
8512 .collect::<Vec<_>>()
8513 }
8514}
8515
8516pub async fn last_opened_workspace_location(
8517 db: &WorkspaceDb,
8518 fs: &dyn fs::Fs,
8519) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8520 db.last_workspace(fs)
8521 .await
8522 .log_err()
8523 .flatten()
8524 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8525}
8526
8527pub async fn last_session_workspace_locations(
8528 db: &WorkspaceDb,
8529 last_session_id: &str,
8530 last_session_window_stack: Option<Vec<WindowId>>,
8531 fs: &dyn fs::Fs,
8532) -> Option<Vec<SessionWorkspace>> {
8533 db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8534 .await
8535 .log_err()
8536}
8537
8538pub struct MultiWorkspaceRestoreResult {
8539 pub window_handle: WindowHandle<MultiWorkspace>,
8540 pub errors: Vec<anyhow::Error>,
8541}
8542
8543pub async fn restore_multiworkspace(
8544 multi_workspace: SerializedMultiWorkspace,
8545 app_state: Arc<AppState>,
8546 cx: &mut AsyncApp,
8547) -> anyhow::Result<MultiWorkspaceRestoreResult> {
8548 let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
8549 let mut group_iter = workspaces.into_iter();
8550 let first = group_iter
8551 .next()
8552 .context("window group must not be empty")?;
8553
8554 let window_handle = if first.paths.is_empty() {
8555 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
8556 .await?
8557 } else {
8558 let OpenResult { window, .. } = cx
8559 .update(|cx| {
8560 Workspace::new_local(
8561 first.paths.paths().to_vec(),
8562 app_state.clone(),
8563 None,
8564 None,
8565 None,
8566 true,
8567 cx,
8568 )
8569 })
8570 .await?;
8571 window
8572 };
8573
8574 let mut errors = Vec::new();
8575
8576 for session_workspace in group_iter {
8577 let error = if session_workspace.paths.is_empty() {
8578 cx.update(|cx| {
8579 open_workspace_by_id(
8580 session_workspace.workspace_id,
8581 app_state.clone(),
8582 Some(window_handle),
8583 cx,
8584 )
8585 })
8586 .await
8587 .err()
8588 } else {
8589 cx.update(|cx| {
8590 Workspace::new_local(
8591 session_workspace.paths.paths().to_vec(),
8592 app_state.clone(),
8593 Some(window_handle),
8594 None,
8595 None,
8596 false,
8597 cx,
8598 )
8599 })
8600 .await
8601 .err()
8602 };
8603
8604 if let Some(error) = error {
8605 errors.push(error);
8606 }
8607 }
8608
8609 if let Some(target_id) = state.active_workspace_id {
8610 window_handle
8611 .update(cx, |multi_workspace, window, cx| {
8612 let target_index = multi_workspace
8613 .workspaces()
8614 .iter()
8615 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8616 if let Some(index) = target_index {
8617 multi_workspace.activate_index(index, window, cx);
8618 } else if !multi_workspace.workspaces().is_empty() {
8619 multi_workspace.activate_index(0, window, cx);
8620 }
8621 })
8622 .ok();
8623 } else {
8624 window_handle
8625 .update(cx, |multi_workspace, window, cx| {
8626 if !multi_workspace.workspaces().is_empty() {
8627 multi_workspace.activate_index(0, window, cx);
8628 }
8629 })
8630 .ok();
8631 }
8632
8633 if state.sidebar_open {
8634 window_handle
8635 .update(cx, |multi_workspace, _, cx| {
8636 multi_workspace.open_sidebar(cx);
8637 })
8638 .ok();
8639 }
8640
8641 window_handle
8642 .update(cx, |_, window, _cx| {
8643 window.activate_window();
8644 })
8645 .ok();
8646
8647 Ok(MultiWorkspaceRestoreResult {
8648 window_handle,
8649 errors,
8650 })
8651}
8652
8653actions!(
8654 collab,
8655 [
8656 /// Opens the channel notes for the current call.
8657 ///
8658 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8659 /// channel in the collab panel.
8660 ///
8661 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8662 /// can be copied via "Copy link to section" in the context menu of the channel notes
8663 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8664 OpenChannelNotes,
8665 /// Mutes your microphone.
8666 Mute,
8667 /// Deafens yourself (mute both microphone and speakers).
8668 Deafen,
8669 /// Leaves the current call.
8670 LeaveCall,
8671 /// Shares the current project with collaborators.
8672 ShareProject,
8673 /// Shares your screen with collaborators.
8674 ScreenShare,
8675 /// Copies the current room name and session id for debugging purposes.
8676 CopyRoomId,
8677 ]
8678);
8679
8680/// Opens the channel notes for a specific channel by its ID.
8681#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8682#[action(namespace = collab)]
8683#[serde(deny_unknown_fields)]
8684pub struct OpenChannelNotesById {
8685 pub channel_id: u64,
8686}
8687
8688actions!(
8689 zed,
8690 [
8691 /// Opens the Zed log file.
8692 OpenLog,
8693 /// Reveals the Zed log file in the system file manager.
8694 RevealLogInFileManager
8695 ]
8696);
8697
8698async fn join_channel_internal(
8699 channel_id: ChannelId,
8700 app_state: &Arc<AppState>,
8701 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8702 requesting_workspace: Option<WeakEntity<Workspace>>,
8703 active_call: &dyn AnyActiveCall,
8704 cx: &mut AsyncApp,
8705) -> Result<bool> {
8706 let (should_prompt, already_in_channel) = cx.update(|cx| {
8707 if !active_call.is_in_room(cx) {
8708 return (false, false);
8709 }
8710
8711 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8712 let should_prompt = active_call.is_sharing_project(cx)
8713 && active_call.has_remote_participants(cx)
8714 && !already_in_channel;
8715 (should_prompt, already_in_channel)
8716 });
8717
8718 if already_in_channel {
8719 let task = cx.update(|cx| {
8720 if let Some((project, host)) = active_call.most_active_project(cx) {
8721 Some(join_in_room_project(project, host, app_state.clone(), cx))
8722 } else {
8723 None
8724 }
8725 });
8726 if let Some(task) = task {
8727 task.await?;
8728 }
8729 return anyhow::Ok(true);
8730 }
8731
8732 if should_prompt {
8733 if let Some(multi_workspace) = requesting_window {
8734 let answer = multi_workspace
8735 .update(cx, |_, window, cx| {
8736 window.prompt(
8737 PromptLevel::Warning,
8738 "Do you want to switch channels?",
8739 Some("Leaving this call will unshare your current project."),
8740 &["Yes, Join Channel", "Cancel"],
8741 cx,
8742 )
8743 })?
8744 .await;
8745
8746 if answer == Ok(1) {
8747 return Ok(false);
8748 }
8749 } else {
8750 return Ok(false);
8751 }
8752 }
8753
8754 let client = cx.update(|cx| active_call.client(cx));
8755
8756 let mut client_status = client.status();
8757
8758 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8759 'outer: loop {
8760 let Some(status) = client_status.recv().await else {
8761 anyhow::bail!("error connecting");
8762 };
8763
8764 match status {
8765 Status::Connecting
8766 | Status::Authenticating
8767 | Status::Authenticated
8768 | Status::Reconnecting
8769 | Status::Reauthenticating
8770 | Status::Reauthenticated => continue,
8771 Status::Connected { .. } => break 'outer,
8772 Status::SignedOut | Status::AuthenticationError => {
8773 return Err(ErrorCode::SignedOut.into());
8774 }
8775 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8776 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8777 return Err(ErrorCode::Disconnected.into());
8778 }
8779 }
8780 }
8781
8782 let joined = cx
8783 .update(|cx| active_call.join_channel(channel_id, cx))
8784 .await?;
8785
8786 if !joined {
8787 return anyhow::Ok(true);
8788 }
8789
8790 cx.update(|cx| active_call.room_update_completed(cx)).await;
8791
8792 let task = cx.update(|cx| {
8793 if let Some((project, host)) = active_call.most_active_project(cx) {
8794 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8795 }
8796
8797 // If you are the first to join a channel, see if you should share your project.
8798 if !active_call.has_remote_participants(cx)
8799 && !active_call.local_participant_is_guest(cx)
8800 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8801 {
8802 let project = workspace.update(cx, |workspace, cx| {
8803 let project = workspace.project.read(cx);
8804
8805 if !active_call.share_on_join(cx) {
8806 return None;
8807 }
8808
8809 if (project.is_local() || project.is_via_remote_server())
8810 && project.visible_worktrees(cx).any(|tree| {
8811 tree.read(cx)
8812 .root_entry()
8813 .is_some_and(|entry| entry.is_dir())
8814 })
8815 {
8816 Some(workspace.project.clone())
8817 } else {
8818 None
8819 }
8820 });
8821 if let Some(project) = project {
8822 let share_task = active_call.share_project(project, cx);
8823 return Some(cx.spawn(async move |_cx| -> Result<()> {
8824 share_task.await?;
8825 Ok(())
8826 }));
8827 }
8828 }
8829
8830 None
8831 });
8832 if let Some(task) = task {
8833 task.await?;
8834 return anyhow::Ok(true);
8835 }
8836 anyhow::Ok(false)
8837}
8838
8839pub fn join_channel(
8840 channel_id: ChannelId,
8841 app_state: Arc<AppState>,
8842 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8843 requesting_workspace: Option<WeakEntity<Workspace>>,
8844 cx: &mut App,
8845) -> Task<Result<()>> {
8846 let active_call = GlobalAnyActiveCall::global(cx).clone();
8847 cx.spawn(async move |cx| {
8848 let result = join_channel_internal(
8849 channel_id,
8850 &app_state,
8851 requesting_window,
8852 requesting_workspace,
8853 &*active_call.0,
8854 cx,
8855 )
8856 .await;
8857
8858 // join channel succeeded, and opened a window
8859 if matches!(result, Ok(true)) {
8860 return anyhow::Ok(());
8861 }
8862
8863 // find an existing workspace to focus and show call controls
8864 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8865 if active_window.is_none() {
8866 // no open workspaces, make one to show the error in (blergh)
8867 let OpenResult {
8868 window: window_handle,
8869 ..
8870 } = cx
8871 .update(|cx| {
8872 Workspace::new_local(
8873 vec![],
8874 app_state.clone(),
8875 requesting_window,
8876 None,
8877 None,
8878 true,
8879 cx,
8880 )
8881 })
8882 .await?;
8883
8884 window_handle
8885 .update(cx, |_, window, _cx| {
8886 window.activate_window();
8887 })
8888 .ok();
8889
8890 if result.is_ok() {
8891 cx.update(|cx| {
8892 cx.dispatch_action(&OpenChannelNotes);
8893 });
8894 }
8895
8896 active_window = Some(window_handle);
8897 }
8898
8899 if let Err(err) = result {
8900 log::error!("failed to join channel: {}", err);
8901 if let Some(active_window) = active_window {
8902 active_window
8903 .update(cx, |_, window, cx| {
8904 let detail: SharedString = match err.error_code() {
8905 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8906 ErrorCode::UpgradeRequired => concat!(
8907 "Your are running an unsupported version of Zed. ",
8908 "Please update to continue."
8909 )
8910 .into(),
8911 ErrorCode::NoSuchChannel => concat!(
8912 "No matching channel was found. ",
8913 "Please check the link and try again."
8914 )
8915 .into(),
8916 ErrorCode::Forbidden => concat!(
8917 "This channel is private, and you do not have access. ",
8918 "Please ask someone to add you and try again."
8919 )
8920 .into(),
8921 ErrorCode::Disconnected => {
8922 "Please check your internet connection and try again.".into()
8923 }
8924 _ => format!("{}\n\nPlease try again.", err).into(),
8925 };
8926 window.prompt(
8927 PromptLevel::Critical,
8928 "Failed to join channel",
8929 Some(&detail),
8930 &["Ok"],
8931 cx,
8932 )
8933 })?
8934 .await
8935 .ok();
8936 }
8937 }
8938
8939 // return ok, we showed the error to the user.
8940 anyhow::Ok(())
8941 })
8942}
8943
8944pub async fn get_any_active_multi_workspace(
8945 app_state: Arc<AppState>,
8946 mut cx: AsyncApp,
8947) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8948 // find an existing workspace to focus and show call controls
8949 let active_window = activate_any_workspace_window(&mut cx);
8950 if active_window.is_none() {
8951 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
8952 .await?;
8953 }
8954 activate_any_workspace_window(&mut cx).context("could not open zed")
8955}
8956
8957fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
8958 cx.update(|cx| {
8959 if let Some(workspace_window) = cx
8960 .active_window()
8961 .and_then(|window| window.downcast::<MultiWorkspace>())
8962 {
8963 return Some(workspace_window);
8964 }
8965
8966 for window in cx.windows() {
8967 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
8968 workspace_window
8969 .update(cx, |_, window, _| window.activate_window())
8970 .ok();
8971 return Some(workspace_window);
8972 }
8973 }
8974 None
8975 })
8976}
8977
8978pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
8979 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
8980}
8981
8982pub fn workspace_windows_for_location(
8983 serialized_location: &SerializedWorkspaceLocation,
8984 cx: &App,
8985) -> Vec<WindowHandle<MultiWorkspace>> {
8986 cx.windows()
8987 .into_iter()
8988 .filter_map(|window| window.downcast::<MultiWorkspace>())
8989 .filter(|multi_workspace| {
8990 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
8991 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
8992 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
8993 }
8994 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
8995 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
8996 a.distro_name == b.distro_name
8997 }
8998 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
8999 a.container_id == b.container_id
9000 }
9001 #[cfg(any(test, feature = "test-support"))]
9002 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
9003 a.id == b.id
9004 }
9005 _ => false,
9006 };
9007
9008 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
9009 multi_workspace.workspaces().iter().any(|workspace| {
9010 match workspace.read(cx).workspace_location(cx) {
9011 WorkspaceLocation::Location(location, _) => {
9012 match (&location, serialized_location) {
9013 (
9014 SerializedWorkspaceLocation::Local,
9015 SerializedWorkspaceLocation::Local,
9016 ) => true,
9017 (
9018 SerializedWorkspaceLocation::Remote(a),
9019 SerializedWorkspaceLocation::Remote(b),
9020 ) => same_host(a, b),
9021 _ => false,
9022 }
9023 }
9024 _ => false,
9025 }
9026 })
9027 })
9028 })
9029 .collect()
9030}
9031
9032pub async fn find_existing_workspace(
9033 abs_paths: &[PathBuf],
9034 open_options: &OpenOptions,
9035 location: &SerializedWorkspaceLocation,
9036 cx: &mut AsyncApp,
9037) -> (
9038 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
9039 OpenVisible,
9040) {
9041 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
9042 let mut open_visible = OpenVisible::All;
9043 let mut best_match = None;
9044
9045 if open_options.open_new_workspace != Some(true) {
9046 cx.update(|cx| {
9047 for window in workspace_windows_for_location(location, cx) {
9048 if let Ok(multi_workspace) = window.read(cx) {
9049 for workspace in multi_workspace.workspaces() {
9050 let project = workspace.read(cx).project.read(cx);
9051 let m = project.visibility_for_paths(
9052 abs_paths,
9053 open_options.open_new_workspace == None,
9054 cx,
9055 );
9056 if m > best_match {
9057 existing = Some((window, workspace.clone()));
9058 best_match = m;
9059 } else if best_match.is_none()
9060 && open_options.open_new_workspace == Some(false)
9061 {
9062 existing = Some((window, workspace.clone()))
9063 }
9064 }
9065 }
9066 }
9067 });
9068
9069 let all_paths_are_files = existing
9070 .as_ref()
9071 .and_then(|(_, target_workspace)| {
9072 cx.update(|cx| {
9073 let workspace = target_workspace.read(cx);
9074 let project = workspace.project.read(cx);
9075 let path_style = workspace.path_style(cx);
9076 Some(!abs_paths.iter().any(|path| {
9077 let path = util::paths::SanitizedPath::new(path);
9078 project.worktrees(cx).any(|worktree| {
9079 let worktree = worktree.read(cx);
9080 let abs_path = worktree.abs_path();
9081 path_style
9082 .strip_prefix(path.as_ref(), abs_path.as_ref())
9083 .and_then(|rel| worktree.entry_for_path(&rel))
9084 .is_some_and(|e| e.is_dir())
9085 })
9086 }))
9087 })
9088 })
9089 .unwrap_or(false);
9090
9091 if open_options.open_new_workspace.is_none()
9092 && existing.is_some()
9093 && open_options.wait
9094 && all_paths_are_files
9095 {
9096 cx.update(|cx| {
9097 let windows = workspace_windows_for_location(location, cx);
9098 let window = cx
9099 .active_window()
9100 .and_then(|window| window.downcast::<MultiWorkspace>())
9101 .filter(|window| windows.contains(window))
9102 .or_else(|| windows.into_iter().next());
9103 if let Some(window) = window {
9104 if let Ok(multi_workspace) = window.read(cx) {
9105 let active_workspace = multi_workspace.workspace().clone();
9106 existing = Some((window, active_workspace));
9107 open_visible = OpenVisible::None;
9108 }
9109 }
9110 });
9111 }
9112 }
9113 (existing, open_visible)
9114}
9115
9116#[derive(Default, Clone)]
9117pub struct OpenOptions {
9118 pub visible: Option<OpenVisible>,
9119 pub focus: Option<bool>,
9120 pub open_new_workspace: Option<bool>,
9121 pub wait: bool,
9122 pub replace_window: Option<WindowHandle<MultiWorkspace>>,
9123 pub env: Option<HashMap<String, String>>,
9124}
9125
9126/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
9127/// or [`Workspace::open_workspace_for_paths`].
9128pub struct OpenResult {
9129 pub window: WindowHandle<MultiWorkspace>,
9130 pub workspace: Entity<Workspace>,
9131 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
9132}
9133
9134/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
9135pub fn open_workspace_by_id(
9136 workspace_id: WorkspaceId,
9137 app_state: Arc<AppState>,
9138 requesting_window: Option<WindowHandle<MultiWorkspace>>,
9139 cx: &mut App,
9140) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
9141 let project_handle = Project::local(
9142 app_state.client.clone(),
9143 app_state.node_runtime.clone(),
9144 app_state.user_store.clone(),
9145 app_state.languages.clone(),
9146 app_state.fs.clone(),
9147 None,
9148 project::LocalProjectFlags {
9149 init_worktree_trust: true,
9150 ..project::LocalProjectFlags::default()
9151 },
9152 cx,
9153 );
9154
9155 let db = WorkspaceDb::global(cx);
9156 let kvp = db::kvp::KeyValueStore::global(cx);
9157 cx.spawn(async move |cx| {
9158 let serialized_workspace = db
9159 .workspace_for_id(workspace_id)
9160 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
9161
9162 let centered_layout = serialized_workspace.centered_layout;
9163
9164 let (window, workspace) = if let Some(window) = requesting_window {
9165 let workspace = window.update(cx, |multi_workspace, window, cx| {
9166 let workspace = cx.new(|cx| {
9167 let mut workspace = Workspace::new(
9168 Some(workspace_id),
9169 project_handle.clone(),
9170 app_state.clone(),
9171 window,
9172 cx,
9173 );
9174 workspace.centered_layout = centered_layout;
9175 workspace
9176 });
9177 multi_workspace.add_workspace(workspace.clone(), cx);
9178 workspace
9179 })?;
9180 (window, workspace)
9181 } else {
9182 let window_bounds_override = window_bounds_env_override();
9183
9184 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
9185 (Some(WindowBounds::Windowed(bounds)), None)
9186 } else if let Some(display) = serialized_workspace.display
9187 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
9188 {
9189 (Some(bounds.0), Some(display))
9190 } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
9191 (Some(bounds), Some(display))
9192 } else {
9193 (None, None)
9194 };
9195
9196 let options = cx.update(|cx| {
9197 let mut options = (app_state.build_window_options)(display, cx);
9198 options.window_bounds = window_bounds;
9199 options
9200 });
9201
9202 let window = cx.open_window(options, {
9203 let app_state = app_state.clone();
9204 let project_handle = project_handle.clone();
9205 move |window, cx| {
9206 let workspace = cx.new(|cx| {
9207 let mut workspace = Workspace::new(
9208 Some(workspace_id),
9209 project_handle,
9210 app_state,
9211 window,
9212 cx,
9213 );
9214 workspace.centered_layout = centered_layout;
9215 workspace
9216 });
9217 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9218 }
9219 })?;
9220
9221 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
9222 multi_workspace.workspace().clone()
9223 })?;
9224
9225 (window, workspace)
9226 };
9227
9228 notify_if_database_failed(window, cx);
9229
9230 // Restore items from the serialized workspace
9231 window
9232 .update(cx, |_, window, cx| {
9233 workspace.update(cx, |_workspace, cx| {
9234 open_items(Some(serialized_workspace), vec![], window, cx)
9235 })
9236 })?
9237 .await?;
9238
9239 window.update(cx, |_, window, cx| {
9240 workspace.update(cx, |workspace, cx| {
9241 workspace.serialize_workspace(window, cx);
9242 });
9243 })?;
9244
9245 Ok(window)
9246 })
9247}
9248
9249#[allow(clippy::type_complexity)]
9250pub fn open_paths(
9251 abs_paths: &[PathBuf],
9252 app_state: Arc<AppState>,
9253 open_options: OpenOptions,
9254 cx: &mut App,
9255) -> Task<anyhow::Result<OpenResult>> {
9256 let abs_paths = abs_paths.to_vec();
9257 #[cfg(target_os = "windows")]
9258 let wsl_path = abs_paths
9259 .iter()
9260 .find_map(|p| util::paths::WslPath::from_path(p));
9261
9262 cx.spawn(async move |cx| {
9263 let (mut existing, mut open_visible) = find_existing_workspace(
9264 &abs_paths,
9265 &open_options,
9266 &SerializedWorkspaceLocation::Local,
9267 cx,
9268 )
9269 .await;
9270
9271 // Fallback: if no workspace contains the paths and all paths are files,
9272 // prefer an existing local workspace window (active window first).
9273 if open_options.open_new_workspace.is_none() && existing.is_none() {
9274 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9275 let all_metadatas = futures::future::join_all(all_paths)
9276 .await
9277 .into_iter()
9278 .filter_map(|result| result.ok().flatten())
9279 .collect::<Vec<_>>();
9280
9281 if all_metadatas.iter().all(|file| !file.is_dir) {
9282 cx.update(|cx| {
9283 let windows = workspace_windows_for_location(
9284 &SerializedWorkspaceLocation::Local,
9285 cx,
9286 );
9287 let window = cx
9288 .active_window()
9289 .and_then(|window| window.downcast::<MultiWorkspace>())
9290 .filter(|window| windows.contains(window))
9291 .or_else(|| windows.into_iter().next());
9292 if let Some(window) = window {
9293 if let Ok(multi_workspace) = window.read(cx) {
9294 let active_workspace = multi_workspace.workspace().clone();
9295 existing = Some((window, active_workspace));
9296 open_visible = OpenVisible::None;
9297 }
9298 }
9299 });
9300 }
9301 }
9302
9303 let result = if let Some((existing, target_workspace)) = existing {
9304 let open_task = existing
9305 .update(cx, |multi_workspace, window, cx| {
9306 window.activate_window();
9307 multi_workspace.activate(target_workspace.clone(), cx);
9308 target_workspace.update(cx, |workspace, cx| {
9309 workspace.open_paths(
9310 abs_paths,
9311 OpenOptions {
9312 visible: Some(open_visible),
9313 ..Default::default()
9314 },
9315 None,
9316 window,
9317 cx,
9318 )
9319 })
9320 })?
9321 .await;
9322
9323 _ = existing.update(cx, |multi_workspace, _, cx| {
9324 let workspace = multi_workspace.workspace().clone();
9325 workspace.update(cx, |workspace, cx| {
9326 for item in open_task.iter().flatten() {
9327 if let Err(e) = item {
9328 workspace.show_error(&e, cx);
9329 }
9330 }
9331 });
9332 });
9333
9334 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9335 } else {
9336 let result = cx
9337 .update(move |cx| {
9338 Workspace::new_local(
9339 abs_paths,
9340 app_state.clone(),
9341 open_options.replace_window,
9342 open_options.env,
9343 None,
9344 true,
9345 cx,
9346 )
9347 })
9348 .await;
9349
9350 if let Ok(ref result) = result {
9351 result.window
9352 .update(cx, |_, window, _cx| {
9353 window.activate_window();
9354 })
9355 .log_err();
9356 }
9357
9358 result
9359 };
9360
9361 #[cfg(target_os = "windows")]
9362 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9363 && let Ok(ref result) = result
9364 {
9365 result.window
9366 .update(cx, move |multi_workspace, _window, cx| {
9367 struct OpenInWsl;
9368 let workspace = multi_workspace.workspace().clone();
9369 workspace.update(cx, |workspace, cx| {
9370 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9371 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9372 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9373 cx.new(move |cx| {
9374 MessageNotification::new(msg, cx)
9375 .primary_message("Open in WSL")
9376 .primary_icon(IconName::FolderOpen)
9377 .primary_on_click(move |window, cx| {
9378 window.dispatch_action(Box::new(remote::OpenWslPath {
9379 distro: remote::WslConnectionOptions {
9380 distro_name: distro.clone(),
9381 user: None,
9382 },
9383 paths: vec![path.clone().into()],
9384 }), cx)
9385 })
9386 })
9387 });
9388 });
9389 })
9390 .unwrap();
9391 };
9392 result
9393 })
9394}
9395
9396pub fn open_new(
9397 open_options: OpenOptions,
9398 app_state: Arc<AppState>,
9399 cx: &mut App,
9400 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9401) -> Task<anyhow::Result<()>> {
9402 let task = Workspace::new_local(
9403 Vec::new(),
9404 app_state,
9405 open_options.replace_window,
9406 open_options.env,
9407 Some(Box::new(init)),
9408 true,
9409 cx,
9410 );
9411 cx.spawn(async move |cx| {
9412 let OpenResult { window, .. } = task.await?;
9413 window
9414 .update(cx, |_, window, _cx| {
9415 window.activate_window();
9416 })
9417 .ok();
9418 Ok(())
9419 })
9420}
9421
9422pub fn create_and_open_local_file(
9423 path: &'static Path,
9424 window: &mut Window,
9425 cx: &mut Context<Workspace>,
9426 default_content: impl 'static + Send + FnOnce() -> Rope,
9427) -> Task<Result<Box<dyn ItemHandle>>> {
9428 cx.spawn_in(window, async move |workspace, cx| {
9429 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9430 if !fs.is_file(path).await {
9431 fs.create_file(path, Default::default()).await?;
9432 fs.save(path, &default_content(), Default::default())
9433 .await?;
9434 }
9435
9436 workspace
9437 .update_in(cx, |workspace, window, cx| {
9438 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9439 let path = workspace
9440 .project
9441 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9442 cx.spawn_in(window, async move |workspace, cx| {
9443 let path = path.await?;
9444
9445 let path = fs.canonicalize(&path).await.unwrap_or(path);
9446
9447 let mut items = workspace
9448 .update_in(cx, |workspace, window, cx| {
9449 workspace.open_paths(
9450 vec![path.to_path_buf()],
9451 OpenOptions {
9452 visible: Some(OpenVisible::None),
9453 ..Default::default()
9454 },
9455 None,
9456 window,
9457 cx,
9458 )
9459 })?
9460 .await;
9461 let item = items.pop().flatten();
9462 item.with_context(|| format!("path {path:?} is not a file"))?
9463 })
9464 })
9465 })?
9466 .await?
9467 .await
9468 })
9469}
9470
9471pub fn open_remote_project_with_new_connection(
9472 window: WindowHandle<MultiWorkspace>,
9473 remote_connection: Arc<dyn RemoteConnection>,
9474 cancel_rx: oneshot::Receiver<()>,
9475 delegate: Arc<dyn RemoteClientDelegate>,
9476 app_state: Arc<AppState>,
9477 paths: Vec<PathBuf>,
9478 cx: &mut App,
9479) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9480 cx.spawn(async move |cx| {
9481 let (workspace_id, serialized_workspace) =
9482 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9483 .await?;
9484
9485 let session = match cx
9486 .update(|cx| {
9487 remote::RemoteClient::new(
9488 ConnectionIdentifier::Workspace(workspace_id.0),
9489 remote_connection,
9490 cancel_rx,
9491 delegate,
9492 cx,
9493 )
9494 })
9495 .await?
9496 {
9497 Some(result) => result,
9498 None => return Ok(Vec::new()),
9499 };
9500
9501 let project = cx.update(|cx| {
9502 project::Project::remote(
9503 session,
9504 app_state.client.clone(),
9505 app_state.node_runtime.clone(),
9506 app_state.user_store.clone(),
9507 app_state.languages.clone(),
9508 app_state.fs.clone(),
9509 true,
9510 cx,
9511 )
9512 });
9513
9514 open_remote_project_inner(
9515 project,
9516 paths,
9517 workspace_id,
9518 serialized_workspace,
9519 app_state,
9520 window,
9521 cx,
9522 )
9523 .await
9524 })
9525}
9526
9527pub fn open_remote_project_with_existing_connection(
9528 connection_options: RemoteConnectionOptions,
9529 project: Entity<Project>,
9530 paths: Vec<PathBuf>,
9531 app_state: Arc<AppState>,
9532 window: WindowHandle<MultiWorkspace>,
9533 cx: &mut AsyncApp,
9534) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9535 cx.spawn(async move |cx| {
9536 let (workspace_id, serialized_workspace) =
9537 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9538
9539 open_remote_project_inner(
9540 project,
9541 paths,
9542 workspace_id,
9543 serialized_workspace,
9544 app_state,
9545 window,
9546 cx,
9547 )
9548 .await
9549 })
9550}
9551
9552async fn open_remote_project_inner(
9553 project: Entity<Project>,
9554 paths: Vec<PathBuf>,
9555 workspace_id: WorkspaceId,
9556 serialized_workspace: Option<SerializedWorkspace>,
9557 app_state: Arc<AppState>,
9558 window: WindowHandle<MultiWorkspace>,
9559 cx: &mut AsyncApp,
9560) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9561 let db = cx.update(|cx| WorkspaceDb::global(cx));
9562 let toolchains = db.toolchains(workspace_id).await?;
9563 for (toolchain, worktree_path, path) in toolchains {
9564 project
9565 .update(cx, |this, cx| {
9566 let Some(worktree_id) =
9567 this.find_worktree(&worktree_path, cx)
9568 .and_then(|(worktree, rel_path)| {
9569 if rel_path.is_empty() {
9570 Some(worktree.read(cx).id())
9571 } else {
9572 None
9573 }
9574 })
9575 else {
9576 return Task::ready(None);
9577 };
9578
9579 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9580 })
9581 .await;
9582 }
9583 let mut project_paths_to_open = vec![];
9584 let mut project_path_errors = vec![];
9585
9586 for path in paths {
9587 let result = cx
9588 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9589 .await;
9590 match result {
9591 Ok((_, project_path)) => {
9592 project_paths_to_open.push((path.clone(), Some(project_path)));
9593 }
9594 Err(error) => {
9595 project_path_errors.push(error);
9596 }
9597 };
9598 }
9599
9600 if project_paths_to_open.is_empty() {
9601 return Err(project_path_errors.pop().context("no paths given")?);
9602 }
9603
9604 let workspace = window.update(cx, |multi_workspace, window, cx| {
9605 telemetry::event!("SSH Project Opened");
9606
9607 let new_workspace = cx.new(|cx| {
9608 let mut workspace =
9609 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9610 workspace.update_history(cx);
9611
9612 if let Some(ref serialized) = serialized_workspace {
9613 workspace.centered_layout = serialized.centered_layout;
9614 }
9615
9616 workspace
9617 });
9618
9619 multi_workspace.activate(new_workspace.clone(), cx);
9620 new_workspace
9621 })?;
9622
9623 let items = window
9624 .update(cx, |_, window, cx| {
9625 window.activate_window();
9626 workspace.update(cx, |_workspace, cx| {
9627 open_items(serialized_workspace, project_paths_to_open, window, cx)
9628 })
9629 })?
9630 .await?;
9631
9632 workspace.update(cx, |workspace, cx| {
9633 for error in project_path_errors {
9634 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9635 if let Some(path) = error.error_tag("path") {
9636 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9637 }
9638 } else {
9639 workspace.show_error(&error, cx)
9640 }
9641 }
9642 });
9643
9644 Ok(items.into_iter().map(|item| item?.ok()).collect())
9645}
9646
9647fn deserialize_remote_project(
9648 connection_options: RemoteConnectionOptions,
9649 paths: Vec<PathBuf>,
9650 cx: &AsyncApp,
9651) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9652 let db = cx.update(|cx| WorkspaceDb::global(cx));
9653 cx.background_spawn(async move {
9654 let remote_connection_id = db
9655 .get_or_create_remote_connection(connection_options)
9656 .await?;
9657
9658 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9659
9660 let workspace_id = if let Some(workspace_id) =
9661 serialized_workspace.as_ref().map(|workspace| workspace.id)
9662 {
9663 workspace_id
9664 } else {
9665 db.next_id().await?
9666 };
9667
9668 Ok((workspace_id, serialized_workspace))
9669 })
9670}
9671
9672pub fn join_in_room_project(
9673 project_id: u64,
9674 follow_user_id: u64,
9675 app_state: Arc<AppState>,
9676 cx: &mut App,
9677) -> Task<Result<()>> {
9678 let windows = cx.windows();
9679 cx.spawn(async move |cx| {
9680 let existing_window_and_workspace: Option<(
9681 WindowHandle<MultiWorkspace>,
9682 Entity<Workspace>,
9683 )> = windows.into_iter().find_map(|window_handle| {
9684 window_handle
9685 .downcast::<MultiWorkspace>()
9686 .and_then(|window_handle| {
9687 window_handle
9688 .update(cx, |multi_workspace, _window, cx| {
9689 for workspace in multi_workspace.workspaces() {
9690 if workspace.read(cx).project().read(cx).remote_id()
9691 == Some(project_id)
9692 {
9693 return Some((window_handle, workspace.clone()));
9694 }
9695 }
9696 None
9697 })
9698 .unwrap_or(None)
9699 })
9700 });
9701
9702 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9703 existing_window_and_workspace
9704 {
9705 existing_window
9706 .update(cx, |multi_workspace, _, cx| {
9707 multi_workspace.activate(target_workspace, cx);
9708 })
9709 .ok();
9710 existing_window
9711 } else {
9712 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9713 let project = cx
9714 .update(|cx| {
9715 active_call.0.join_project(
9716 project_id,
9717 app_state.languages.clone(),
9718 app_state.fs.clone(),
9719 cx,
9720 )
9721 })
9722 .await?;
9723
9724 let window_bounds_override = window_bounds_env_override();
9725 cx.update(|cx| {
9726 let mut options = (app_state.build_window_options)(None, cx);
9727 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9728 cx.open_window(options, |window, cx| {
9729 let workspace = cx.new(|cx| {
9730 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9731 });
9732 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9733 })
9734 })?
9735 };
9736
9737 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9738 cx.activate(true);
9739 window.activate_window();
9740
9741 // We set the active workspace above, so this is the correct workspace.
9742 let workspace = multi_workspace.workspace().clone();
9743 workspace.update(cx, |workspace, cx| {
9744 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9745 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9746 .or_else(|| {
9747 // If we couldn't follow the given user, follow the host instead.
9748 let collaborator = workspace
9749 .project()
9750 .read(cx)
9751 .collaborators()
9752 .values()
9753 .find(|collaborator| collaborator.is_host)?;
9754 Some(collaborator.peer_id)
9755 });
9756
9757 if let Some(follow_peer_id) = follow_peer_id {
9758 workspace.follow(follow_peer_id, window, cx);
9759 }
9760 });
9761 })?;
9762
9763 anyhow::Ok(())
9764 })
9765}
9766
9767pub fn reload(cx: &mut App) {
9768 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9769 let mut workspace_windows = cx
9770 .windows()
9771 .into_iter()
9772 .filter_map(|window| window.downcast::<MultiWorkspace>())
9773 .collect::<Vec<_>>();
9774
9775 // If multiple windows have unsaved changes, and need a save prompt,
9776 // prompt in the active window before switching to a different window.
9777 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9778
9779 let mut prompt = None;
9780 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9781 prompt = window
9782 .update(cx, |_, window, cx| {
9783 window.prompt(
9784 PromptLevel::Info,
9785 "Are you sure you want to restart?",
9786 None,
9787 &["Restart", "Cancel"],
9788 cx,
9789 )
9790 })
9791 .ok();
9792 }
9793
9794 cx.spawn(async move |cx| {
9795 if let Some(prompt) = prompt {
9796 let answer = prompt.await?;
9797 if answer != 0 {
9798 return anyhow::Ok(());
9799 }
9800 }
9801
9802 // If the user cancels any save prompt, then keep the app open.
9803 for window in workspace_windows {
9804 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9805 let workspace = multi_workspace.workspace().clone();
9806 workspace.update(cx, |workspace, cx| {
9807 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9808 })
9809 }) && !should_close.await?
9810 {
9811 return anyhow::Ok(());
9812 }
9813 }
9814 cx.update(|cx| cx.restart());
9815 anyhow::Ok(())
9816 })
9817 .detach_and_log_err(cx);
9818}
9819
9820fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9821 let mut parts = value.split(',');
9822 let x: usize = parts.next()?.parse().ok()?;
9823 let y: usize = parts.next()?.parse().ok()?;
9824 Some(point(px(x as f32), px(y as f32)))
9825}
9826
9827fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9828 let mut parts = value.split(',');
9829 let width: usize = parts.next()?.parse().ok()?;
9830 let height: usize = parts.next()?.parse().ok()?;
9831 Some(size(px(width as f32), px(height as f32)))
9832}
9833
9834/// Add client-side decorations (rounded corners, shadows, resize handling) when
9835/// appropriate.
9836///
9837/// The `border_radius_tiling` parameter allows overriding which corners get
9838/// rounded, independently of the actual window tiling state. This is used
9839/// specifically for the workspace switcher sidebar: when the sidebar is open,
9840/// we want square corners on the left (so the sidebar appears flush with the
9841/// window edge) but we still need the shadow padding for proper visual
9842/// appearance. Unlike actual window tiling, this only affects border radius -
9843/// not padding or shadows.
9844pub fn client_side_decorations(
9845 element: impl IntoElement,
9846 window: &mut Window,
9847 cx: &mut App,
9848 border_radius_tiling: Tiling,
9849) -> Stateful<Div> {
9850 const BORDER_SIZE: Pixels = px(1.0);
9851 let decorations = window.window_decorations();
9852 let tiling = match decorations {
9853 Decorations::Server => Tiling::default(),
9854 Decorations::Client { tiling } => tiling,
9855 };
9856
9857 match decorations {
9858 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9859 Decorations::Server => window.set_client_inset(px(0.0)),
9860 }
9861
9862 struct GlobalResizeEdge(ResizeEdge);
9863 impl Global for GlobalResizeEdge {}
9864
9865 div()
9866 .id("window-backdrop")
9867 .bg(transparent_black())
9868 .map(|div| match decorations {
9869 Decorations::Server => div,
9870 Decorations::Client { .. } => div
9871 .when(
9872 !(tiling.top
9873 || tiling.right
9874 || border_radius_tiling.top
9875 || border_radius_tiling.right),
9876 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9877 )
9878 .when(
9879 !(tiling.top
9880 || tiling.left
9881 || border_radius_tiling.top
9882 || border_radius_tiling.left),
9883 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9884 )
9885 .when(
9886 !(tiling.bottom
9887 || tiling.right
9888 || border_radius_tiling.bottom
9889 || border_radius_tiling.right),
9890 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9891 )
9892 .when(
9893 !(tiling.bottom
9894 || tiling.left
9895 || border_radius_tiling.bottom
9896 || border_radius_tiling.left),
9897 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9898 )
9899 .when(!tiling.top, |div| {
9900 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9901 })
9902 .when(!tiling.bottom, |div| {
9903 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9904 })
9905 .when(!tiling.left, |div| {
9906 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9907 })
9908 .when(!tiling.right, |div| {
9909 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9910 })
9911 .on_mouse_move(move |e, window, cx| {
9912 let size = window.window_bounds().get_bounds().size;
9913 let pos = e.position;
9914
9915 let new_edge =
9916 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9917
9918 let edge = cx.try_global::<GlobalResizeEdge>();
9919 if new_edge != edge.map(|edge| edge.0) {
9920 window
9921 .window_handle()
9922 .update(cx, |workspace, _, cx| {
9923 cx.notify(workspace.entity_id());
9924 })
9925 .ok();
9926 }
9927 })
9928 .on_mouse_down(MouseButton::Left, move |e, window, _| {
9929 let size = window.window_bounds().get_bounds().size;
9930 let pos = e.position;
9931
9932 let edge = match resize_edge(
9933 pos,
9934 theme::CLIENT_SIDE_DECORATION_SHADOW,
9935 size,
9936 tiling,
9937 ) {
9938 Some(value) => value,
9939 None => return,
9940 };
9941
9942 window.start_window_resize(edge);
9943 }),
9944 })
9945 .size_full()
9946 .child(
9947 div()
9948 .cursor(CursorStyle::Arrow)
9949 .map(|div| match decorations {
9950 Decorations::Server => div,
9951 Decorations::Client { .. } => div
9952 .border_color(cx.theme().colors().border)
9953 .when(
9954 !(tiling.top
9955 || tiling.right
9956 || border_radius_tiling.top
9957 || border_radius_tiling.right),
9958 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9959 )
9960 .when(
9961 !(tiling.top
9962 || tiling.left
9963 || border_radius_tiling.top
9964 || border_radius_tiling.left),
9965 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9966 )
9967 .when(
9968 !(tiling.bottom
9969 || tiling.right
9970 || border_radius_tiling.bottom
9971 || border_radius_tiling.right),
9972 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9973 )
9974 .when(
9975 !(tiling.bottom
9976 || tiling.left
9977 || border_radius_tiling.bottom
9978 || border_radius_tiling.left),
9979 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9980 )
9981 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
9982 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
9983 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
9984 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
9985 .when(!tiling.is_tiled(), |div| {
9986 div.shadow(vec![gpui::BoxShadow {
9987 color: Hsla {
9988 h: 0.,
9989 s: 0.,
9990 l: 0.,
9991 a: 0.4,
9992 },
9993 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
9994 spread_radius: px(0.),
9995 offset: point(px(0.0), px(0.0)),
9996 }])
9997 }),
9998 })
9999 .on_mouse_move(|_e, _, cx| {
10000 cx.stop_propagation();
10001 })
10002 .size_full()
10003 .child(element),
10004 )
10005 .map(|div| match decorations {
10006 Decorations::Server => div,
10007 Decorations::Client { tiling, .. } => div.child(
10008 canvas(
10009 |_bounds, window, _| {
10010 window.insert_hitbox(
10011 Bounds::new(
10012 point(px(0.0), px(0.0)),
10013 window.window_bounds().get_bounds().size,
10014 ),
10015 HitboxBehavior::Normal,
10016 )
10017 },
10018 move |_bounds, hitbox, window, cx| {
10019 let mouse = window.mouse_position();
10020 let size = window.window_bounds().get_bounds().size;
10021 let Some(edge) =
10022 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10023 else {
10024 return;
10025 };
10026 cx.set_global(GlobalResizeEdge(edge));
10027 window.set_cursor_style(
10028 match edge {
10029 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10030 ResizeEdge::Left | ResizeEdge::Right => {
10031 CursorStyle::ResizeLeftRight
10032 }
10033 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10034 CursorStyle::ResizeUpLeftDownRight
10035 }
10036 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10037 CursorStyle::ResizeUpRightDownLeft
10038 }
10039 },
10040 &hitbox,
10041 );
10042 },
10043 )
10044 .size_full()
10045 .absolute(),
10046 ),
10047 })
10048}
10049
10050fn resize_edge(
10051 pos: Point<Pixels>,
10052 shadow_size: Pixels,
10053 window_size: Size<Pixels>,
10054 tiling: Tiling,
10055) -> Option<ResizeEdge> {
10056 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10057 if bounds.contains(&pos) {
10058 return None;
10059 }
10060
10061 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10062 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10063 if !tiling.top && top_left_bounds.contains(&pos) {
10064 return Some(ResizeEdge::TopLeft);
10065 }
10066
10067 let top_right_bounds = Bounds::new(
10068 Point::new(window_size.width - corner_size.width, px(0.)),
10069 corner_size,
10070 );
10071 if !tiling.top && top_right_bounds.contains(&pos) {
10072 return Some(ResizeEdge::TopRight);
10073 }
10074
10075 let bottom_left_bounds = Bounds::new(
10076 Point::new(px(0.), window_size.height - corner_size.height),
10077 corner_size,
10078 );
10079 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10080 return Some(ResizeEdge::BottomLeft);
10081 }
10082
10083 let bottom_right_bounds = Bounds::new(
10084 Point::new(
10085 window_size.width - corner_size.width,
10086 window_size.height - corner_size.height,
10087 ),
10088 corner_size,
10089 );
10090 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10091 return Some(ResizeEdge::BottomRight);
10092 }
10093
10094 if !tiling.top && pos.y < shadow_size {
10095 Some(ResizeEdge::Top)
10096 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10097 Some(ResizeEdge::Bottom)
10098 } else if !tiling.left && pos.x < shadow_size {
10099 Some(ResizeEdge::Left)
10100 } else if !tiling.right && pos.x > window_size.width - shadow_size {
10101 Some(ResizeEdge::Right)
10102 } else {
10103 None
10104 }
10105}
10106
10107fn join_pane_into_active(
10108 active_pane: &Entity<Pane>,
10109 pane: &Entity<Pane>,
10110 window: &mut Window,
10111 cx: &mut App,
10112) {
10113 if pane == active_pane {
10114 } else if pane.read(cx).items_len() == 0 {
10115 pane.update(cx, |_, cx| {
10116 cx.emit(pane::Event::Remove {
10117 focus_on_pane: None,
10118 });
10119 })
10120 } else {
10121 move_all_items(pane, active_pane, window, cx);
10122 }
10123}
10124
10125fn move_all_items(
10126 from_pane: &Entity<Pane>,
10127 to_pane: &Entity<Pane>,
10128 window: &mut Window,
10129 cx: &mut App,
10130) {
10131 let destination_is_different = from_pane != to_pane;
10132 let mut moved_items = 0;
10133 for (item_ix, item_handle) in from_pane
10134 .read(cx)
10135 .items()
10136 .enumerate()
10137 .map(|(ix, item)| (ix, item.clone()))
10138 .collect::<Vec<_>>()
10139 {
10140 let ix = item_ix - moved_items;
10141 if destination_is_different {
10142 // Close item from previous pane
10143 from_pane.update(cx, |source, cx| {
10144 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10145 });
10146 moved_items += 1;
10147 }
10148
10149 // This automatically removes duplicate items in the pane
10150 to_pane.update(cx, |destination, cx| {
10151 destination.add_item(item_handle, true, true, None, window, cx);
10152 window.focus(&destination.focus_handle(cx), cx)
10153 });
10154 }
10155}
10156
10157pub fn move_item(
10158 source: &Entity<Pane>,
10159 destination: &Entity<Pane>,
10160 item_id_to_move: EntityId,
10161 destination_index: usize,
10162 activate: bool,
10163 window: &mut Window,
10164 cx: &mut App,
10165) {
10166 let Some((item_ix, item_handle)) = source
10167 .read(cx)
10168 .items()
10169 .enumerate()
10170 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10171 .map(|(ix, item)| (ix, item.clone()))
10172 else {
10173 // Tab was closed during drag
10174 return;
10175 };
10176
10177 if source != destination {
10178 // Close item from previous pane
10179 source.update(cx, |source, cx| {
10180 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10181 });
10182 }
10183
10184 // This automatically removes duplicate items in the pane
10185 destination.update(cx, |destination, cx| {
10186 destination.add_item_inner(
10187 item_handle,
10188 activate,
10189 activate,
10190 activate,
10191 Some(destination_index),
10192 window,
10193 cx,
10194 );
10195 if activate {
10196 window.focus(&destination.focus_handle(cx), cx)
10197 }
10198 });
10199}
10200
10201pub fn move_active_item(
10202 source: &Entity<Pane>,
10203 destination: &Entity<Pane>,
10204 focus_destination: bool,
10205 close_if_empty: bool,
10206 window: &mut Window,
10207 cx: &mut App,
10208) {
10209 if source == destination {
10210 return;
10211 }
10212 let Some(active_item) = source.read(cx).active_item() else {
10213 return;
10214 };
10215 source.update(cx, |source_pane, cx| {
10216 let item_id = active_item.item_id();
10217 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10218 destination.update(cx, |target_pane, cx| {
10219 target_pane.add_item(
10220 active_item,
10221 focus_destination,
10222 focus_destination,
10223 Some(target_pane.items_len()),
10224 window,
10225 cx,
10226 );
10227 });
10228 });
10229}
10230
10231pub fn clone_active_item(
10232 workspace_id: Option<WorkspaceId>,
10233 source: &Entity<Pane>,
10234 destination: &Entity<Pane>,
10235 focus_destination: bool,
10236 window: &mut Window,
10237 cx: &mut App,
10238) {
10239 if source == destination {
10240 return;
10241 }
10242 let Some(active_item) = source.read(cx).active_item() else {
10243 return;
10244 };
10245 if !active_item.can_split(cx) {
10246 return;
10247 }
10248 let destination = destination.downgrade();
10249 let task = active_item.clone_on_split(workspace_id, window, cx);
10250 window
10251 .spawn(cx, async move |cx| {
10252 let Some(clone) = task.await else {
10253 return;
10254 };
10255 destination
10256 .update_in(cx, |target_pane, window, cx| {
10257 target_pane.add_item(
10258 clone,
10259 focus_destination,
10260 focus_destination,
10261 Some(target_pane.items_len()),
10262 window,
10263 cx,
10264 );
10265 })
10266 .log_err();
10267 })
10268 .detach();
10269}
10270
10271#[derive(Debug)]
10272pub struct WorkspacePosition {
10273 pub window_bounds: Option<WindowBounds>,
10274 pub display: Option<Uuid>,
10275 pub centered_layout: bool,
10276}
10277
10278pub fn remote_workspace_position_from_db(
10279 connection_options: RemoteConnectionOptions,
10280 paths_to_open: &[PathBuf],
10281 cx: &App,
10282) -> Task<Result<WorkspacePosition>> {
10283 let paths = paths_to_open.to_vec();
10284 let db = WorkspaceDb::global(cx);
10285 let kvp = db::kvp::KeyValueStore::global(cx);
10286
10287 cx.background_spawn(async move {
10288 let remote_connection_id = db
10289 .get_or_create_remote_connection(connection_options)
10290 .await
10291 .context("fetching serialized ssh project")?;
10292 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10293
10294 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10295 (Some(WindowBounds::Windowed(bounds)), None)
10296 } else {
10297 let restorable_bounds = serialized_workspace
10298 .as_ref()
10299 .and_then(|workspace| {
10300 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10301 })
10302 .or_else(|| persistence::read_default_window_bounds(&kvp));
10303
10304 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10305 (Some(serialized_bounds), Some(serialized_display))
10306 } else {
10307 (None, None)
10308 }
10309 };
10310
10311 let centered_layout = serialized_workspace
10312 .as_ref()
10313 .map(|w| w.centered_layout)
10314 .unwrap_or(false);
10315
10316 Ok(WorkspacePosition {
10317 window_bounds,
10318 display,
10319 centered_layout,
10320 })
10321 })
10322}
10323
10324pub fn with_active_or_new_workspace(
10325 cx: &mut App,
10326 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10327) {
10328 match cx
10329 .active_window()
10330 .and_then(|w| w.downcast::<MultiWorkspace>())
10331 {
10332 Some(multi_workspace) => {
10333 cx.defer(move |cx| {
10334 multi_workspace
10335 .update(cx, |multi_workspace, window, cx| {
10336 let workspace = multi_workspace.workspace().clone();
10337 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10338 })
10339 .log_err();
10340 });
10341 }
10342 None => {
10343 let app_state = AppState::global(cx);
10344 if let Some(app_state) = app_state.upgrade() {
10345 open_new(
10346 OpenOptions::default(),
10347 app_state,
10348 cx,
10349 move |workspace, window, cx| f(workspace, window, cx),
10350 )
10351 .detach_and_log_err(cx);
10352 }
10353 }
10354 }
10355}
10356
10357/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10358/// key. This migration path only runs once per panel per workspace.
10359fn load_legacy_panel_size(
10360 panel_key: &str,
10361 dock_position: DockPosition,
10362 workspace: &Workspace,
10363 cx: &mut App,
10364) -> Option<Pixels> {
10365 #[derive(Deserialize)]
10366 struct LegacyPanelState {
10367 #[serde(default)]
10368 width: Option<Pixels>,
10369 #[serde(default)]
10370 height: Option<Pixels>,
10371 }
10372
10373 let workspace_id = workspace
10374 .database_id()
10375 .map(|id| i64::from(id).to_string())
10376 .or_else(|| workspace.session_id())?;
10377
10378 let legacy_key = match panel_key {
10379 "ProjectPanel" => {
10380 format!("{}-{:?}", "ProjectPanel", workspace_id)
10381 }
10382 "OutlinePanel" => {
10383 format!("{}-{:?}", "OutlinePanel", workspace_id)
10384 }
10385 "GitPanel" => {
10386 format!("{}-{:?}", "GitPanel", workspace_id)
10387 }
10388 "TerminalPanel" => {
10389 format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10390 }
10391 _ => return None,
10392 };
10393
10394 let kvp = db::kvp::KeyValueStore::global(cx);
10395 let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10396 let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10397 let size = match dock_position {
10398 DockPosition::Bottom => state.height,
10399 DockPosition::Left | DockPosition::Right => state.width,
10400 }?;
10401
10402 cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10403 .detach_and_log_err(cx);
10404
10405 Some(size)
10406}
10407
10408#[cfg(test)]
10409mod tests {
10410 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10411
10412 use super::*;
10413 use crate::{
10414 dock::{PanelEvent, test::TestPanel},
10415 item::{
10416 ItemBufferKind, ItemEvent,
10417 test::{TestItem, TestProjectItem},
10418 },
10419 };
10420 use fs::FakeFs;
10421 use gpui::{
10422 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10423 UpdateGlobal, VisualTestContext, px,
10424 };
10425 use project::{Project, ProjectEntryId};
10426 use serde_json::json;
10427 use settings::SettingsStore;
10428 use util::path;
10429 use util::rel_path::rel_path;
10430
10431 #[gpui::test]
10432 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10433 init_test(cx);
10434
10435 let fs = FakeFs::new(cx.executor());
10436 let project = Project::test(fs, [], cx).await;
10437 let (workspace, cx) =
10438 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10439
10440 // Adding an item with no ambiguity renders the tab without detail.
10441 let item1 = cx.new(|cx| {
10442 let mut item = TestItem::new(cx);
10443 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10444 item
10445 });
10446 workspace.update_in(cx, |workspace, window, cx| {
10447 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10448 });
10449 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10450
10451 // Adding an item that creates ambiguity increases the level of detail on
10452 // both tabs.
10453 let item2 = cx.new_window_entity(|_window, cx| {
10454 let mut item = TestItem::new(cx);
10455 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10456 item
10457 });
10458 workspace.update_in(cx, |workspace, window, cx| {
10459 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10460 });
10461 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10462 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10463
10464 // Adding an item that creates ambiguity increases the level of detail only
10465 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10466 // we stop at the highest detail available.
10467 let item3 = cx.new(|cx| {
10468 let mut item = TestItem::new(cx);
10469 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10470 item
10471 });
10472 workspace.update_in(cx, |workspace, window, cx| {
10473 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10474 });
10475 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10476 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10477 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10478 }
10479
10480 #[gpui::test]
10481 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10482 init_test(cx);
10483
10484 let fs = FakeFs::new(cx.executor());
10485 fs.insert_tree(
10486 "/root1",
10487 json!({
10488 "one.txt": "",
10489 "two.txt": "",
10490 }),
10491 )
10492 .await;
10493 fs.insert_tree(
10494 "/root2",
10495 json!({
10496 "three.txt": "",
10497 }),
10498 )
10499 .await;
10500
10501 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10502 let (workspace, cx) =
10503 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10504 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10505 let worktree_id = project.update(cx, |project, cx| {
10506 project.worktrees(cx).next().unwrap().read(cx).id()
10507 });
10508
10509 let item1 = cx.new(|cx| {
10510 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10511 });
10512 let item2 = cx.new(|cx| {
10513 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10514 });
10515
10516 // Add an item to an empty pane
10517 workspace.update_in(cx, |workspace, window, cx| {
10518 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10519 });
10520 project.update(cx, |project, cx| {
10521 assert_eq!(
10522 project.active_entry(),
10523 project
10524 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10525 .map(|e| e.id)
10526 );
10527 });
10528 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10529
10530 // Add a second item to a non-empty pane
10531 workspace.update_in(cx, |workspace, window, cx| {
10532 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10533 });
10534 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10535 project.update(cx, |project, cx| {
10536 assert_eq!(
10537 project.active_entry(),
10538 project
10539 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10540 .map(|e| e.id)
10541 );
10542 });
10543
10544 // Close the active item
10545 pane.update_in(cx, |pane, window, cx| {
10546 pane.close_active_item(&Default::default(), window, cx)
10547 })
10548 .await
10549 .unwrap();
10550 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10551 project.update(cx, |project, cx| {
10552 assert_eq!(
10553 project.active_entry(),
10554 project
10555 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10556 .map(|e| e.id)
10557 );
10558 });
10559
10560 // Add a project folder
10561 project
10562 .update(cx, |project, cx| {
10563 project.find_or_create_worktree("root2", true, cx)
10564 })
10565 .await
10566 .unwrap();
10567 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10568
10569 // Remove a project folder
10570 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10571 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10572 }
10573
10574 #[gpui::test]
10575 async fn test_close_window(cx: &mut TestAppContext) {
10576 init_test(cx);
10577
10578 let fs = FakeFs::new(cx.executor());
10579 fs.insert_tree("/root", json!({ "one": "" })).await;
10580
10581 let project = Project::test(fs, ["root".as_ref()], cx).await;
10582 let (workspace, cx) =
10583 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10584
10585 // When there are no dirty items, there's nothing to do.
10586 let item1 = cx.new(TestItem::new);
10587 workspace.update_in(cx, |w, window, cx| {
10588 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10589 });
10590 let task = workspace.update_in(cx, |w, window, cx| {
10591 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10592 });
10593 assert!(task.await.unwrap());
10594
10595 // When there are dirty untitled items, prompt to save each one. If the user
10596 // cancels any prompt, then abort.
10597 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10598 let item3 = cx.new(|cx| {
10599 TestItem::new(cx)
10600 .with_dirty(true)
10601 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10602 });
10603 workspace.update_in(cx, |w, window, cx| {
10604 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10605 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10606 });
10607 let task = workspace.update_in(cx, |w, window, cx| {
10608 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10609 });
10610 cx.executor().run_until_parked();
10611 cx.simulate_prompt_answer("Cancel"); // cancel save all
10612 cx.executor().run_until_parked();
10613 assert!(!cx.has_pending_prompt());
10614 assert!(!task.await.unwrap());
10615 }
10616
10617 #[gpui::test]
10618 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10619 init_test(cx);
10620
10621 let fs = FakeFs::new(cx.executor());
10622 fs.insert_tree("/root", json!({ "one": "" })).await;
10623
10624 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10625 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10626 let multi_workspace_handle =
10627 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10628 cx.run_until_parked();
10629
10630 let workspace_a = multi_workspace_handle
10631 .read_with(cx, |mw, _| mw.workspace().clone())
10632 .unwrap();
10633
10634 let workspace_b = multi_workspace_handle
10635 .update(cx, |mw, window, cx| {
10636 mw.test_add_workspace(project_b, window, cx)
10637 })
10638 .unwrap();
10639
10640 // Activate workspace A
10641 multi_workspace_handle
10642 .update(cx, |mw, window, cx| {
10643 mw.activate_index(0, window, cx);
10644 })
10645 .unwrap();
10646
10647 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10648
10649 // Workspace A has a clean item
10650 let item_a = cx.new(TestItem::new);
10651 workspace_a.update_in(cx, |w, window, cx| {
10652 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10653 });
10654
10655 // Workspace B has a dirty item
10656 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10657 workspace_b.update_in(cx, |w, window, cx| {
10658 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10659 });
10660
10661 // Verify workspace A is active
10662 multi_workspace_handle
10663 .read_with(cx, |mw, _| {
10664 assert_eq!(mw.active_workspace_index(), 0);
10665 })
10666 .unwrap();
10667
10668 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10669 multi_workspace_handle
10670 .update(cx, |mw, window, cx| {
10671 mw.close_window(&CloseWindow, window, cx);
10672 })
10673 .unwrap();
10674 cx.run_until_parked();
10675
10676 // Workspace B should now be active since it has dirty items that need attention
10677 multi_workspace_handle
10678 .read_with(cx, |mw, _| {
10679 assert_eq!(
10680 mw.active_workspace_index(),
10681 1,
10682 "workspace B should be activated when it prompts"
10683 );
10684 })
10685 .unwrap();
10686
10687 // User cancels the save prompt from workspace B
10688 cx.simulate_prompt_answer("Cancel");
10689 cx.run_until_parked();
10690
10691 // Window should still exist because workspace B's close was cancelled
10692 assert!(
10693 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10694 "window should still exist after cancelling one workspace's close"
10695 );
10696 }
10697
10698 #[gpui::test]
10699 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10700 init_test(cx);
10701
10702 // Register TestItem as a serializable item
10703 cx.update(|cx| {
10704 register_serializable_item::<TestItem>(cx);
10705 });
10706
10707 let fs = FakeFs::new(cx.executor());
10708 fs.insert_tree("/root", json!({ "one": "" })).await;
10709
10710 let project = Project::test(fs, ["root".as_ref()], cx).await;
10711 let (workspace, cx) =
10712 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10713
10714 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10715 let item1 = cx.new(|cx| {
10716 TestItem::new(cx)
10717 .with_dirty(true)
10718 .with_serialize(|| Some(Task::ready(Ok(()))))
10719 });
10720 let item2 = cx.new(|cx| {
10721 TestItem::new(cx)
10722 .with_dirty(true)
10723 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10724 .with_serialize(|| Some(Task::ready(Ok(()))))
10725 });
10726 workspace.update_in(cx, |w, window, cx| {
10727 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10728 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10729 });
10730 let task = workspace.update_in(cx, |w, window, cx| {
10731 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10732 });
10733 assert!(task.await.unwrap());
10734 }
10735
10736 #[gpui::test]
10737 async fn test_close_pane_items(cx: &mut TestAppContext) {
10738 init_test(cx);
10739
10740 let fs = FakeFs::new(cx.executor());
10741
10742 let project = Project::test(fs, None, cx).await;
10743 let (workspace, cx) =
10744 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10745
10746 let item1 = cx.new(|cx| {
10747 TestItem::new(cx)
10748 .with_dirty(true)
10749 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10750 });
10751 let item2 = cx.new(|cx| {
10752 TestItem::new(cx)
10753 .with_dirty(true)
10754 .with_conflict(true)
10755 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10756 });
10757 let item3 = cx.new(|cx| {
10758 TestItem::new(cx)
10759 .with_dirty(true)
10760 .with_conflict(true)
10761 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10762 });
10763 let item4 = cx.new(|cx| {
10764 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10765 let project_item = TestProjectItem::new_untitled(cx);
10766 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10767 project_item
10768 }])
10769 });
10770 let pane = workspace.update_in(cx, |workspace, window, cx| {
10771 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10772 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10773 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10774 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10775 workspace.active_pane().clone()
10776 });
10777
10778 let close_items = pane.update_in(cx, |pane, window, cx| {
10779 pane.activate_item(1, true, true, window, cx);
10780 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10781 let item1_id = item1.item_id();
10782 let item3_id = item3.item_id();
10783 let item4_id = item4.item_id();
10784 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10785 [item1_id, item3_id, item4_id].contains(&id)
10786 })
10787 });
10788 cx.executor().run_until_parked();
10789
10790 assert!(cx.has_pending_prompt());
10791 cx.simulate_prompt_answer("Save all");
10792
10793 cx.executor().run_until_parked();
10794
10795 // Item 1 is saved. There's a prompt to save item 3.
10796 pane.update(cx, |pane, cx| {
10797 assert_eq!(item1.read(cx).save_count, 1);
10798 assert_eq!(item1.read(cx).save_as_count, 0);
10799 assert_eq!(item1.read(cx).reload_count, 0);
10800 assert_eq!(pane.items_len(), 3);
10801 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10802 });
10803 assert!(cx.has_pending_prompt());
10804
10805 // Cancel saving item 3.
10806 cx.simulate_prompt_answer("Discard");
10807 cx.executor().run_until_parked();
10808
10809 // Item 3 is reloaded. There's a prompt to save item 4.
10810 pane.update(cx, |pane, cx| {
10811 assert_eq!(item3.read(cx).save_count, 0);
10812 assert_eq!(item3.read(cx).save_as_count, 0);
10813 assert_eq!(item3.read(cx).reload_count, 1);
10814 assert_eq!(pane.items_len(), 2);
10815 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10816 });
10817
10818 // There's a prompt for a path for item 4.
10819 cx.simulate_new_path_selection(|_| Some(Default::default()));
10820 close_items.await.unwrap();
10821
10822 // The requested items are closed.
10823 pane.update(cx, |pane, cx| {
10824 assert_eq!(item4.read(cx).save_count, 0);
10825 assert_eq!(item4.read(cx).save_as_count, 1);
10826 assert_eq!(item4.read(cx).reload_count, 0);
10827 assert_eq!(pane.items_len(), 1);
10828 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10829 });
10830 }
10831
10832 #[gpui::test]
10833 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10834 init_test(cx);
10835
10836 let fs = FakeFs::new(cx.executor());
10837 let project = Project::test(fs, [], cx).await;
10838 let (workspace, cx) =
10839 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10840
10841 // Create several workspace items with single project entries, and two
10842 // workspace items with multiple project entries.
10843 let single_entry_items = (0..=4)
10844 .map(|project_entry_id| {
10845 cx.new(|cx| {
10846 TestItem::new(cx)
10847 .with_dirty(true)
10848 .with_project_items(&[dirty_project_item(
10849 project_entry_id,
10850 &format!("{project_entry_id}.txt"),
10851 cx,
10852 )])
10853 })
10854 })
10855 .collect::<Vec<_>>();
10856 let item_2_3 = cx.new(|cx| {
10857 TestItem::new(cx)
10858 .with_dirty(true)
10859 .with_buffer_kind(ItemBufferKind::Multibuffer)
10860 .with_project_items(&[
10861 single_entry_items[2].read(cx).project_items[0].clone(),
10862 single_entry_items[3].read(cx).project_items[0].clone(),
10863 ])
10864 });
10865 let item_3_4 = cx.new(|cx| {
10866 TestItem::new(cx)
10867 .with_dirty(true)
10868 .with_buffer_kind(ItemBufferKind::Multibuffer)
10869 .with_project_items(&[
10870 single_entry_items[3].read(cx).project_items[0].clone(),
10871 single_entry_items[4].read(cx).project_items[0].clone(),
10872 ])
10873 });
10874
10875 // Create two panes that contain the following project entries:
10876 // left pane:
10877 // multi-entry items: (2, 3)
10878 // single-entry items: 0, 2, 3, 4
10879 // right pane:
10880 // single-entry items: 4, 1
10881 // multi-entry items: (3, 4)
10882 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10883 let left_pane = workspace.active_pane().clone();
10884 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10885 workspace.add_item_to_active_pane(
10886 single_entry_items[0].boxed_clone(),
10887 None,
10888 true,
10889 window,
10890 cx,
10891 );
10892 workspace.add_item_to_active_pane(
10893 single_entry_items[2].boxed_clone(),
10894 None,
10895 true,
10896 window,
10897 cx,
10898 );
10899 workspace.add_item_to_active_pane(
10900 single_entry_items[3].boxed_clone(),
10901 None,
10902 true,
10903 window,
10904 cx,
10905 );
10906 workspace.add_item_to_active_pane(
10907 single_entry_items[4].boxed_clone(),
10908 None,
10909 true,
10910 window,
10911 cx,
10912 );
10913
10914 let right_pane =
10915 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10916
10917 let boxed_clone = single_entry_items[1].boxed_clone();
10918 let right_pane = window.spawn(cx, async move |cx| {
10919 right_pane.await.inspect(|right_pane| {
10920 right_pane
10921 .update_in(cx, |pane, window, cx| {
10922 pane.add_item(boxed_clone, true, true, None, window, cx);
10923 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10924 })
10925 .unwrap();
10926 })
10927 });
10928
10929 (left_pane, right_pane)
10930 });
10931 let right_pane = right_pane.await.unwrap();
10932 cx.focus(&right_pane);
10933
10934 let close = right_pane.update_in(cx, |pane, window, cx| {
10935 pane.close_all_items(&CloseAllItems::default(), window, cx)
10936 .unwrap()
10937 });
10938 cx.executor().run_until_parked();
10939
10940 let msg = cx.pending_prompt().unwrap().0;
10941 assert!(msg.contains("1.txt"));
10942 assert!(!msg.contains("2.txt"));
10943 assert!(!msg.contains("3.txt"));
10944 assert!(!msg.contains("4.txt"));
10945
10946 // With best-effort close, cancelling item 1 keeps it open but items 4
10947 // and (3,4) still close since their entries exist in left pane.
10948 cx.simulate_prompt_answer("Cancel");
10949 close.await;
10950
10951 right_pane.read_with(cx, |pane, _| {
10952 assert_eq!(pane.items_len(), 1);
10953 });
10954
10955 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10956 left_pane
10957 .update_in(cx, |left_pane, window, cx| {
10958 left_pane.close_item_by_id(
10959 single_entry_items[3].entity_id(),
10960 SaveIntent::Skip,
10961 window,
10962 cx,
10963 )
10964 })
10965 .await
10966 .unwrap();
10967
10968 let close = left_pane.update_in(cx, |pane, window, cx| {
10969 pane.close_all_items(&CloseAllItems::default(), window, cx)
10970 .unwrap()
10971 });
10972 cx.executor().run_until_parked();
10973
10974 let details = cx.pending_prompt().unwrap().1;
10975 assert!(details.contains("0.txt"));
10976 assert!(details.contains("3.txt"));
10977 assert!(details.contains("4.txt"));
10978 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10979 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10980 // assert!(!details.contains("2.txt"));
10981
10982 cx.simulate_prompt_answer("Save all");
10983 cx.executor().run_until_parked();
10984 close.await;
10985
10986 left_pane.read_with(cx, |pane, _| {
10987 assert_eq!(pane.items_len(), 0);
10988 });
10989 }
10990
10991 #[gpui::test]
10992 async fn test_autosave(cx: &mut gpui::TestAppContext) {
10993 init_test(cx);
10994
10995 let fs = FakeFs::new(cx.executor());
10996 let project = Project::test(fs, [], cx).await;
10997 let (workspace, cx) =
10998 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10999 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11000
11001 let item = cx.new(|cx| {
11002 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11003 });
11004 let item_id = item.entity_id();
11005 workspace.update_in(cx, |workspace, window, cx| {
11006 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11007 });
11008
11009 // Autosave on window change.
11010 item.update(cx, |item, cx| {
11011 SettingsStore::update_global(cx, |settings, cx| {
11012 settings.update_user_settings(cx, |settings| {
11013 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11014 })
11015 });
11016 item.is_dirty = true;
11017 });
11018
11019 // Deactivating the window saves the file.
11020 cx.deactivate_window();
11021 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11022
11023 // Re-activating the window doesn't save the file.
11024 cx.update(|window, _| window.activate_window());
11025 cx.executor().run_until_parked();
11026 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11027
11028 // Autosave on focus change.
11029 item.update_in(cx, |item, window, cx| {
11030 cx.focus_self(window);
11031 SettingsStore::update_global(cx, |settings, cx| {
11032 settings.update_user_settings(cx, |settings| {
11033 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11034 })
11035 });
11036 item.is_dirty = true;
11037 });
11038 // Blurring the item saves the file.
11039 item.update_in(cx, |_, window, _| window.blur());
11040 cx.executor().run_until_parked();
11041 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11042
11043 // Deactivating the window still saves the file.
11044 item.update_in(cx, |item, window, cx| {
11045 cx.focus_self(window);
11046 item.is_dirty = true;
11047 });
11048 cx.deactivate_window();
11049 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11050
11051 // Autosave after delay.
11052 item.update(cx, |item, cx| {
11053 SettingsStore::update_global(cx, |settings, cx| {
11054 settings.update_user_settings(cx, |settings| {
11055 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11056 milliseconds: 500.into(),
11057 });
11058 })
11059 });
11060 item.is_dirty = true;
11061 cx.emit(ItemEvent::Edit);
11062 });
11063
11064 // Delay hasn't fully expired, so the file is still dirty and unsaved.
11065 cx.executor().advance_clock(Duration::from_millis(250));
11066 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11067
11068 // After delay expires, the file is saved.
11069 cx.executor().advance_clock(Duration::from_millis(250));
11070 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11071
11072 // Autosave after delay, should save earlier than delay if tab is closed
11073 item.update(cx, |item, cx| {
11074 item.is_dirty = true;
11075 cx.emit(ItemEvent::Edit);
11076 });
11077 cx.executor().advance_clock(Duration::from_millis(250));
11078 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11079
11080 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11081 pane.update_in(cx, |pane, window, cx| {
11082 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11083 })
11084 .await
11085 .unwrap();
11086 assert!(!cx.has_pending_prompt());
11087 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11088
11089 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11090 workspace.update_in(cx, |workspace, window, cx| {
11091 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11092 });
11093 item.update_in(cx, |item, _window, cx| {
11094 item.is_dirty = true;
11095 for project_item in &mut item.project_items {
11096 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11097 }
11098 });
11099 cx.run_until_parked();
11100 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11101
11102 // Autosave on focus change, ensuring closing the tab counts as such.
11103 item.update(cx, |item, cx| {
11104 SettingsStore::update_global(cx, |settings, cx| {
11105 settings.update_user_settings(cx, |settings| {
11106 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11107 })
11108 });
11109 item.is_dirty = true;
11110 for project_item in &mut item.project_items {
11111 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11112 }
11113 });
11114
11115 pane.update_in(cx, |pane, window, cx| {
11116 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11117 })
11118 .await
11119 .unwrap();
11120 assert!(!cx.has_pending_prompt());
11121 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11122
11123 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11124 workspace.update_in(cx, |workspace, window, cx| {
11125 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11126 });
11127 item.update_in(cx, |item, window, cx| {
11128 item.project_items[0].update(cx, |item, _| {
11129 item.entry_id = None;
11130 });
11131 item.is_dirty = true;
11132 window.blur();
11133 });
11134 cx.run_until_parked();
11135 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11136
11137 // Ensure autosave is prevented for deleted files also when closing the buffer.
11138 let _close_items = pane.update_in(cx, |pane, window, cx| {
11139 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11140 });
11141 cx.run_until_parked();
11142 assert!(cx.has_pending_prompt());
11143 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11144 }
11145
11146 #[gpui::test]
11147 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11148 init_test(cx);
11149
11150 let fs = FakeFs::new(cx.executor());
11151 let project = Project::test(fs, [], cx).await;
11152 let (workspace, cx) =
11153 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11154
11155 // Create a multibuffer-like item with two child focus handles,
11156 // simulating individual buffer editors within a multibuffer.
11157 let item = cx.new(|cx| {
11158 TestItem::new(cx)
11159 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11160 .with_child_focus_handles(2, cx)
11161 });
11162 workspace.update_in(cx, |workspace, window, cx| {
11163 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11164 });
11165
11166 // Set autosave to OnFocusChange and focus the first child handle,
11167 // simulating the user's cursor being inside one of the multibuffer's excerpts.
11168 item.update_in(cx, |item, window, cx| {
11169 SettingsStore::update_global(cx, |settings, cx| {
11170 settings.update_user_settings(cx, |settings| {
11171 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11172 })
11173 });
11174 item.is_dirty = true;
11175 window.focus(&item.child_focus_handles[0], cx);
11176 });
11177 cx.executor().run_until_parked();
11178 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11179
11180 // Moving focus from one child to another within the same item should
11181 // NOT trigger autosave — focus is still within the item's focus hierarchy.
11182 item.update_in(cx, |item, window, cx| {
11183 window.focus(&item.child_focus_handles[1], cx);
11184 });
11185 cx.executor().run_until_parked();
11186 item.read_with(cx, |item, _| {
11187 assert_eq!(
11188 item.save_count, 0,
11189 "Switching focus between children within the same item should not autosave"
11190 );
11191 });
11192
11193 // Blurring the item saves the file. This is the core regression scenario:
11194 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11195 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11196 // the leaf is always a child focus handle, so `on_blur` never detected
11197 // focus leaving the item.
11198 item.update_in(cx, |_, window, _| window.blur());
11199 cx.executor().run_until_parked();
11200 item.read_with(cx, |item, _| {
11201 assert_eq!(
11202 item.save_count, 1,
11203 "Blurring should trigger autosave when focus was on a child of the item"
11204 );
11205 });
11206
11207 // Deactivating the window should also trigger autosave when a child of
11208 // the multibuffer item currently owns focus.
11209 item.update_in(cx, |item, window, cx| {
11210 item.is_dirty = true;
11211 window.focus(&item.child_focus_handles[0], cx);
11212 });
11213 cx.executor().run_until_parked();
11214 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11215
11216 cx.deactivate_window();
11217 item.read_with(cx, |item, _| {
11218 assert_eq!(
11219 item.save_count, 2,
11220 "Deactivating window should trigger autosave when focus was on a child"
11221 );
11222 });
11223 }
11224
11225 #[gpui::test]
11226 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11227 init_test(cx);
11228
11229 let fs = FakeFs::new(cx.executor());
11230
11231 let project = Project::test(fs, [], cx).await;
11232 let (workspace, cx) =
11233 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11234
11235 let item = cx.new(|cx| {
11236 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11237 });
11238 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11239 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11240 let toolbar_notify_count = Rc::new(RefCell::new(0));
11241
11242 workspace.update_in(cx, |workspace, window, cx| {
11243 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11244 let toolbar_notification_count = toolbar_notify_count.clone();
11245 cx.observe_in(&toolbar, window, move |_, _, _, _| {
11246 *toolbar_notification_count.borrow_mut() += 1
11247 })
11248 .detach();
11249 });
11250
11251 pane.read_with(cx, |pane, _| {
11252 assert!(!pane.can_navigate_backward());
11253 assert!(!pane.can_navigate_forward());
11254 });
11255
11256 item.update_in(cx, |item, _, cx| {
11257 item.set_state("one".to_string(), cx);
11258 });
11259
11260 // Toolbar must be notified to re-render the navigation buttons
11261 assert_eq!(*toolbar_notify_count.borrow(), 1);
11262
11263 pane.read_with(cx, |pane, _| {
11264 assert!(pane.can_navigate_backward());
11265 assert!(!pane.can_navigate_forward());
11266 });
11267
11268 workspace
11269 .update_in(cx, |workspace, window, cx| {
11270 workspace.go_back(pane.downgrade(), window, cx)
11271 })
11272 .await
11273 .unwrap();
11274
11275 assert_eq!(*toolbar_notify_count.borrow(), 2);
11276 pane.read_with(cx, |pane, _| {
11277 assert!(!pane.can_navigate_backward());
11278 assert!(pane.can_navigate_forward());
11279 });
11280 }
11281
11282 /// Tests that the navigation history deduplicates entries for the same item.
11283 ///
11284 /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11285 /// the navigation history deduplicates by keeping only the most recent visit to each item,
11286 /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11287 /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11288 /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11289 ///
11290 /// This behavior prevents the navigation history from growing unnecessarily large and provides
11291 /// a better user experience by eliminating redundant navigation steps when jumping between files.
11292 #[gpui::test]
11293 async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11294 init_test(cx);
11295
11296 let fs = FakeFs::new(cx.executor());
11297 let project = Project::test(fs, [], cx).await;
11298 let (workspace, cx) =
11299 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11300
11301 let item_a = cx.new(|cx| {
11302 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11303 });
11304 let item_b = cx.new(|cx| {
11305 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11306 });
11307 let item_c = cx.new(|cx| {
11308 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11309 });
11310
11311 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11312
11313 workspace.update_in(cx, |workspace, window, cx| {
11314 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11315 workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11316 workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11317 });
11318
11319 workspace.update_in(cx, |workspace, window, cx| {
11320 workspace.activate_item(&item_a, false, false, window, cx);
11321 });
11322 cx.run_until_parked();
11323
11324 workspace.update_in(cx, |workspace, window, cx| {
11325 workspace.activate_item(&item_b, false, false, window, cx);
11326 });
11327 cx.run_until_parked();
11328
11329 workspace.update_in(cx, |workspace, window, cx| {
11330 workspace.activate_item(&item_a, false, false, window, cx);
11331 });
11332 cx.run_until_parked();
11333
11334 workspace.update_in(cx, |workspace, window, cx| {
11335 workspace.activate_item(&item_b, false, false, window, cx);
11336 });
11337 cx.run_until_parked();
11338
11339 workspace.update_in(cx, |workspace, window, cx| {
11340 workspace.activate_item(&item_a, false, false, window, cx);
11341 });
11342 cx.run_until_parked();
11343
11344 workspace.update_in(cx, |workspace, window, cx| {
11345 workspace.activate_item(&item_b, false, false, window, cx);
11346 });
11347 cx.run_until_parked();
11348
11349 workspace.update_in(cx, |workspace, window, cx| {
11350 workspace.activate_item(&item_c, false, false, window, cx);
11351 });
11352 cx.run_until_parked();
11353
11354 let backward_count = pane.read_with(cx, |pane, cx| {
11355 let mut count = 0;
11356 pane.nav_history().for_each_entry(cx, &mut |_, _| {
11357 count += 1;
11358 });
11359 count
11360 });
11361 assert!(
11362 backward_count <= 4,
11363 "Should have at most 4 entries, got {}",
11364 backward_count
11365 );
11366
11367 workspace
11368 .update_in(cx, |workspace, window, cx| {
11369 workspace.go_back(pane.downgrade(), window, cx)
11370 })
11371 .await
11372 .unwrap();
11373
11374 let active_item = workspace.read_with(cx, |workspace, cx| {
11375 workspace.active_item(cx).unwrap().item_id()
11376 });
11377 assert_eq!(
11378 active_item,
11379 item_b.entity_id(),
11380 "After first go_back, should be at item B"
11381 );
11382
11383 workspace
11384 .update_in(cx, |workspace, window, cx| {
11385 workspace.go_back(pane.downgrade(), window, cx)
11386 })
11387 .await
11388 .unwrap();
11389
11390 let active_item = workspace.read_with(cx, |workspace, cx| {
11391 workspace.active_item(cx).unwrap().item_id()
11392 });
11393 assert_eq!(
11394 active_item,
11395 item_a.entity_id(),
11396 "After second go_back, should be at item A"
11397 );
11398
11399 pane.read_with(cx, |pane, _| {
11400 assert!(pane.can_navigate_forward(), "Should be able to go forward");
11401 });
11402 }
11403
11404 #[gpui::test]
11405 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11406 init_test(cx);
11407 let fs = FakeFs::new(cx.executor());
11408 let project = Project::test(fs, [], cx).await;
11409 let (multi_workspace, cx) =
11410 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11411 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11412
11413 workspace.update_in(cx, |workspace, window, cx| {
11414 let first_item = cx.new(|cx| {
11415 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11416 });
11417 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11418 workspace.split_pane(
11419 workspace.active_pane().clone(),
11420 SplitDirection::Right,
11421 window,
11422 cx,
11423 );
11424 workspace.split_pane(
11425 workspace.active_pane().clone(),
11426 SplitDirection::Right,
11427 window,
11428 cx,
11429 );
11430 });
11431
11432 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11433 let panes = workspace.center.panes();
11434 assert!(panes.len() >= 2);
11435 (
11436 panes.first().expect("at least one pane").entity_id(),
11437 panes.last().expect("at least one pane").entity_id(),
11438 )
11439 });
11440
11441 workspace.update_in(cx, |workspace, window, cx| {
11442 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11443 });
11444 workspace.update(cx, |workspace, _| {
11445 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11446 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11447 });
11448
11449 cx.dispatch_action(ActivateLastPane);
11450
11451 workspace.update(cx, |workspace, _| {
11452 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11453 });
11454 }
11455
11456 #[gpui::test]
11457 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11458 init_test(cx);
11459 let fs = FakeFs::new(cx.executor());
11460
11461 let project = Project::test(fs, [], cx).await;
11462 let (workspace, cx) =
11463 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11464
11465 let panel = workspace.update_in(cx, |workspace, window, cx| {
11466 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11467 workspace.add_panel(panel.clone(), window, cx);
11468
11469 workspace
11470 .right_dock()
11471 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11472
11473 panel
11474 });
11475
11476 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11477 pane.update_in(cx, |pane, window, cx| {
11478 let item = cx.new(TestItem::new);
11479 pane.add_item(Box::new(item), true, true, None, window, cx);
11480 });
11481
11482 // Transfer focus from center to panel
11483 workspace.update_in(cx, |workspace, window, cx| {
11484 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11485 });
11486
11487 workspace.update_in(cx, |workspace, window, cx| {
11488 assert!(workspace.right_dock().read(cx).is_open());
11489 assert!(!panel.is_zoomed(window, cx));
11490 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11491 });
11492
11493 // Transfer focus from panel to center
11494 workspace.update_in(cx, |workspace, window, cx| {
11495 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11496 });
11497
11498 workspace.update_in(cx, |workspace, window, cx| {
11499 assert!(workspace.right_dock().read(cx).is_open());
11500 assert!(!panel.is_zoomed(window, cx));
11501 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11502 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11503 });
11504
11505 // Close the dock
11506 workspace.update_in(cx, |workspace, window, cx| {
11507 workspace.toggle_dock(DockPosition::Right, window, cx);
11508 });
11509
11510 workspace.update_in(cx, |workspace, window, cx| {
11511 assert!(!workspace.right_dock().read(cx).is_open());
11512 assert!(!panel.is_zoomed(window, cx));
11513 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11514 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11515 });
11516
11517 // Open the dock
11518 workspace.update_in(cx, |workspace, window, cx| {
11519 workspace.toggle_dock(DockPosition::Right, window, cx);
11520 });
11521
11522 workspace.update_in(cx, |workspace, window, cx| {
11523 assert!(workspace.right_dock().read(cx).is_open());
11524 assert!(!panel.is_zoomed(window, cx));
11525 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11526 });
11527
11528 // Focus and zoom panel
11529 panel.update_in(cx, |panel, window, cx| {
11530 cx.focus_self(window);
11531 panel.set_zoomed(true, window, cx)
11532 });
11533
11534 workspace.update_in(cx, |workspace, window, cx| {
11535 assert!(workspace.right_dock().read(cx).is_open());
11536 assert!(panel.is_zoomed(window, cx));
11537 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11538 });
11539
11540 // Transfer focus to the center closes the dock
11541 workspace.update_in(cx, |workspace, window, cx| {
11542 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11543 });
11544
11545 workspace.update_in(cx, |workspace, window, cx| {
11546 assert!(!workspace.right_dock().read(cx).is_open());
11547 assert!(panel.is_zoomed(window, cx));
11548 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11549 });
11550
11551 // Transferring focus back to the panel keeps it zoomed
11552 workspace.update_in(cx, |workspace, window, cx| {
11553 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11554 });
11555
11556 workspace.update_in(cx, |workspace, window, cx| {
11557 assert!(workspace.right_dock().read(cx).is_open());
11558 assert!(panel.is_zoomed(window, cx));
11559 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11560 });
11561
11562 // Close the dock while it is zoomed
11563 workspace.update_in(cx, |workspace, window, cx| {
11564 workspace.toggle_dock(DockPosition::Right, window, cx)
11565 });
11566
11567 workspace.update_in(cx, |workspace, window, cx| {
11568 assert!(!workspace.right_dock().read(cx).is_open());
11569 assert!(panel.is_zoomed(window, cx));
11570 assert!(workspace.zoomed.is_none());
11571 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11572 });
11573
11574 // Opening the dock, when it's zoomed, retains focus
11575 workspace.update_in(cx, |workspace, window, cx| {
11576 workspace.toggle_dock(DockPosition::Right, window, cx)
11577 });
11578
11579 workspace.update_in(cx, |workspace, window, cx| {
11580 assert!(workspace.right_dock().read(cx).is_open());
11581 assert!(panel.is_zoomed(window, cx));
11582 assert!(workspace.zoomed.is_some());
11583 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11584 });
11585
11586 // Unzoom and close the panel, zoom the active pane.
11587 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11588 workspace.update_in(cx, |workspace, window, cx| {
11589 workspace.toggle_dock(DockPosition::Right, window, cx)
11590 });
11591 pane.update_in(cx, |pane, window, cx| {
11592 pane.toggle_zoom(&Default::default(), window, cx)
11593 });
11594
11595 // Opening a dock unzooms the pane.
11596 workspace.update_in(cx, |workspace, window, cx| {
11597 workspace.toggle_dock(DockPosition::Right, window, cx)
11598 });
11599 workspace.update_in(cx, |workspace, window, cx| {
11600 let pane = pane.read(cx);
11601 assert!(!pane.is_zoomed());
11602 assert!(!pane.focus_handle(cx).is_focused(window));
11603 assert!(workspace.right_dock().read(cx).is_open());
11604 assert!(workspace.zoomed.is_none());
11605 });
11606 }
11607
11608 #[gpui::test]
11609 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11610 init_test(cx);
11611 let fs = FakeFs::new(cx.executor());
11612
11613 let project = Project::test(fs, [], cx).await;
11614 let (workspace, cx) =
11615 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11616
11617 let panel = workspace.update_in(cx, |workspace, window, cx| {
11618 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11619 workspace.add_panel(panel.clone(), window, cx);
11620 panel
11621 });
11622
11623 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11624 pane.update_in(cx, |pane, window, cx| {
11625 let item = cx.new(TestItem::new);
11626 pane.add_item(Box::new(item), true, true, None, window, cx);
11627 });
11628
11629 // Enable close_panel_on_toggle
11630 cx.update_global(|store: &mut SettingsStore, cx| {
11631 store.update_user_settings(cx, |settings| {
11632 settings.workspace.close_panel_on_toggle = Some(true);
11633 });
11634 });
11635
11636 // Panel starts closed. Toggling should open and focus it.
11637 workspace.update_in(cx, |workspace, window, cx| {
11638 assert!(!workspace.right_dock().read(cx).is_open());
11639 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11640 });
11641
11642 workspace.update_in(cx, |workspace, window, cx| {
11643 assert!(
11644 workspace.right_dock().read(cx).is_open(),
11645 "Dock should be open after toggling from center"
11646 );
11647 assert!(
11648 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11649 "Panel should be focused after toggling from center"
11650 );
11651 });
11652
11653 // Panel is open and focused. Toggling should close the panel and
11654 // return focus to the center.
11655 workspace.update_in(cx, |workspace, window, cx| {
11656 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11657 });
11658
11659 workspace.update_in(cx, |workspace, window, cx| {
11660 assert!(
11661 !workspace.right_dock().read(cx).is_open(),
11662 "Dock should be closed after toggling from focused panel"
11663 );
11664 assert!(
11665 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11666 "Panel should not be focused after toggling from focused panel"
11667 );
11668 });
11669
11670 // Open the dock and focus something else so the panel is open but not
11671 // focused. Toggling should focus the panel (not close it).
11672 workspace.update_in(cx, |workspace, window, cx| {
11673 workspace
11674 .right_dock()
11675 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11676 window.focus(&pane.read(cx).focus_handle(cx), cx);
11677 });
11678
11679 workspace.update_in(cx, |workspace, window, cx| {
11680 assert!(workspace.right_dock().read(cx).is_open());
11681 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11682 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11683 });
11684
11685 workspace.update_in(cx, |workspace, window, cx| {
11686 assert!(
11687 workspace.right_dock().read(cx).is_open(),
11688 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11689 );
11690 assert!(
11691 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11692 "Panel should be focused after toggling an open-but-unfocused panel"
11693 );
11694 });
11695
11696 // Now disable the setting and verify the original behavior: toggling
11697 // from a focused panel moves focus to center but leaves the dock open.
11698 cx.update_global(|store: &mut SettingsStore, cx| {
11699 store.update_user_settings(cx, |settings| {
11700 settings.workspace.close_panel_on_toggle = Some(false);
11701 });
11702 });
11703
11704 workspace.update_in(cx, |workspace, window, cx| {
11705 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11706 });
11707
11708 workspace.update_in(cx, |workspace, window, cx| {
11709 assert!(
11710 workspace.right_dock().read(cx).is_open(),
11711 "Dock should remain open when setting is disabled"
11712 );
11713 assert!(
11714 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11715 "Panel should not be focused after toggling with setting disabled"
11716 );
11717 });
11718 }
11719
11720 #[gpui::test]
11721 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11722 init_test(cx);
11723 let fs = FakeFs::new(cx.executor());
11724
11725 let project = Project::test(fs, [], cx).await;
11726 let (workspace, cx) =
11727 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11728
11729 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11730 workspace.active_pane().clone()
11731 });
11732
11733 // Add an item to the pane so it can be zoomed
11734 workspace.update_in(cx, |workspace, window, cx| {
11735 let item = cx.new(TestItem::new);
11736 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11737 });
11738
11739 // Initially not zoomed
11740 workspace.update_in(cx, |workspace, _window, cx| {
11741 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11742 assert!(
11743 workspace.zoomed.is_none(),
11744 "Workspace should track no zoomed pane"
11745 );
11746 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11747 });
11748
11749 // Zoom In
11750 pane.update_in(cx, |pane, window, cx| {
11751 pane.zoom_in(&crate::ZoomIn, window, cx);
11752 });
11753
11754 workspace.update_in(cx, |workspace, window, cx| {
11755 assert!(
11756 pane.read(cx).is_zoomed(),
11757 "Pane should be zoomed after ZoomIn"
11758 );
11759 assert!(
11760 workspace.zoomed.is_some(),
11761 "Workspace should track the zoomed pane"
11762 );
11763 assert!(
11764 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11765 "ZoomIn should focus the pane"
11766 );
11767 });
11768
11769 // Zoom In again is a no-op
11770 pane.update_in(cx, |pane, window, cx| {
11771 pane.zoom_in(&crate::ZoomIn, window, cx);
11772 });
11773
11774 workspace.update_in(cx, |workspace, window, cx| {
11775 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11776 assert!(
11777 workspace.zoomed.is_some(),
11778 "Workspace still tracks zoomed pane"
11779 );
11780 assert!(
11781 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11782 "Pane remains focused after repeated ZoomIn"
11783 );
11784 });
11785
11786 // Zoom Out
11787 pane.update_in(cx, |pane, window, cx| {
11788 pane.zoom_out(&crate::ZoomOut, window, cx);
11789 });
11790
11791 workspace.update_in(cx, |workspace, _window, cx| {
11792 assert!(
11793 !pane.read(cx).is_zoomed(),
11794 "Pane should unzoom after ZoomOut"
11795 );
11796 assert!(
11797 workspace.zoomed.is_none(),
11798 "Workspace clears zoom tracking after ZoomOut"
11799 );
11800 });
11801
11802 // Zoom Out again is a no-op
11803 pane.update_in(cx, |pane, window, cx| {
11804 pane.zoom_out(&crate::ZoomOut, window, cx);
11805 });
11806
11807 workspace.update_in(cx, |workspace, _window, cx| {
11808 assert!(
11809 !pane.read(cx).is_zoomed(),
11810 "Second ZoomOut keeps pane unzoomed"
11811 );
11812 assert!(
11813 workspace.zoomed.is_none(),
11814 "Workspace remains without zoomed pane"
11815 );
11816 });
11817 }
11818
11819 #[gpui::test]
11820 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11821 init_test(cx);
11822 let fs = FakeFs::new(cx.executor());
11823
11824 let project = Project::test(fs, [], cx).await;
11825 let (workspace, cx) =
11826 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11827 workspace.update_in(cx, |workspace, window, cx| {
11828 // Open two docks
11829 let left_dock = workspace.dock_at_position(DockPosition::Left);
11830 let right_dock = workspace.dock_at_position(DockPosition::Right);
11831
11832 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11833 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11834
11835 assert!(left_dock.read(cx).is_open());
11836 assert!(right_dock.read(cx).is_open());
11837 });
11838
11839 workspace.update_in(cx, |workspace, window, cx| {
11840 // Toggle all docks - should close both
11841 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11842
11843 let left_dock = workspace.dock_at_position(DockPosition::Left);
11844 let right_dock = workspace.dock_at_position(DockPosition::Right);
11845 assert!(!left_dock.read(cx).is_open());
11846 assert!(!right_dock.read(cx).is_open());
11847 });
11848
11849 workspace.update_in(cx, |workspace, window, cx| {
11850 // Toggle again - should reopen both
11851 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11852
11853 let left_dock = workspace.dock_at_position(DockPosition::Left);
11854 let right_dock = workspace.dock_at_position(DockPosition::Right);
11855 assert!(left_dock.read(cx).is_open());
11856 assert!(right_dock.read(cx).is_open());
11857 });
11858 }
11859
11860 #[gpui::test]
11861 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11862 init_test(cx);
11863 let fs = FakeFs::new(cx.executor());
11864
11865 let project = Project::test(fs, [], cx).await;
11866 let (workspace, cx) =
11867 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11868 workspace.update_in(cx, |workspace, window, cx| {
11869 // Open two docks
11870 let left_dock = workspace.dock_at_position(DockPosition::Left);
11871 let right_dock = workspace.dock_at_position(DockPosition::Right);
11872
11873 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11874 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11875
11876 assert!(left_dock.read(cx).is_open());
11877 assert!(right_dock.read(cx).is_open());
11878 });
11879
11880 workspace.update_in(cx, |workspace, window, cx| {
11881 // Close them manually
11882 workspace.toggle_dock(DockPosition::Left, window, cx);
11883 workspace.toggle_dock(DockPosition::Right, window, cx);
11884
11885 let left_dock = workspace.dock_at_position(DockPosition::Left);
11886 let right_dock = workspace.dock_at_position(DockPosition::Right);
11887 assert!(!left_dock.read(cx).is_open());
11888 assert!(!right_dock.read(cx).is_open());
11889 });
11890
11891 workspace.update_in(cx, |workspace, window, cx| {
11892 // Toggle all docks - only last closed (right dock) should reopen
11893 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11894
11895 let left_dock = workspace.dock_at_position(DockPosition::Left);
11896 let right_dock = workspace.dock_at_position(DockPosition::Right);
11897 assert!(!left_dock.read(cx).is_open());
11898 assert!(right_dock.read(cx).is_open());
11899 });
11900 }
11901
11902 #[gpui::test]
11903 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11904 init_test(cx);
11905 let fs = FakeFs::new(cx.executor());
11906 let project = Project::test(fs, [], cx).await;
11907 let (multi_workspace, cx) =
11908 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11909 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11910
11911 // Open two docks (left and right) with one panel each
11912 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11913 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11914 workspace.add_panel(left_panel.clone(), window, cx);
11915
11916 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11917 workspace.add_panel(right_panel.clone(), window, cx);
11918
11919 workspace.toggle_dock(DockPosition::Left, window, cx);
11920 workspace.toggle_dock(DockPosition::Right, window, cx);
11921
11922 // Verify initial state
11923 assert!(
11924 workspace.left_dock().read(cx).is_open(),
11925 "Left dock should be open"
11926 );
11927 assert_eq!(
11928 workspace
11929 .left_dock()
11930 .read(cx)
11931 .visible_panel()
11932 .unwrap()
11933 .panel_id(),
11934 left_panel.panel_id(),
11935 "Left panel should be visible in left dock"
11936 );
11937 assert!(
11938 workspace.right_dock().read(cx).is_open(),
11939 "Right dock should be open"
11940 );
11941 assert_eq!(
11942 workspace
11943 .right_dock()
11944 .read(cx)
11945 .visible_panel()
11946 .unwrap()
11947 .panel_id(),
11948 right_panel.panel_id(),
11949 "Right panel should be visible in right dock"
11950 );
11951 assert!(
11952 !workspace.bottom_dock().read(cx).is_open(),
11953 "Bottom dock should be closed"
11954 );
11955
11956 (left_panel, right_panel)
11957 });
11958
11959 // Focus the left panel and move it to the next position (bottom dock)
11960 workspace.update_in(cx, |workspace, window, cx| {
11961 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11962 assert!(
11963 left_panel.read(cx).focus_handle(cx).is_focused(window),
11964 "Left panel should be focused"
11965 );
11966 });
11967
11968 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11969
11970 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11971 workspace.update(cx, |workspace, cx| {
11972 assert!(
11973 !workspace.left_dock().read(cx).is_open(),
11974 "Left dock should be closed"
11975 );
11976 assert!(
11977 workspace.bottom_dock().read(cx).is_open(),
11978 "Bottom dock should now be open"
11979 );
11980 assert_eq!(
11981 left_panel.read(cx).position,
11982 DockPosition::Bottom,
11983 "Left panel should now be in the bottom dock"
11984 );
11985 assert_eq!(
11986 workspace
11987 .bottom_dock()
11988 .read(cx)
11989 .visible_panel()
11990 .unwrap()
11991 .panel_id(),
11992 left_panel.panel_id(),
11993 "Left panel should be the visible panel in the bottom dock"
11994 );
11995 });
11996
11997 // Toggle all docks off
11998 workspace.update_in(cx, |workspace, window, cx| {
11999 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12000 assert!(
12001 !workspace.left_dock().read(cx).is_open(),
12002 "Left dock should be closed"
12003 );
12004 assert!(
12005 !workspace.right_dock().read(cx).is_open(),
12006 "Right dock should be closed"
12007 );
12008 assert!(
12009 !workspace.bottom_dock().read(cx).is_open(),
12010 "Bottom dock should be closed"
12011 );
12012 });
12013
12014 // Toggle all docks back on and verify positions are restored
12015 workspace.update_in(cx, |workspace, window, cx| {
12016 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12017 assert!(
12018 !workspace.left_dock().read(cx).is_open(),
12019 "Left dock should remain closed"
12020 );
12021 assert!(
12022 workspace.right_dock().read(cx).is_open(),
12023 "Right dock should remain open"
12024 );
12025 assert!(
12026 workspace.bottom_dock().read(cx).is_open(),
12027 "Bottom dock should remain open"
12028 );
12029 assert_eq!(
12030 left_panel.read(cx).position,
12031 DockPosition::Bottom,
12032 "Left panel should remain in the bottom dock"
12033 );
12034 assert_eq!(
12035 right_panel.read(cx).position,
12036 DockPosition::Right,
12037 "Right panel should remain in the right dock"
12038 );
12039 assert_eq!(
12040 workspace
12041 .bottom_dock()
12042 .read(cx)
12043 .visible_panel()
12044 .unwrap()
12045 .panel_id(),
12046 left_panel.panel_id(),
12047 "Left panel should be the visible panel in the right dock"
12048 );
12049 });
12050 }
12051
12052 #[gpui::test]
12053 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12054 init_test(cx);
12055
12056 let fs = FakeFs::new(cx.executor());
12057
12058 let project = Project::test(fs, None, cx).await;
12059 let (workspace, cx) =
12060 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12061
12062 // Let's arrange the panes like this:
12063 //
12064 // +-----------------------+
12065 // | top |
12066 // +------+--------+-------+
12067 // | left | center | right |
12068 // +------+--------+-------+
12069 // | bottom |
12070 // +-----------------------+
12071
12072 let top_item = cx.new(|cx| {
12073 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12074 });
12075 let bottom_item = cx.new(|cx| {
12076 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12077 });
12078 let left_item = cx.new(|cx| {
12079 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12080 });
12081 let right_item = cx.new(|cx| {
12082 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12083 });
12084 let center_item = cx.new(|cx| {
12085 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12086 });
12087
12088 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12089 let top_pane_id = workspace.active_pane().entity_id();
12090 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12091 workspace.split_pane(
12092 workspace.active_pane().clone(),
12093 SplitDirection::Down,
12094 window,
12095 cx,
12096 );
12097 top_pane_id
12098 });
12099 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12100 let bottom_pane_id = workspace.active_pane().entity_id();
12101 workspace.add_item_to_active_pane(
12102 Box::new(bottom_item.clone()),
12103 None,
12104 false,
12105 window,
12106 cx,
12107 );
12108 workspace.split_pane(
12109 workspace.active_pane().clone(),
12110 SplitDirection::Up,
12111 window,
12112 cx,
12113 );
12114 bottom_pane_id
12115 });
12116 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12117 let left_pane_id = workspace.active_pane().entity_id();
12118 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12119 workspace.split_pane(
12120 workspace.active_pane().clone(),
12121 SplitDirection::Right,
12122 window,
12123 cx,
12124 );
12125 left_pane_id
12126 });
12127 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12128 let right_pane_id = workspace.active_pane().entity_id();
12129 workspace.add_item_to_active_pane(
12130 Box::new(right_item.clone()),
12131 None,
12132 false,
12133 window,
12134 cx,
12135 );
12136 workspace.split_pane(
12137 workspace.active_pane().clone(),
12138 SplitDirection::Left,
12139 window,
12140 cx,
12141 );
12142 right_pane_id
12143 });
12144 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12145 let center_pane_id = workspace.active_pane().entity_id();
12146 workspace.add_item_to_active_pane(
12147 Box::new(center_item.clone()),
12148 None,
12149 false,
12150 window,
12151 cx,
12152 );
12153 center_pane_id
12154 });
12155 cx.executor().run_until_parked();
12156
12157 workspace.update_in(cx, |workspace, window, cx| {
12158 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12159
12160 // Join into next from center pane into right
12161 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12162 });
12163
12164 workspace.update_in(cx, |workspace, window, cx| {
12165 let active_pane = workspace.active_pane();
12166 assert_eq!(right_pane_id, active_pane.entity_id());
12167 assert_eq!(2, active_pane.read(cx).items_len());
12168 let item_ids_in_pane =
12169 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12170 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12171 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12172
12173 // Join into next from right pane into bottom
12174 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12175 });
12176
12177 workspace.update_in(cx, |workspace, window, cx| {
12178 let active_pane = workspace.active_pane();
12179 assert_eq!(bottom_pane_id, active_pane.entity_id());
12180 assert_eq!(3, active_pane.read(cx).items_len());
12181 let item_ids_in_pane =
12182 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12183 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12184 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12185 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12186
12187 // Join into next from bottom pane into left
12188 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12189 });
12190
12191 workspace.update_in(cx, |workspace, window, cx| {
12192 let active_pane = workspace.active_pane();
12193 assert_eq!(left_pane_id, active_pane.entity_id());
12194 assert_eq!(4, active_pane.read(cx).items_len());
12195 let item_ids_in_pane =
12196 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12197 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12198 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12199 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12200 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12201
12202 // Join into next from left pane into top
12203 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12204 });
12205
12206 workspace.update_in(cx, |workspace, window, cx| {
12207 let active_pane = workspace.active_pane();
12208 assert_eq!(top_pane_id, active_pane.entity_id());
12209 assert_eq!(5, active_pane.read(cx).items_len());
12210 let item_ids_in_pane =
12211 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12212 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12213 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12214 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12215 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12216 assert!(item_ids_in_pane.contains(&top_item.item_id()));
12217
12218 // Single pane left: no-op
12219 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12220 });
12221
12222 workspace.update(cx, |workspace, _cx| {
12223 let active_pane = workspace.active_pane();
12224 assert_eq!(top_pane_id, active_pane.entity_id());
12225 });
12226 }
12227
12228 fn add_an_item_to_active_pane(
12229 cx: &mut VisualTestContext,
12230 workspace: &Entity<Workspace>,
12231 item_id: u64,
12232 ) -> Entity<TestItem> {
12233 let item = cx.new(|cx| {
12234 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12235 item_id,
12236 "item{item_id}.txt",
12237 cx,
12238 )])
12239 });
12240 workspace.update_in(cx, |workspace, window, cx| {
12241 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12242 });
12243 item
12244 }
12245
12246 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12247 workspace.update_in(cx, |workspace, window, cx| {
12248 workspace.split_pane(
12249 workspace.active_pane().clone(),
12250 SplitDirection::Right,
12251 window,
12252 cx,
12253 )
12254 })
12255 }
12256
12257 #[gpui::test]
12258 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12259 init_test(cx);
12260 let fs = FakeFs::new(cx.executor());
12261 let project = Project::test(fs, None, cx).await;
12262 let (workspace, cx) =
12263 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12264
12265 add_an_item_to_active_pane(cx, &workspace, 1);
12266 split_pane(cx, &workspace);
12267 add_an_item_to_active_pane(cx, &workspace, 2);
12268 split_pane(cx, &workspace); // empty pane
12269 split_pane(cx, &workspace);
12270 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12271
12272 cx.executor().run_until_parked();
12273
12274 workspace.update(cx, |workspace, cx| {
12275 let num_panes = workspace.panes().len();
12276 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12277 let active_item = workspace
12278 .active_pane()
12279 .read(cx)
12280 .active_item()
12281 .expect("item is in focus");
12282
12283 assert_eq!(num_panes, 4);
12284 assert_eq!(num_items_in_current_pane, 1);
12285 assert_eq!(active_item.item_id(), last_item.item_id());
12286 });
12287
12288 workspace.update_in(cx, |workspace, window, cx| {
12289 workspace.join_all_panes(window, cx);
12290 });
12291
12292 workspace.update(cx, |workspace, cx| {
12293 let num_panes = workspace.panes().len();
12294 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12295 let active_item = workspace
12296 .active_pane()
12297 .read(cx)
12298 .active_item()
12299 .expect("item is in focus");
12300
12301 assert_eq!(num_panes, 1);
12302 assert_eq!(num_items_in_current_pane, 3);
12303 assert_eq!(active_item.item_id(), last_item.item_id());
12304 });
12305 }
12306
12307 #[gpui::test]
12308 async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12309 init_test(cx);
12310 let fs = FakeFs::new(cx.executor());
12311
12312 let project = Project::test(fs, [], cx).await;
12313 let (multi_workspace, cx) =
12314 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12315 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12316
12317 workspace.update(cx, |workspace, _cx| {
12318 workspace.bounds.size.width = px(800.);
12319 });
12320
12321 workspace.update_in(cx, |workspace, window, cx| {
12322 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12323 workspace.add_panel(panel, window, cx);
12324 workspace.toggle_dock(DockPosition::Right, window, cx);
12325 });
12326
12327 let (panel, resized_width, ratio_basis_width) =
12328 workspace.update_in(cx, |workspace, window, cx| {
12329 let item = cx.new(|cx| {
12330 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12331 });
12332 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12333
12334 let dock = workspace.right_dock().read(cx);
12335 let workspace_width = workspace.bounds.size.width;
12336 let initial_width = workspace
12337 .dock_size(&dock, window, cx)
12338 .expect("flexible dock should have an initial width");
12339
12340 assert_eq!(initial_width, workspace_width / 2.);
12341
12342 workspace.resize_right_dock(px(300.), window, cx);
12343
12344 let dock = workspace.right_dock().read(cx);
12345 let resized_width = workspace
12346 .dock_size(&dock, window, cx)
12347 .expect("flexible dock should keep its resized width");
12348
12349 assert_eq!(resized_width, px(300.));
12350
12351 let panel = workspace
12352 .right_dock()
12353 .read(cx)
12354 .visible_panel()
12355 .expect("flexible dock should have a visible panel")
12356 .panel_id();
12357
12358 (panel, resized_width, workspace_width)
12359 });
12360
12361 workspace.update_in(cx, |workspace, window, cx| {
12362 workspace.toggle_dock(DockPosition::Right, window, cx);
12363 workspace.toggle_dock(DockPosition::Right, window, cx);
12364
12365 let dock = workspace.right_dock().read(cx);
12366 let reopened_width = workspace
12367 .dock_size(&dock, window, cx)
12368 .expect("flexible dock should restore when reopened");
12369
12370 assert_eq!(reopened_width, resized_width);
12371
12372 let right_dock = workspace.right_dock().read(cx);
12373 let flexible_panel = right_dock
12374 .visible_panel()
12375 .expect("flexible dock should still have a visible panel");
12376 assert_eq!(flexible_panel.panel_id(), panel);
12377 assert_eq!(
12378 right_dock
12379 .stored_panel_size_state(flexible_panel.as_ref())
12380 .and_then(|size_state| size_state.flex),
12381 Some(
12382 resized_width.to_f64() as f32
12383 / (workspace.bounds.size.width - resized_width).to_f64() as f32
12384 )
12385 );
12386 });
12387
12388 workspace.update_in(cx, |workspace, window, cx| {
12389 workspace.split_pane(
12390 workspace.active_pane().clone(),
12391 SplitDirection::Right,
12392 window,
12393 cx,
12394 );
12395
12396 let dock = workspace.right_dock().read(cx);
12397 let split_width = workspace
12398 .dock_size(&dock, window, cx)
12399 .expect("flexible dock should keep its user-resized proportion");
12400
12401 assert_eq!(split_width, px(300.));
12402
12403 workspace.bounds.size.width = px(1600.);
12404
12405 let dock = workspace.right_dock().read(cx);
12406 let resized_window_width = workspace
12407 .dock_size(&dock, window, cx)
12408 .expect("flexible dock should preserve proportional size on window resize");
12409
12410 assert_eq!(
12411 resized_window_width,
12412 workspace.bounds.size.width
12413 * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12414 );
12415 });
12416 }
12417
12418 #[gpui::test]
12419 async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12420 init_test(cx);
12421 let fs = FakeFs::new(cx.executor());
12422
12423 // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12424 {
12425 let project = Project::test(fs.clone(), [], cx).await;
12426 let (multi_workspace, cx) =
12427 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12428 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12429
12430 workspace.update(cx, |workspace, _cx| {
12431 workspace.set_random_database_id();
12432 workspace.bounds.size.width = px(800.);
12433 });
12434
12435 let panel = workspace.update_in(cx, |workspace, window, cx| {
12436 let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12437 workspace.add_panel(panel.clone(), window, cx);
12438 workspace.toggle_dock(DockPosition::Left, window, cx);
12439 panel
12440 });
12441
12442 workspace.update_in(cx, |workspace, window, cx| {
12443 workspace.resize_left_dock(px(350.), window, cx);
12444 });
12445
12446 cx.run_until_parked();
12447
12448 let persisted = workspace.read_with(cx, |workspace, cx| {
12449 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12450 });
12451 assert_eq!(
12452 persisted.and_then(|s| s.size),
12453 Some(px(350.)),
12454 "fixed-width panel size should be persisted to KVP"
12455 );
12456
12457 // Remove the panel and re-add a fresh instance with the same key.
12458 // The new instance should have its size state restored from KVP.
12459 workspace.update_in(cx, |workspace, window, cx| {
12460 workspace.remove_panel(&panel, window, cx);
12461 });
12462
12463 workspace.update_in(cx, |workspace, window, cx| {
12464 let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12465 workspace.add_panel(new_panel, window, cx);
12466
12467 let left_dock = workspace.left_dock().read(cx);
12468 let size_state = left_dock
12469 .panel::<TestPanel>()
12470 .and_then(|p| left_dock.stored_panel_size_state(&p));
12471 assert_eq!(
12472 size_state.and_then(|s| s.size),
12473 Some(px(350.)),
12474 "re-added fixed-width panel should restore persisted size from KVP"
12475 );
12476 });
12477 }
12478
12479 // Flexible panel: both pixel size and ratio are persisted and restored.
12480 {
12481 let project = Project::test(fs.clone(), [], cx).await;
12482 let (multi_workspace, cx) =
12483 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12484 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12485
12486 workspace.update(cx, |workspace, _cx| {
12487 workspace.set_random_database_id();
12488 workspace.bounds.size.width = px(800.);
12489 });
12490
12491 let panel = workspace.update_in(cx, |workspace, window, cx| {
12492 let item = cx.new(|cx| {
12493 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12494 });
12495 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12496
12497 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12498 workspace.add_panel(panel.clone(), window, cx);
12499 workspace.toggle_dock(DockPosition::Right, window, cx);
12500 panel
12501 });
12502
12503 workspace.update_in(cx, |workspace, window, cx| {
12504 workspace.resize_right_dock(px(300.), window, cx);
12505 });
12506
12507 cx.run_until_parked();
12508
12509 let persisted = workspace
12510 .read_with(cx, |workspace, cx| {
12511 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12512 })
12513 .expect("flexible panel state should be persisted to KVP");
12514 assert_eq!(
12515 persisted.size, None,
12516 "flexible panel should not persist a redundant pixel size"
12517 );
12518 let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12519
12520 // Remove the panel and re-add: both size and ratio should be restored.
12521 workspace.update_in(cx, |workspace, window, cx| {
12522 workspace.remove_panel(&panel, window, cx);
12523 });
12524
12525 workspace.update_in(cx, |workspace, window, cx| {
12526 let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12527 workspace.add_panel(new_panel, window, cx);
12528
12529 let right_dock = workspace.right_dock().read(cx);
12530 let size_state = right_dock
12531 .panel::<TestPanel>()
12532 .and_then(|p| right_dock.stored_panel_size_state(&p))
12533 .expect("re-added flexible panel should have restored size state from KVP");
12534 assert_eq!(
12535 size_state.size, None,
12536 "re-added flexible panel should not have a persisted pixel size"
12537 );
12538 assert_eq!(
12539 size_state.flex,
12540 Some(original_ratio),
12541 "re-added flexible panel should restore persisted flex"
12542 );
12543 });
12544 }
12545 }
12546
12547 #[gpui::test]
12548 async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12549 init_test(cx);
12550 let fs = FakeFs::new(cx.executor());
12551
12552 let project = Project::test(fs, [], cx).await;
12553 let (multi_workspace, cx) =
12554 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12555 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12556
12557 workspace.update(cx, |workspace, _cx| {
12558 workspace.bounds.size.width = px(900.);
12559 });
12560
12561 // Step 1: Add a tab to the center pane then open a flexible panel in the left
12562 // dock. With one full-width center pane the default ratio is 0.5, so the panel
12563 // and the center pane each take half the workspace width.
12564 workspace.update_in(cx, |workspace, window, cx| {
12565 let item = cx.new(|cx| {
12566 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12567 });
12568 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12569
12570 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12571 workspace.add_panel(panel, window, cx);
12572 workspace.toggle_dock(DockPosition::Left, window, cx);
12573
12574 let left_dock = workspace.left_dock().read(cx);
12575 let left_width = workspace
12576 .dock_size(&left_dock, window, cx)
12577 .expect("left dock should have an active panel");
12578
12579 assert_eq!(
12580 left_width,
12581 workspace.bounds.size.width / 2.,
12582 "flexible left panel should split evenly with the center pane"
12583 );
12584 });
12585
12586 // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12587 // change horizontal width fractions, so the flexible panel stays at the same
12588 // width as each half of the split.
12589 workspace.update_in(cx, |workspace, window, cx| {
12590 workspace.split_pane(
12591 workspace.active_pane().clone(),
12592 SplitDirection::Down,
12593 window,
12594 cx,
12595 );
12596
12597 let left_dock = workspace.left_dock().read(cx);
12598 let left_width = workspace
12599 .dock_size(&left_dock, window, cx)
12600 .expect("left dock should still have an active panel after vertical split");
12601
12602 assert_eq!(
12603 left_width,
12604 workspace.bounds.size.width / 2.,
12605 "flexible left panel width should match each vertically-split pane"
12606 );
12607 });
12608
12609 // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12610 // size reduces the available width, so the flexible left panel and the center
12611 // panes all shrink proportionally to accommodate it.
12612 workspace.update_in(cx, |workspace, window, cx| {
12613 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12614 workspace.add_panel(panel, window, cx);
12615 workspace.toggle_dock(DockPosition::Right, window, cx);
12616
12617 let right_dock = workspace.right_dock().read(cx);
12618 let right_width = workspace
12619 .dock_size(&right_dock, window, cx)
12620 .expect("right dock should have an active panel");
12621
12622 let left_dock = workspace.left_dock().read(cx);
12623 let left_width = workspace
12624 .dock_size(&left_dock, window, cx)
12625 .expect("left dock should still have an active panel");
12626
12627 let available_width = workspace.bounds.size.width - right_width;
12628 assert_eq!(
12629 left_width,
12630 available_width / 2.,
12631 "flexible left panel should shrink proportionally as the right dock takes space"
12632 );
12633 });
12634
12635 // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12636 // flex sizing and the workspace width is divided among left-flex, center
12637 // (implicit flex 1.0), and right-flex.
12638 workspace.update_in(cx, |workspace, window, cx| {
12639 let right_dock = workspace.right_dock().clone();
12640 let right_panel = right_dock
12641 .read(cx)
12642 .visible_panel()
12643 .expect("right dock should have a visible panel")
12644 .clone();
12645 workspace.toggle_dock_panel_flexible_size(
12646 &right_dock,
12647 right_panel.as_ref(),
12648 window,
12649 cx,
12650 );
12651
12652 let right_dock = right_dock.read(cx);
12653 let right_panel = right_dock
12654 .visible_panel()
12655 .expect("right dock should still have a visible panel");
12656 assert!(
12657 right_panel.has_flexible_size(window, cx),
12658 "right panel should now be flexible"
12659 );
12660
12661 let right_size_state = right_dock
12662 .stored_panel_size_state(right_panel.as_ref())
12663 .expect("right panel should have a stored size state after toggling");
12664 let right_flex = right_size_state
12665 .flex
12666 .expect("right panel should have a flex value after toggling");
12667
12668 let left_dock = workspace.left_dock().read(cx);
12669 let left_width = workspace
12670 .dock_size(&left_dock, window, cx)
12671 .expect("left dock should still have an active panel");
12672 let right_width = workspace
12673 .dock_size(&right_dock, window, cx)
12674 .expect("right dock should still have an active panel");
12675
12676 let left_flex = workspace
12677 .default_dock_flex(DockPosition::Left)
12678 .expect("left dock should have a default flex");
12679
12680 let total_flex = left_flex + 1.0 + right_flex;
12681 let expected_left = left_flex / total_flex * workspace.bounds.size.width;
12682 let expected_right = right_flex / total_flex * workspace.bounds.size.width;
12683 assert_eq!(
12684 left_width, expected_left,
12685 "flexible left panel should share workspace width via flex ratios"
12686 );
12687 assert_eq!(
12688 right_width, expected_right,
12689 "flexible right panel should share workspace width via flex ratios"
12690 );
12691 });
12692 }
12693
12694 struct TestModal(FocusHandle);
12695
12696 impl TestModal {
12697 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12698 Self(cx.focus_handle())
12699 }
12700 }
12701
12702 impl EventEmitter<DismissEvent> for TestModal {}
12703
12704 impl Focusable for TestModal {
12705 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12706 self.0.clone()
12707 }
12708 }
12709
12710 impl ModalView for TestModal {}
12711
12712 impl Render for TestModal {
12713 fn render(
12714 &mut self,
12715 _window: &mut Window,
12716 _cx: &mut Context<TestModal>,
12717 ) -> impl IntoElement {
12718 div().track_focus(&self.0)
12719 }
12720 }
12721
12722 #[gpui::test]
12723 async fn test_panels(cx: &mut gpui::TestAppContext) {
12724 init_test(cx);
12725 let fs = FakeFs::new(cx.executor());
12726
12727 let project = Project::test(fs, [], cx).await;
12728 let (multi_workspace, cx) =
12729 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12730 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12731
12732 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12733 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12734 workspace.add_panel(panel_1.clone(), window, cx);
12735 workspace.toggle_dock(DockPosition::Left, window, cx);
12736 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12737 workspace.add_panel(panel_2.clone(), window, cx);
12738 workspace.toggle_dock(DockPosition::Right, window, cx);
12739
12740 let left_dock = workspace.left_dock();
12741 assert_eq!(
12742 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12743 panel_1.panel_id()
12744 );
12745 assert_eq!(
12746 workspace.dock_size(&left_dock.read(cx), window, cx),
12747 Some(px(300.))
12748 );
12749
12750 workspace.resize_left_dock(px(1337.), window, cx);
12751 assert_eq!(
12752 workspace
12753 .right_dock()
12754 .read(cx)
12755 .visible_panel()
12756 .unwrap()
12757 .panel_id(),
12758 panel_2.panel_id(),
12759 );
12760
12761 (panel_1, panel_2)
12762 });
12763
12764 // Move panel_1 to the right
12765 panel_1.update_in(cx, |panel_1, window, cx| {
12766 panel_1.set_position(DockPosition::Right, window, cx)
12767 });
12768
12769 workspace.update_in(cx, |workspace, window, cx| {
12770 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12771 // Since it was the only panel on the left, the left dock should now be closed.
12772 assert!(!workspace.left_dock().read(cx).is_open());
12773 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12774 let right_dock = workspace.right_dock();
12775 assert_eq!(
12776 right_dock.read(cx).visible_panel().unwrap().panel_id(),
12777 panel_1.panel_id()
12778 );
12779 assert_eq!(
12780 right_dock
12781 .read(cx)
12782 .active_panel_size()
12783 .unwrap()
12784 .size
12785 .unwrap(),
12786 px(1337.)
12787 );
12788
12789 // Now we move panel_2 to the left
12790 panel_2.set_position(DockPosition::Left, window, cx);
12791 });
12792
12793 workspace.update(cx, |workspace, cx| {
12794 // Since panel_2 was not visible on the right, we don't open the left dock.
12795 assert!(!workspace.left_dock().read(cx).is_open());
12796 // And the right dock is unaffected in its displaying of panel_1
12797 assert!(workspace.right_dock().read(cx).is_open());
12798 assert_eq!(
12799 workspace
12800 .right_dock()
12801 .read(cx)
12802 .visible_panel()
12803 .unwrap()
12804 .panel_id(),
12805 panel_1.panel_id(),
12806 );
12807 });
12808
12809 // Move panel_1 back to the left
12810 panel_1.update_in(cx, |panel_1, window, cx| {
12811 panel_1.set_position(DockPosition::Left, window, cx)
12812 });
12813
12814 workspace.update_in(cx, |workspace, window, cx| {
12815 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12816 let left_dock = workspace.left_dock();
12817 assert!(left_dock.read(cx).is_open());
12818 assert_eq!(
12819 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12820 panel_1.panel_id()
12821 );
12822 assert_eq!(
12823 workspace.dock_size(&left_dock.read(cx), window, cx),
12824 Some(px(1337.))
12825 );
12826 // And the right dock should be closed as it no longer has any panels.
12827 assert!(!workspace.right_dock().read(cx).is_open());
12828
12829 // Now we move panel_1 to the bottom
12830 panel_1.set_position(DockPosition::Bottom, window, cx);
12831 });
12832
12833 workspace.update_in(cx, |workspace, window, cx| {
12834 // Since panel_1 was visible on the left, we close the left dock.
12835 assert!(!workspace.left_dock().read(cx).is_open());
12836 // The bottom dock is sized based on the panel's default size,
12837 // since the panel orientation changed from vertical to horizontal.
12838 let bottom_dock = workspace.bottom_dock();
12839 assert_eq!(
12840 workspace.dock_size(&bottom_dock.read(cx), window, cx),
12841 Some(px(300.))
12842 );
12843 // Close bottom dock and move panel_1 back to the left.
12844 bottom_dock.update(cx, |bottom_dock, cx| {
12845 bottom_dock.set_open(false, window, cx)
12846 });
12847 panel_1.set_position(DockPosition::Left, window, cx);
12848 });
12849
12850 // Emit activated event on panel 1
12851 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12852
12853 // Now the left dock is open and panel_1 is active and focused.
12854 workspace.update_in(cx, |workspace, window, cx| {
12855 let left_dock = workspace.left_dock();
12856 assert!(left_dock.read(cx).is_open());
12857 assert_eq!(
12858 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12859 panel_1.panel_id(),
12860 );
12861 assert!(panel_1.focus_handle(cx).is_focused(window));
12862 });
12863
12864 // Emit closed event on panel 2, which is not active
12865 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12866
12867 // Wo don't close the left dock, because panel_2 wasn't the active panel
12868 workspace.update(cx, |workspace, cx| {
12869 let left_dock = workspace.left_dock();
12870 assert!(left_dock.read(cx).is_open());
12871 assert_eq!(
12872 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12873 panel_1.panel_id(),
12874 );
12875 });
12876
12877 // Emitting a ZoomIn event shows the panel as zoomed.
12878 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12879 workspace.read_with(cx, |workspace, _| {
12880 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12881 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12882 });
12883
12884 // Move panel to another dock while it is zoomed
12885 panel_1.update_in(cx, |panel, window, cx| {
12886 panel.set_position(DockPosition::Right, window, cx)
12887 });
12888 workspace.read_with(cx, |workspace, _| {
12889 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12890
12891 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12892 });
12893
12894 // This is a helper for getting a:
12895 // - valid focus on an element,
12896 // - that isn't a part of the panes and panels system of the Workspace,
12897 // - and doesn't trigger the 'on_focus_lost' API.
12898 let focus_other_view = {
12899 let workspace = workspace.clone();
12900 move |cx: &mut VisualTestContext| {
12901 workspace.update_in(cx, |workspace, window, cx| {
12902 if workspace.active_modal::<TestModal>(cx).is_some() {
12903 workspace.toggle_modal(window, cx, TestModal::new);
12904 workspace.toggle_modal(window, cx, TestModal::new);
12905 } else {
12906 workspace.toggle_modal(window, cx, TestModal::new);
12907 }
12908 })
12909 }
12910 };
12911
12912 // If focus is transferred to another view that's not a panel or another pane, we still show
12913 // the panel as zoomed.
12914 focus_other_view(cx);
12915 workspace.read_with(cx, |workspace, _| {
12916 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12917 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12918 });
12919
12920 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12921 workspace.update_in(cx, |_workspace, window, cx| {
12922 cx.focus_self(window);
12923 });
12924 workspace.read_with(cx, |workspace, _| {
12925 assert_eq!(workspace.zoomed, None);
12926 assert_eq!(workspace.zoomed_position, None);
12927 });
12928
12929 // If focus is transferred again to another view that's not a panel or a pane, we won't
12930 // show the panel as zoomed because it wasn't zoomed before.
12931 focus_other_view(cx);
12932 workspace.read_with(cx, |workspace, _| {
12933 assert_eq!(workspace.zoomed, None);
12934 assert_eq!(workspace.zoomed_position, None);
12935 });
12936
12937 // When the panel is activated, it is zoomed again.
12938 cx.dispatch_action(ToggleRightDock);
12939 workspace.read_with(cx, |workspace, _| {
12940 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12941 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12942 });
12943
12944 // Emitting a ZoomOut event unzooms the panel.
12945 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12946 workspace.read_with(cx, |workspace, _| {
12947 assert_eq!(workspace.zoomed, None);
12948 assert_eq!(workspace.zoomed_position, None);
12949 });
12950
12951 // Emit closed event on panel 1, which is active
12952 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12953
12954 // Now the left dock is closed, because panel_1 was the active panel
12955 workspace.update(cx, |workspace, cx| {
12956 let right_dock = workspace.right_dock();
12957 assert!(!right_dock.read(cx).is_open());
12958 });
12959 }
12960
12961 #[gpui::test]
12962 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12963 init_test(cx);
12964
12965 let fs = FakeFs::new(cx.background_executor.clone());
12966 let project = Project::test(fs, [], cx).await;
12967 let (workspace, cx) =
12968 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12969 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12970
12971 let dirty_regular_buffer = cx.new(|cx| {
12972 TestItem::new(cx)
12973 .with_dirty(true)
12974 .with_label("1.txt")
12975 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12976 });
12977 let dirty_regular_buffer_2 = cx.new(|cx| {
12978 TestItem::new(cx)
12979 .with_dirty(true)
12980 .with_label("2.txt")
12981 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12982 });
12983 let dirty_multi_buffer_with_both = cx.new(|cx| {
12984 TestItem::new(cx)
12985 .with_dirty(true)
12986 .with_buffer_kind(ItemBufferKind::Multibuffer)
12987 .with_label("Fake Project Search")
12988 .with_project_items(&[
12989 dirty_regular_buffer.read(cx).project_items[0].clone(),
12990 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12991 ])
12992 });
12993 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12994 workspace.update_in(cx, |workspace, window, cx| {
12995 workspace.add_item(
12996 pane.clone(),
12997 Box::new(dirty_regular_buffer.clone()),
12998 None,
12999 false,
13000 false,
13001 window,
13002 cx,
13003 );
13004 workspace.add_item(
13005 pane.clone(),
13006 Box::new(dirty_regular_buffer_2.clone()),
13007 None,
13008 false,
13009 false,
13010 window,
13011 cx,
13012 );
13013 workspace.add_item(
13014 pane.clone(),
13015 Box::new(dirty_multi_buffer_with_both.clone()),
13016 None,
13017 false,
13018 false,
13019 window,
13020 cx,
13021 );
13022 });
13023
13024 pane.update_in(cx, |pane, window, cx| {
13025 pane.activate_item(2, true, true, window, cx);
13026 assert_eq!(
13027 pane.active_item().unwrap().item_id(),
13028 multi_buffer_with_both_files_id,
13029 "Should select the multi buffer in the pane"
13030 );
13031 });
13032 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13033 pane.close_other_items(
13034 &CloseOtherItems {
13035 save_intent: Some(SaveIntent::Save),
13036 close_pinned: true,
13037 },
13038 None,
13039 window,
13040 cx,
13041 )
13042 });
13043 cx.background_executor.run_until_parked();
13044 assert!(!cx.has_pending_prompt());
13045 close_all_but_multi_buffer_task
13046 .await
13047 .expect("Closing all buffers but the multi buffer failed");
13048 pane.update(cx, |pane, cx| {
13049 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13050 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13051 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13052 assert_eq!(pane.items_len(), 1);
13053 assert_eq!(
13054 pane.active_item().unwrap().item_id(),
13055 multi_buffer_with_both_files_id,
13056 "Should have only the multi buffer left in the pane"
13057 );
13058 assert!(
13059 dirty_multi_buffer_with_both.read(cx).is_dirty,
13060 "The multi buffer containing the unsaved buffer should still be dirty"
13061 );
13062 });
13063
13064 dirty_regular_buffer.update(cx, |buffer, cx| {
13065 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13066 });
13067
13068 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13069 pane.close_active_item(
13070 &CloseActiveItem {
13071 save_intent: Some(SaveIntent::Close),
13072 close_pinned: false,
13073 },
13074 window,
13075 cx,
13076 )
13077 });
13078 cx.background_executor.run_until_parked();
13079 assert!(
13080 cx.has_pending_prompt(),
13081 "Dirty multi buffer should prompt a save dialog"
13082 );
13083 cx.simulate_prompt_answer("Save");
13084 cx.background_executor.run_until_parked();
13085 close_multi_buffer_task
13086 .await
13087 .expect("Closing the multi buffer failed");
13088 pane.update(cx, |pane, cx| {
13089 assert_eq!(
13090 dirty_multi_buffer_with_both.read(cx).save_count,
13091 1,
13092 "Multi buffer item should get be saved"
13093 );
13094 // Test impl does not save inner items, so we do not assert them
13095 assert_eq!(
13096 pane.items_len(),
13097 0,
13098 "No more items should be left in the pane"
13099 );
13100 assert!(pane.active_item().is_none());
13101 });
13102 }
13103
13104 #[gpui::test]
13105 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13106 cx: &mut TestAppContext,
13107 ) {
13108 init_test(cx);
13109
13110 let fs = FakeFs::new(cx.background_executor.clone());
13111 let project = Project::test(fs, [], cx).await;
13112 let (workspace, cx) =
13113 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13114 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13115
13116 let dirty_regular_buffer = cx.new(|cx| {
13117 TestItem::new(cx)
13118 .with_dirty(true)
13119 .with_label("1.txt")
13120 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13121 });
13122 let dirty_regular_buffer_2 = cx.new(|cx| {
13123 TestItem::new(cx)
13124 .with_dirty(true)
13125 .with_label("2.txt")
13126 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13127 });
13128 let clear_regular_buffer = cx.new(|cx| {
13129 TestItem::new(cx)
13130 .with_label("3.txt")
13131 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13132 });
13133
13134 let dirty_multi_buffer_with_both = cx.new(|cx| {
13135 TestItem::new(cx)
13136 .with_dirty(true)
13137 .with_buffer_kind(ItemBufferKind::Multibuffer)
13138 .with_label("Fake Project Search")
13139 .with_project_items(&[
13140 dirty_regular_buffer.read(cx).project_items[0].clone(),
13141 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13142 clear_regular_buffer.read(cx).project_items[0].clone(),
13143 ])
13144 });
13145 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13146 workspace.update_in(cx, |workspace, window, cx| {
13147 workspace.add_item(
13148 pane.clone(),
13149 Box::new(dirty_regular_buffer.clone()),
13150 None,
13151 false,
13152 false,
13153 window,
13154 cx,
13155 );
13156 workspace.add_item(
13157 pane.clone(),
13158 Box::new(dirty_multi_buffer_with_both.clone()),
13159 None,
13160 false,
13161 false,
13162 window,
13163 cx,
13164 );
13165 });
13166
13167 pane.update_in(cx, |pane, window, cx| {
13168 pane.activate_item(1, true, true, window, cx);
13169 assert_eq!(
13170 pane.active_item().unwrap().item_id(),
13171 multi_buffer_with_both_files_id,
13172 "Should select the multi buffer in the pane"
13173 );
13174 });
13175 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13176 pane.close_active_item(
13177 &CloseActiveItem {
13178 save_intent: None,
13179 close_pinned: false,
13180 },
13181 window,
13182 cx,
13183 )
13184 });
13185 cx.background_executor.run_until_parked();
13186 assert!(
13187 cx.has_pending_prompt(),
13188 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13189 );
13190 }
13191
13192 /// Tests that when `close_on_file_delete` is enabled, files are automatically
13193 /// closed when they are deleted from disk.
13194 #[gpui::test]
13195 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13196 init_test(cx);
13197
13198 // Enable the close_on_disk_deletion setting
13199 cx.update_global(|store: &mut SettingsStore, cx| {
13200 store.update_user_settings(cx, |settings| {
13201 settings.workspace.close_on_file_delete = Some(true);
13202 });
13203 });
13204
13205 let fs = FakeFs::new(cx.background_executor.clone());
13206 let project = Project::test(fs, [], cx).await;
13207 let (workspace, cx) =
13208 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13209 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13210
13211 // Create a test item that simulates a file
13212 let item = cx.new(|cx| {
13213 TestItem::new(cx)
13214 .with_label("test.txt")
13215 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13216 });
13217
13218 // Add item to workspace
13219 workspace.update_in(cx, |workspace, window, cx| {
13220 workspace.add_item(
13221 pane.clone(),
13222 Box::new(item.clone()),
13223 None,
13224 false,
13225 false,
13226 window,
13227 cx,
13228 );
13229 });
13230
13231 // Verify the item is in the pane
13232 pane.read_with(cx, |pane, _| {
13233 assert_eq!(pane.items().count(), 1);
13234 });
13235
13236 // Simulate file deletion by setting the item's deleted state
13237 item.update(cx, |item, _| {
13238 item.set_has_deleted_file(true);
13239 });
13240
13241 // Emit UpdateTab event to trigger the close behavior
13242 cx.run_until_parked();
13243 item.update(cx, |_, cx| {
13244 cx.emit(ItemEvent::UpdateTab);
13245 });
13246
13247 // Allow the close operation to complete
13248 cx.run_until_parked();
13249
13250 // Verify the item was automatically closed
13251 pane.read_with(cx, |pane, _| {
13252 assert_eq!(
13253 pane.items().count(),
13254 0,
13255 "Item should be automatically closed when file is deleted"
13256 );
13257 });
13258 }
13259
13260 /// Tests that when `close_on_file_delete` is disabled (default), files remain
13261 /// open with a strikethrough when they are deleted from disk.
13262 #[gpui::test]
13263 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13264 init_test(cx);
13265
13266 // Ensure close_on_disk_deletion is disabled (default)
13267 cx.update_global(|store: &mut SettingsStore, cx| {
13268 store.update_user_settings(cx, |settings| {
13269 settings.workspace.close_on_file_delete = Some(false);
13270 });
13271 });
13272
13273 let fs = FakeFs::new(cx.background_executor.clone());
13274 let project = Project::test(fs, [], cx).await;
13275 let (workspace, cx) =
13276 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13277 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13278
13279 // Create a test item that simulates a file
13280 let item = cx.new(|cx| {
13281 TestItem::new(cx)
13282 .with_label("test.txt")
13283 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13284 });
13285
13286 // Add item to workspace
13287 workspace.update_in(cx, |workspace, window, cx| {
13288 workspace.add_item(
13289 pane.clone(),
13290 Box::new(item.clone()),
13291 None,
13292 false,
13293 false,
13294 window,
13295 cx,
13296 );
13297 });
13298
13299 // Verify the item is in the pane
13300 pane.read_with(cx, |pane, _| {
13301 assert_eq!(pane.items().count(), 1);
13302 });
13303
13304 // Simulate file deletion
13305 item.update(cx, |item, _| {
13306 item.set_has_deleted_file(true);
13307 });
13308
13309 // Emit UpdateTab event
13310 cx.run_until_parked();
13311 item.update(cx, |_, cx| {
13312 cx.emit(ItemEvent::UpdateTab);
13313 });
13314
13315 // Allow any potential close operation to complete
13316 cx.run_until_parked();
13317
13318 // Verify the item remains open (with strikethrough)
13319 pane.read_with(cx, |pane, _| {
13320 assert_eq!(
13321 pane.items().count(),
13322 1,
13323 "Item should remain open when close_on_disk_deletion is disabled"
13324 );
13325 });
13326
13327 // Verify the item shows as deleted
13328 item.read_with(cx, |item, _| {
13329 assert!(
13330 item.has_deleted_file,
13331 "Item should be marked as having deleted file"
13332 );
13333 });
13334 }
13335
13336 /// Tests that dirty files are not automatically closed when deleted from disk,
13337 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13338 /// unsaved changes without being prompted.
13339 #[gpui::test]
13340 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13341 init_test(cx);
13342
13343 // Enable the close_on_file_delete setting
13344 cx.update_global(|store: &mut SettingsStore, cx| {
13345 store.update_user_settings(cx, |settings| {
13346 settings.workspace.close_on_file_delete = Some(true);
13347 });
13348 });
13349
13350 let fs = FakeFs::new(cx.background_executor.clone());
13351 let project = Project::test(fs, [], cx).await;
13352 let (workspace, cx) =
13353 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13354 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13355
13356 // Create a dirty test item
13357 let item = cx.new(|cx| {
13358 TestItem::new(cx)
13359 .with_dirty(true)
13360 .with_label("test.txt")
13361 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13362 });
13363
13364 // Add item to workspace
13365 workspace.update_in(cx, |workspace, window, cx| {
13366 workspace.add_item(
13367 pane.clone(),
13368 Box::new(item.clone()),
13369 None,
13370 false,
13371 false,
13372 window,
13373 cx,
13374 );
13375 });
13376
13377 // Simulate file deletion
13378 item.update(cx, |item, _| {
13379 item.set_has_deleted_file(true);
13380 });
13381
13382 // Emit UpdateTab event to trigger the close behavior
13383 cx.run_until_parked();
13384 item.update(cx, |_, cx| {
13385 cx.emit(ItemEvent::UpdateTab);
13386 });
13387
13388 // Allow any potential close operation to complete
13389 cx.run_until_parked();
13390
13391 // Verify the item remains open (dirty files are not auto-closed)
13392 pane.read_with(cx, |pane, _| {
13393 assert_eq!(
13394 pane.items().count(),
13395 1,
13396 "Dirty items should not be automatically closed even when file is deleted"
13397 );
13398 });
13399
13400 // Verify the item is marked as deleted and still dirty
13401 item.read_with(cx, |item, _| {
13402 assert!(
13403 item.has_deleted_file,
13404 "Item should be marked as having deleted file"
13405 );
13406 assert!(item.is_dirty, "Item should still be dirty");
13407 });
13408 }
13409
13410 /// Tests that navigation history is cleaned up when files are auto-closed
13411 /// due to deletion from disk.
13412 #[gpui::test]
13413 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13414 init_test(cx);
13415
13416 // Enable the close_on_file_delete setting
13417 cx.update_global(|store: &mut SettingsStore, cx| {
13418 store.update_user_settings(cx, |settings| {
13419 settings.workspace.close_on_file_delete = Some(true);
13420 });
13421 });
13422
13423 let fs = FakeFs::new(cx.background_executor.clone());
13424 let project = Project::test(fs, [], cx).await;
13425 let (workspace, cx) =
13426 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13427 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13428
13429 // Create test items
13430 let item1 = cx.new(|cx| {
13431 TestItem::new(cx)
13432 .with_label("test1.txt")
13433 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13434 });
13435 let item1_id = item1.item_id();
13436
13437 let item2 = cx.new(|cx| {
13438 TestItem::new(cx)
13439 .with_label("test2.txt")
13440 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13441 });
13442
13443 // Add items to workspace
13444 workspace.update_in(cx, |workspace, window, cx| {
13445 workspace.add_item(
13446 pane.clone(),
13447 Box::new(item1.clone()),
13448 None,
13449 false,
13450 false,
13451 window,
13452 cx,
13453 );
13454 workspace.add_item(
13455 pane.clone(),
13456 Box::new(item2.clone()),
13457 None,
13458 false,
13459 false,
13460 window,
13461 cx,
13462 );
13463 });
13464
13465 // Activate item1 to ensure it gets navigation entries
13466 pane.update_in(cx, |pane, window, cx| {
13467 pane.activate_item(0, true, true, window, cx);
13468 });
13469
13470 // Switch to item2 and back to create navigation history
13471 pane.update_in(cx, |pane, window, cx| {
13472 pane.activate_item(1, true, true, window, cx);
13473 });
13474 cx.run_until_parked();
13475
13476 pane.update_in(cx, |pane, window, cx| {
13477 pane.activate_item(0, true, true, window, cx);
13478 });
13479 cx.run_until_parked();
13480
13481 // Simulate file deletion for item1
13482 item1.update(cx, |item, _| {
13483 item.set_has_deleted_file(true);
13484 });
13485
13486 // Emit UpdateTab event to trigger the close behavior
13487 item1.update(cx, |_, cx| {
13488 cx.emit(ItemEvent::UpdateTab);
13489 });
13490 cx.run_until_parked();
13491
13492 // Verify item1 was closed
13493 pane.read_with(cx, |pane, _| {
13494 assert_eq!(
13495 pane.items().count(),
13496 1,
13497 "Should have 1 item remaining after auto-close"
13498 );
13499 });
13500
13501 // Check navigation history after close
13502 let has_item = pane.read_with(cx, |pane, cx| {
13503 let mut has_item = false;
13504 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13505 if entry.item.id() == item1_id {
13506 has_item = true;
13507 }
13508 });
13509 has_item
13510 });
13511
13512 assert!(
13513 !has_item,
13514 "Navigation history should not contain closed item entries"
13515 );
13516 }
13517
13518 #[gpui::test]
13519 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13520 cx: &mut TestAppContext,
13521 ) {
13522 init_test(cx);
13523
13524 let fs = FakeFs::new(cx.background_executor.clone());
13525 let project = Project::test(fs, [], cx).await;
13526 let (workspace, cx) =
13527 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13528 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13529
13530 let dirty_regular_buffer = cx.new(|cx| {
13531 TestItem::new(cx)
13532 .with_dirty(true)
13533 .with_label("1.txt")
13534 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13535 });
13536 let dirty_regular_buffer_2 = cx.new(|cx| {
13537 TestItem::new(cx)
13538 .with_dirty(true)
13539 .with_label("2.txt")
13540 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13541 });
13542 let clear_regular_buffer = cx.new(|cx| {
13543 TestItem::new(cx)
13544 .with_label("3.txt")
13545 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13546 });
13547
13548 let dirty_multi_buffer = cx.new(|cx| {
13549 TestItem::new(cx)
13550 .with_dirty(true)
13551 .with_buffer_kind(ItemBufferKind::Multibuffer)
13552 .with_label("Fake Project Search")
13553 .with_project_items(&[
13554 dirty_regular_buffer.read(cx).project_items[0].clone(),
13555 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13556 clear_regular_buffer.read(cx).project_items[0].clone(),
13557 ])
13558 });
13559 workspace.update_in(cx, |workspace, window, cx| {
13560 workspace.add_item(
13561 pane.clone(),
13562 Box::new(dirty_regular_buffer.clone()),
13563 None,
13564 false,
13565 false,
13566 window,
13567 cx,
13568 );
13569 workspace.add_item(
13570 pane.clone(),
13571 Box::new(dirty_regular_buffer_2.clone()),
13572 None,
13573 false,
13574 false,
13575 window,
13576 cx,
13577 );
13578 workspace.add_item(
13579 pane.clone(),
13580 Box::new(dirty_multi_buffer.clone()),
13581 None,
13582 false,
13583 false,
13584 window,
13585 cx,
13586 );
13587 });
13588
13589 pane.update_in(cx, |pane, window, cx| {
13590 pane.activate_item(2, true, true, window, cx);
13591 assert_eq!(
13592 pane.active_item().unwrap().item_id(),
13593 dirty_multi_buffer.item_id(),
13594 "Should select the multi buffer in the pane"
13595 );
13596 });
13597 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13598 pane.close_active_item(
13599 &CloseActiveItem {
13600 save_intent: None,
13601 close_pinned: false,
13602 },
13603 window,
13604 cx,
13605 )
13606 });
13607 cx.background_executor.run_until_parked();
13608 assert!(
13609 !cx.has_pending_prompt(),
13610 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13611 );
13612 close_multi_buffer_task
13613 .await
13614 .expect("Closing multi buffer failed");
13615 pane.update(cx, |pane, cx| {
13616 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13617 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13618 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13619 assert_eq!(
13620 pane.items()
13621 .map(|item| item.item_id())
13622 .sorted()
13623 .collect::<Vec<_>>(),
13624 vec![
13625 dirty_regular_buffer.item_id(),
13626 dirty_regular_buffer_2.item_id(),
13627 ],
13628 "Should have no multi buffer left in the pane"
13629 );
13630 assert!(dirty_regular_buffer.read(cx).is_dirty);
13631 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13632 });
13633 }
13634
13635 #[gpui::test]
13636 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13637 init_test(cx);
13638 let fs = FakeFs::new(cx.executor());
13639 let project = Project::test(fs, [], cx).await;
13640 let (multi_workspace, cx) =
13641 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13642 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13643
13644 // Add a new panel to the right dock, opening the dock and setting the
13645 // focus to the new panel.
13646 let panel = workspace.update_in(cx, |workspace, window, cx| {
13647 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13648 workspace.add_panel(panel.clone(), window, cx);
13649
13650 workspace
13651 .right_dock()
13652 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13653
13654 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13655
13656 panel
13657 });
13658
13659 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13660 // panel to the next valid position which, in this case, is the left
13661 // dock.
13662 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13663 workspace.update(cx, |workspace, cx| {
13664 assert!(workspace.left_dock().read(cx).is_open());
13665 assert_eq!(panel.read(cx).position, DockPosition::Left);
13666 });
13667
13668 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13669 // panel to the next valid position which, in this case, is the bottom
13670 // dock.
13671 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13672 workspace.update(cx, |workspace, cx| {
13673 assert!(workspace.bottom_dock().read(cx).is_open());
13674 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13675 });
13676
13677 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13678 // around moving the panel to its initial position, the right dock.
13679 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13680 workspace.update(cx, |workspace, cx| {
13681 assert!(workspace.right_dock().read(cx).is_open());
13682 assert_eq!(panel.read(cx).position, DockPosition::Right);
13683 });
13684
13685 // Remove focus from the panel, ensuring that, if the panel is not
13686 // focused, the `MoveFocusedPanelToNextPosition` action does not update
13687 // the panel's position, so the panel is still in the right dock.
13688 workspace.update_in(cx, |workspace, window, cx| {
13689 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13690 });
13691
13692 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13693 workspace.update(cx, |workspace, cx| {
13694 assert!(workspace.right_dock().read(cx).is_open());
13695 assert_eq!(panel.read(cx).position, DockPosition::Right);
13696 });
13697 }
13698
13699 #[gpui::test]
13700 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13701 init_test(cx);
13702
13703 let fs = FakeFs::new(cx.executor());
13704 let project = Project::test(fs, [], cx).await;
13705 let (workspace, cx) =
13706 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13707
13708 let item_1 = cx.new(|cx| {
13709 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13710 });
13711 workspace.update_in(cx, |workspace, window, cx| {
13712 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13713 workspace.move_item_to_pane_in_direction(
13714 &MoveItemToPaneInDirection {
13715 direction: SplitDirection::Right,
13716 focus: true,
13717 clone: false,
13718 },
13719 window,
13720 cx,
13721 );
13722 workspace.move_item_to_pane_at_index(
13723 &MoveItemToPane {
13724 destination: 3,
13725 focus: true,
13726 clone: false,
13727 },
13728 window,
13729 cx,
13730 );
13731
13732 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13733 assert_eq!(
13734 pane_items_paths(&workspace.active_pane, cx),
13735 vec!["first.txt".to_string()],
13736 "Single item was not moved anywhere"
13737 );
13738 });
13739
13740 let item_2 = cx.new(|cx| {
13741 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13742 });
13743 workspace.update_in(cx, |workspace, window, cx| {
13744 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13745 assert_eq!(
13746 pane_items_paths(&workspace.panes[0], cx),
13747 vec!["first.txt".to_string(), "second.txt".to_string()],
13748 );
13749 workspace.move_item_to_pane_in_direction(
13750 &MoveItemToPaneInDirection {
13751 direction: SplitDirection::Right,
13752 focus: true,
13753 clone: false,
13754 },
13755 window,
13756 cx,
13757 );
13758
13759 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13760 assert_eq!(
13761 pane_items_paths(&workspace.panes[0], cx),
13762 vec!["first.txt".to_string()],
13763 "After moving, one item should be left in the original pane"
13764 );
13765 assert_eq!(
13766 pane_items_paths(&workspace.panes[1], cx),
13767 vec!["second.txt".to_string()],
13768 "New item should have been moved to the new pane"
13769 );
13770 });
13771
13772 let item_3 = cx.new(|cx| {
13773 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13774 });
13775 workspace.update_in(cx, |workspace, window, cx| {
13776 let original_pane = workspace.panes[0].clone();
13777 workspace.set_active_pane(&original_pane, window, cx);
13778 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13779 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13780 assert_eq!(
13781 pane_items_paths(&workspace.active_pane, cx),
13782 vec!["first.txt".to_string(), "third.txt".to_string()],
13783 "New pane should be ready to move one item out"
13784 );
13785
13786 workspace.move_item_to_pane_at_index(
13787 &MoveItemToPane {
13788 destination: 3,
13789 focus: true,
13790 clone: false,
13791 },
13792 window,
13793 cx,
13794 );
13795 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13796 assert_eq!(
13797 pane_items_paths(&workspace.active_pane, cx),
13798 vec!["first.txt".to_string()],
13799 "After moving, one item should be left in the original pane"
13800 );
13801 assert_eq!(
13802 pane_items_paths(&workspace.panes[1], cx),
13803 vec!["second.txt".to_string()],
13804 "Previously created pane should be unchanged"
13805 );
13806 assert_eq!(
13807 pane_items_paths(&workspace.panes[2], cx),
13808 vec!["third.txt".to_string()],
13809 "New item should have been moved to the new pane"
13810 );
13811 });
13812 }
13813
13814 #[gpui::test]
13815 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13816 init_test(cx);
13817
13818 let fs = FakeFs::new(cx.executor());
13819 let project = Project::test(fs, [], cx).await;
13820 let (workspace, cx) =
13821 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13822
13823 let item_1 = cx.new(|cx| {
13824 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13825 });
13826 workspace.update_in(cx, |workspace, window, cx| {
13827 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13828 workspace.move_item_to_pane_in_direction(
13829 &MoveItemToPaneInDirection {
13830 direction: SplitDirection::Right,
13831 focus: true,
13832 clone: true,
13833 },
13834 window,
13835 cx,
13836 );
13837 });
13838 cx.run_until_parked();
13839 workspace.update_in(cx, |workspace, window, cx| {
13840 workspace.move_item_to_pane_at_index(
13841 &MoveItemToPane {
13842 destination: 3,
13843 focus: true,
13844 clone: true,
13845 },
13846 window,
13847 cx,
13848 );
13849 });
13850 cx.run_until_parked();
13851
13852 workspace.update(cx, |workspace, cx| {
13853 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13854 for pane in workspace.panes() {
13855 assert_eq!(
13856 pane_items_paths(pane, cx),
13857 vec!["first.txt".to_string()],
13858 "Single item exists in all panes"
13859 );
13860 }
13861 });
13862
13863 // verify that the active pane has been updated after waiting for the
13864 // pane focus event to fire and resolve
13865 workspace.read_with(cx, |workspace, _app| {
13866 assert_eq!(
13867 workspace.active_pane(),
13868 &workspace.panes[2],
13869 "The third pane should be the active one: {:?}",
13870 workspace.panes
13871 );
13872 })
13873 }
13874
13875 #[gpui::test]
13876 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13877 init_test(cx);
13878
13879 let fs = FakeFs::new(cx.executor());
13880 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13881
13882 let project = Project::test(fs, ["root".as_ref()], cx).await;
13883 let (workspace, cx) =
13884 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13885
13886 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13887 // Add item to pane A with project path
13888 let item_a = cx.new(|cx| {
13889 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13890 });
13891 workspace.update_in(cx, |workspace, window, cx| {
13892 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13893 });
13894
13895 // Split to create pane B
13896 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13897 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13898 });
13899
13900 // Add item with SAME project path to pane B, and pin it
13901 let item_b = cx.new(|cx| {
13902 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13903 });
13904 pane_b.update_in(cx, |pane, window, cx| {
13905 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13906 pane.set_pinned_count(1);
13907 });
13908
13909 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13910 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13911
13912 // close_pinned: false should only close the unpinned copy
13913 workspace.update_in(cx, |workspace, window, cx| {
13914 workspace.close_item_in_all_panes(
13915 &CloseItemInAllPanes {
13916 save_intent: Some(SaveIntent::Close),
13917 close_pinned: false,
13918 },
13919 window,
13920 cx,
13921 )
13922 });
13923 cx.executor().run_until_parked();
13924
13925 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13926 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13927 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13928 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13929
13930 // Split again, seeing as closing the previous item also closed its
13931 // pane, so only pane remains, which does not allow us to properly test
13932 // that both items close when `close_pinned: true`.
13933 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13934 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13935 });
13936
13937 // Add an item with the same project path to pane C so that
13938 // close_item_in_all_panes can determine what to close across all panes
13939 // (it reads the active item from the active pane, and split_pane
13940 // creates an empty pane).
13941 let item_c = cx.new(|cx| {
13942 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13943 });
13944 pane_c.update_in(cx, |pane, window, cx| {
13945 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13946 });
13947
13948 // close_pinned: true should close the pinned copy too
13949 workspace.update_in(cx, |workspace, window, cx| {
13950 let panes_count = workspace.panes().len();
13951 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13952
13953 workspace.close_item_in_all_panes(
13954 &CloseItemInAllPanes {
13955 save_intent: Some(SaveIntent::Close),
13956 close_pinned: true,
13957 },
13958 window,
13959 cx,
13960 )
13961 });
13962 cx.executor().run_until_parked();
13963
13964 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13965 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13966 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13967 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13968 }
13969
13970 mod register_project_item_tests {
13971
13972 use super::*;
13973
13974 // View
13975 struct TestPngItemView {
13976 focus_handle: FocusHandle,
13977 }
13978 // Model
13979 struct TestPngItem {}
13980
13981 impl project::ProjectItem for TestPngItem {
13982 fn try_open(
13983 _project: &Entity<Project>,
13984 path: &ProjectPath,
13985 cx: &mut App,
13986 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13987 if path.path.extension().unwrap() == "png" {
13988 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13989 } else {
13990 None
13991 }
13992 }
13993
13994 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13995 None
13996 }
13997
13998 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13999 None
14000 }
14001
14002 fn is_dirty(&self) -> bool {
14003 false
14004 }
14005 }
14006
14007 impl Item for TestPngItemView {
14008 type Event = ();
14009 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14010 "".into()
14011 }
14012 }
14013 impl EventEmitter<()> for TestPngItemView {}
14014 impl Focusable for TestPngItemView {
14015 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14016 self.focus_handle.clone()
14017 }
14018 }
14019
14020 impl Render for TestPngItemView {
14021 fn render(
14022 &mut self,
14023 _window: &mut Window,
14024 _cx: &mut Context<Self>,
14025 ) -> impl IntoElement {
14026 Empty
14027 }
14028 }
14029
14030 impl ProjectItem for TestPngItemView {
14031 type Item = TestPngItem;
14032
14033 fn for_project_item(
14034 _project: Entity<Project>,
14035 _pane: Option<&Pane>,
14036 _item: Entity<Self::Item>,
14037 _: &mut Window,
14038 cx: &mut Context<Self>,
14039 ) -> Self
14040 where
14041 Self: Sized,
14042 {
14043 Self {
14044 focus_handle: cx.focus_handle(),
14045 }
14046 }
14047 }
14048
14049 // View
14050 struct TestIpynbItemView {
14051 focus_handle: FocusHandle,
14052 }
14053 // Model
14054 struct TestIpynbItem {}
14055
14056 impl project::ProjectItem for TestIpynbItem {
14057 fn try_open(
14058 _project: &Entity<Project>,
14059 path: &ProjectPath,
14060 cx: &mut App,
14061 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14062 if path.path.extension().unwrap() == "ipynb" {
14063 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14064 } else {
14065 None
14066 }
14067 }
14068
14069 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14070 None
14071 }
14072
14073 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14074 None
14075 }
14076
14077 fn is_dirty(&self) -> bool {
14078 false
14079 }
14080 }
14081
14082 impl Item for TestIpynbItemView {
14083 type Event = ();
14084 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14085 "".into()
14086 }
14087 }
14088 impl EventEmitter<()> for TestIpynbItemView {}
14089 impl Focusable for TestIpynbItemView {
14090 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14091 self.focus_handle.clone()
14092 }
14093 }
14094
14095 impl Render for TestIpynbItemView {
14096 fn render(
14097 &mut self,
14098 _window: &mut Window,
14099 _cx: &mut Context<Self>,
14100 ) -> impl IntoElement {
14101 Empty
14102 }
14103 }
14104
14105 impl ProjectItem for TestIpynbItemView {
14106 type Item = TestIpynbItem;
14107
14108 fn for_project_item(
14109 _project: Entity<Project>,
14110 _pane: Option<&Pane>,
14111 _item: Entity<Self::Item>,
14112 _: &mut Window,
14113 cx: &mut Context<Self>,
14114 ) -> Self
14115 where
14116 Self: Sized,
14117 {
14118 Self {
14119 focus_handle: cx.focus_handle(),
14120 }
14121 }
14122 }
14123
14124 struct TestAlternatePngItemView {
14125 focus_handle: FocusHandle,
14126 }
14127
14128 impl Item for TestAlternatePngItemView {
14129 type Event = ();
14130 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14131 "".into()
14132 }
14133 }
14134
14135 impl EventEmitter<()> for TestAlternatePngItemView {}
14136 impl Focusable for TestAlternatePngItemView {
14137 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14138 self.focus_handle.clone()
14139 }
14140 }
14141
14142 impl Render for TestAlternatePngItemView {
14143 fn render(
14144 &mut self,
14145 _window: &mut Window,
14146 _cx: &mut Context<Self>,
14147 ) -> impl IntoElement {
14148 Empty
14149 }
14150 }
14151
14152 impl ProjectItem for TestAlternatePngItemView {
14153 type Item = TestPngItem;
14154
14155 fn for_project_item(
14156 _project: Entity<Project>,
14157 _pane: Option<&Pane>,
14158 _item: Entity<Self::Item>,
14159 _: &mut Window,
14160 cx: &mut Context<Self>,
14161 ) -> Self
14162 where
14163 Self: Sized,
14164 {
14165 Self {
14166 focus_handle: cx.focus_handle(),
14167 }
14168 }
14169 }
14170
14171 #[gpui::test]
14172 async fn test_register_project_item(cx: &mut TestAppContext) {
14173 init_test(cx);
14174
14175 cx.update(|cx| {
14176 register_project_item::<TestPngItemView>(cx);
14177 register_project_item::<TestIpynbItemView>(cx);
14178 });
14179
14180 let fs = FakeFs::new(cx.executor());
14181 fs.insert_tree(
14182 "/root1",
14183 json!({
14184 "one.png": "BINARYDATAHERE",
14185 "two.ipynb": "{ totally a notebook }",
14186 "three.txt": "editing text, sure why not?"
14187 }),
14188 )
14189 .await;
14190
14191 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14192 let (workspace, cx) =
14193 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14194
14195 let worktree_id = project.update(cx, |project, cx| {
14196 project.worktrees(cx).next().unwrap().read(cx).id()
14197 });
14198
14199 let handle = workspace
14200 .update_in(cx, |workspace, window, cx| {
14201 let project_path = (worktree_id, rel_path("one.png"));
14202 workspace.open_path(project_path, None, true, window, cx)
14203 })
14204 .await
14205 .unwrap();
14206
14207 // Now we can check if the handle we got back errored or not
14208 assert_eq!(
14209 handle.to_any_view().entity_type(),
14210 TypeId::of::<TestPngItemView>()
14211 );
14212
14213 let handle = workspace
14214 .update_in(cx, |workspace, window, cx| {
14215 let project_path = (worktree_id, rel_path("two.ipynb"));
14216 workspace.open_path(project_path, None, true, window, cx)
14217 })
14218 .await
14219 .unwrap();
14220
14221 assert_eq!(
14222 handle.to_any_view().entity_type(),
14223 TypeId::of::<TestIpynbItemView>()
14224 );
14225
14226 let handle = workspace
14227 .update_in(cx, |workspace, window, cx| {
14228 let project_path = (worktree_id, rel_path("three.txt"));
14229 workspace.open_path(project_path, None, true, window, cx)
14230 })
14231 .await;
14232 assert!(handle.is_err());
14233 }
14234
14235 #[gpui::test]
14236 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14237 init_test(cx);
14238
14239 cx.update(|cx| {
14240 register_project_item::<TestPngItemView>(cx);
14241 register_project_item::<TestAlternatePngItemView>(cx);
14242 });
14243
14244 let fs = FakeFs::new(cx.executor());
14245 fs.insert_tree(
14246 "/root1",
14247 json!({
14248 "one.png": "BINARYDATAHERE",
14249 "two.ipynb": "{ totally a notebook }",
14250 "three.txt": "editing text, sure why not?"
14251 }),
14252 )
14253 .await;
14254 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14255 let (workspace, cx) =
14256 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14257 let worktree_id = project.update(cx, |project, cx| {
14258 project.worktrees(cx).next().unwrap().read(cx).id()
14259 });
14260
14261 let handle = workspace
14262 .update_in(cx, |workspace, window, cx| {
14263 let project_path = (worktree_id, rel_path("one.png"));
14264 workspace.open_path(project_path, None, true, window, cx)
14265 })
14266 .await
14267 .unwrap();
14268
14269 // This _must_ be the second item registered
14270 assert_eq!(
14271 handle.to_any_view().entity_type(),
14272 TypeId::of::<TestAlternatePngItemView>()
14273 );
14274
14275 let handle = workspace
14276 .update_in(cx, |workspace, window, cx| {
14277 let project_path = (worktree_id, rel_path("three.txt"));
14278 workspace.open_path(project_path, None, true, window, cx)
14279 })
14280 .await;
14281 assert!(handle.is_err());
14282 }
14283 }
14284
14285 #[gpui::test]
14286 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14287 init_test(cx);
14288
14289 let fs = FakeFs::new(cx.executor());
14290 let project = Project::test(fs, [], cx).await;
14291 let (workspace, _cx) =
14292 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14293
14294 // Test with status bar shown (default)
14295 workspace.read_with(cx, |workspace, cx| {
14296 let visible = workspace.status_bar_visible(cx);
14297 assert!(visible, "Status bar should be visible by default");
14298 });
14299
14300 // Test with status bar hidden
14301 cx.update_global(|store: &mut SettingsStore, cx| {
14302 store.update_user_settings(cx, |settings| {
14303 settings.status_bar.get_or_insert_default().show = Some(false);
14304 });
14305 });
14306
14307 workspace.read_with(cx, |workspace, cx| {
14308 let visible = workspace.status_bar_visible(cx);
14309 assert!(!visible, "Status bar should be hidden when show is false");
14310 });
14311
14312 // Test with status bar shown explicitly
14313 cx.update_global(|store: &mut SettingsStore, cx| {
14314 store.update_user_settings(cx, |settings| {
14315 settings.status_bar.get_or_insert_default().show = Some(true);
14316 });
14317 });
14318
14319 workspace.read_with(cx, |workspace, cx| {
14320 let visible = workspace.status_bar_visible(cx);
14321 assert!(visible, "Status bar should be visible when show is true");
14322 });
14323 }
14324
14325 #[gpui::test]
14326 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14327 init_test(cx);
14328
14329 let fs = FakeFs::new(cx.executor());
14330 let project = Project::test(fs, [], cx).await;
14331 let (multi_workspace, cx) =
14332 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14333 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14334 let panel = workspace.update_in(cx, |workspace, window, cx| {
14335 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14336 workspace.add_panel(panel.clone(), window, cx);
14337
14338 workspace
14339 .right_dock()
14340 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14341
14342 panel
14343 });
14344
14345 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14346 let item_a = cx.new(TestItem::new);
14347 let item_b = cx.new(TestItem::new);
14348 let item_a_id = item_a.entity_id();
14349 let item_b_id = item_b.entity_id();
14350
14351 pane.update_in(cx, |pane, window, cx| {
14352 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14353 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14354 });
14355
14356 pane.read_with(cx, |pane, _| {
14357 assert_eq!(pane.items_len(), 2);
14358 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14359 });
14360
14361 workspace.update_in(cx, |workspace, window, cx| {
14362 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14363 });
14364
14365 workspace.update_in(cx, |_, window, cx| {
14366 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14367 });
14368
14369 // Assert that the `pane::CloseActiveItem` action is handled at the
14370 // workspace level when one of the dock panels is focused and, in that
14371 // case, the center pane's active item is closed but the focus is not
14372 // moved.
14373 cx.dispatch_action(pane::CloseActiveItem::default());
14374 cx.run_until_parked();
14375
14376 pane.read_with(cx, |pane, _| {
14377 assert_eq!(pane.items_len(), 1);
14378 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14379 });
14380
14381 workspace.update_in(cx, |workspace, window, cx| {
14382 assert!(workspace.right_dock().read(cx).is_open());
14383 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14384 });
14385 }
14386
14387 #[gpui::test]
14388 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14389 init_test(cx);
14390 let fs = FakeFs::new(cx.executor());
14391
14392 let project_a = Project::test(fs.clone(), [], cx).await;
14393 let project_b = Project::test(fs, [], cx).await;
14394
14395 let multi_workspace_handle =
14396 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14397 cx.run_until_parked();
14398
14399 let workspace_a = multi_workspace_handle
14400 .read_with(cx, |mw, _| mw.workspace().clone())
14401 .unwrap();
14402
14403 let _workspace_b = multi_workspace_handle
14404 .update(cx, |mw, window, cx| {
14405 mw.test_add_workspace(project_b, window, cx)
14406 })
14407 .unwrap();
14408
14409 // Switch to workspace A
14410 multi_workspace_handle
14411 .update(cx, |mw, window, cx| {
14412 mw.activate_index(0, window, cx);
14413 })
14414 .unwrap();
14415
14416 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14417
14418 // Add a panel to workspace A's right dock and open the dock
14419 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14420 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14421 workspace.add_panel(panel.clone(), window, cx);
14422 workspace
14423 .right_dock()
14424 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14425 panel
14426 });
14427
14428 // Focus the panel through the workspace (matching existing test pattern)
14429 workspace_a.update_in(cx, |workspace, window, cx| {
14430 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14431 });
14432
14433 // Zoom the panel
14434 panel.update_in(cx, |panel, window, cx| {
14435 panel.set_zoomed(true, window, cx);
14436 });
14437
14438 // Verify the panel is zoomed and the dock is open
14439 workspace_a.update_in(cx, |workspace, window, cx| {
14440 assert!(
14441 workspace.right_dock().read(cx).is_open(),
14442 "dock should be open before switch"
14443 );
14444 assert!(
14445 panel.is_zoomed(window, cx),
14446 "panel should be zoomed before switch"
14447 );
14448 assert!(
14449 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14450 "panel should be focused before switch"
14451 );
14452 });
14453
14454 // Switch to workspace B
14455 multi_workspace_handle
14456 .update(cx, |mw, window, cx| {
14457 mw.activate_index(1, window, cx);
14458 })
14459 .unwrap();
14460 cx.run_until_parked();
14461
14462 // Switch back to workspace A
14463 multi_workspace_handle
14464 .update(cx, |mw, window, cx| {
14465 mw.activate_index(0, window, cx);
14466 })
14467 .unwrap();
14468 cx.run_until_parked();
14469
14470 // Verify the panel is still zoomed and the dock is still open
14471 workspace_a.update_in(cx, |workspace, window, cx| {
14472 assert!(
14473 workspace.right_dock().read(cx).is_open(),
14474 "dock should still be open after switching back"
14475 );
14476 assert!(
14477 panel.is_zoomed(window, cx),
14478 "panel should still be zoomed after switching back"
14479 );
14480 });
14481 }
14482
14483 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14484 pane.read(cx)
14485 .items()
14486 .flat_map(|item| {
14487 item.project_paths(cx)
14488 .into_iter()
14489 .map(|path| path.path.display(PathStyle::local()).into_owned())
14490 })
14491 .collect()
14492 }
14493
14494 pub fn init_test(cx: &mut TestAppContext) {
14495 cx.update(|cx| {
14496 let settings_store = SettingsStore::test(cx);
14497 cx.set_global(settings_store);
14498 cx.set_global(db::AppDatabase::test_new());
14499 theme::init(theme::LoadThemes::JustBase, cx);
14500 });
14501 }
14502
14503 #[gpui::test]
14504 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14505 use settings::{ThemeName, ThemeSelection};
14506 use theme::SystemAppearance;
14507 use zed_actions::theme::ToggleMode;
14508
14509 init_test(cx);
14510
14511 let fs = FakeFs::new(cx.executor());
14512 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14513
14514 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14515 .await;
14516
14517 // Build a test project and workspace view so the test can invoke
14518 // the workspace action handler the same way the UI would.
14519 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14520 let (workspace, cx) =
14521 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14522
14523 // Seed the settings file with a plain static light theme so the
14524 // first toggle always starts from a known persisted state.
14525 workspace.update_in(cx, |_workspace, _window, cx| {
14526 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14527 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14528 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14529 });
14530 });
14531 cx.executor().advance_clock(Duration::from_millis(200));
14532 cx.run_until_parked();
14533
14534 // Confirm the initial persisted settings contain the static theme
14535 // we just wrote before any toggling happens.
14536 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14537 assert!(settings_text.contains(r#""theme": "One Light""#));
14538
14539 // Toggle once. This should migrate the persisted theme settings
14540 // into light/dark slots and enable system mode.
14541 workspace.update_in(cx, |workspace, window, cx| {
14542 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14543 });
14544 cx.executor().advance_clock(Duration::from_millis(200));
14545 cx.run_until_parked();
14546
14547 // 1. Static -> Dynamic
14548 // this assertion checks theme changed from static to dynamic.
14549 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14550 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14551 assert_eq!(
14552 parsed["theme"],
14553 serde_json::json!({
14554 "mode": "system",
14555 "light": "One Light",
14556 "dark": "One Dark"
14557 })
14558 );
14559
14560 // 2. Toggle again, suppose it will change the mode to light
14561 workspace.update_in(cx, |workspace, window, cx| {
14562 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14563 });
14564 cx.executor().advance_clock(Duration::from_millis(200));
14565 cx.run_until_parked();
14566
14567 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14568 assert!(settings_text.contains(r#""mode": "light""#));
14569 }
14570
14571 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14572 let item = TestProjectItem::new(id, path, cx);
14573 item.update(cx, |item, _| {
14574 item.is_dirty = true;
14575 });
14576 item
14577 }
14578
14579 #[gpui::test]
14580 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14581 cx: &mut gpui::TestAppContext,
14582 ) {
14583 init_test(cx);
14584 let fs = FakeFs::new(cx.executor());
14585
14586 let project = Project::test(fs, [], cx).await;
14587 let (workspace, cx) =
14588 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14589
14590 let panel = workspace.update_in(cx, |workspace, window, cx| {
14591 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14592 workspace.add_panel(panel.clone(), window, cx);
14593 workspace
14594 .right_dock()
14595 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14596 panel
14597 });
14598
14599 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14600 pane.update_in(cx, |pane, window, cx| {
14601 let item = cx.new(TestItem::new);
14602 pane.add_item(Box::new(item), true, true, None, window, cx);
14603 });
14604
14605 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14606 // mirrors the real-world flow and avoids side effects from directly
14607 // focusing the panel while the center pane is active.
14608 workspace.update_in(cx, |workspace, window, cx| {
14609 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14610 });
14611
14612 panel.update_in(cx, |panel, window, cx| {
14613 panel.set_zoomed(true, window, cx);
14614 });
14615
14616 workspace.update_in(cx, |workspace, window, cx| {
14617 assert!(workspace.right_dock().read(cx).is_open());
14618 assert!(panel.is_zoomed(window, cx));
14619 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14620 });
14621
14622 // Simulate a spurious pane::Event::Focus on the center pane while the
14623 // panel still has focus. This mirrors what happens during macOS window
14624 // activation: the center pane fires a focus event even though actual
14625 // focus remains on the dock panel.
14626 pane.update_in(cx, |_, _, cx| {
14627 cx.emit(pane::Event::Focus);
14628 });
14629
14630 // The dock must remain open because the panel had focus at the time the
14631 // event was processed. Before the fix, dock_to_preserve was None for
14632 // panels that don't implement pane(), causing the dock to close.
14633 workspace.update_in(cx, |workspace, window, cx| {
14634 assert!(
14635 workspace.right_dock().read(cx).is_open(),
14636 "Dock should stay open when its zoomed panel (without pane()) still has focus"
14637 );
14638 assert!(panel.is_zoomed(window, cx));
14639 });
14640 }
14641
14642 #[gpui::test]
14643 async fn test_panels_stay_open_after_position_change_and_settings_update(
14644 cx: &mut gpui::TestAppContext,
14645 ) {
14646 init_test(cx);
14647 let fs = FakeFs::new(cx.executor());
14648 let project = Project::test(fs, [], cx).await;
14649 let (workspace, cx) =
14650 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14651
14652 // Add two panels to the left dock and open it.
14653 let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14654 let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14655 let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14656 workspace.add_panel(panel_a.clone(), window, cx);
14657 workspace.add_panel(panel_b.clone(), window, cx);
14658 workspace.left_dock().update(cx, |dock, cx| {
14659 dock.set_open(true, window, cx);
14660 dock.activate_panel(0, window, cx);
14661 });
14662 (panel_a, panel_b)
14663 });
14664
14665 workspace.update_in(cx, |workspace, _, cx| {
14666 assert!(workspace.left_dock().read(cx).is_open());
14667 });
14668
14669 // Simulate a feature flag changing default dock positions: both panels
14670 // move from Left to Right.
14671 workspace.update_in(cx, |_workspace, _window, cx| {
14672 panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14673 panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14674 cx.update_global::<SettingsStore, _>(|_, _| {});
14675 });
14676
14677 // Both panels should now be in the right dock.
14678 workspace.update_in(cx, |workspace, _, cx| {
14679 let right_dock = workspace.right_dock().read(cx);
14680 assert_eq!(right_dock.panels_len(), 2);
14681 });
14682
14683 // Open the right dock and activate panel_b (simulating the user
14684 // opening the panel after it moved).
14685 workspace.update_in(cx, |workspace, window, cx| {
14686 workspace.right_dock().update(cx, |dock, cx| {
14687 dock.set_open(true, window, cx);
14688 dock.activate_panel(1, window, cx);
14689 });
14690 });
14691
14692 // Now trigger another SettingsStore change
14693 workspace.update_in(cx, |_workspace, _window, cx| {
14694 cx.update_global::<SettingsStore, _>(|_, _| {});
14695 });
14696
14697 workspace.update_in(cx, |workspace, _, cx| {
14698 assert!(
14699 workspace.right_dock().read(cx).is_open(),
14700 "Right dock should still be open after a settings change"
14701 );
14702 assert_eq!(
14703 workspace.right_dock().read(cx).panels_len(),
14704 2,
14705 "Both panels should still be in the right dock"
14706 );
14707 });
14708 }
14709}