1pub mod dock;
2pub mod history_manager;
3pub mod invalid_item_view;
4pub mod item;
5mod modal_layer;
6mod multi_workspace;
7pub mod notifications;
8pub mod pane;
9pub mod pane_group;
10pub mod path_list {
11 pub use util::path_list::{PathList, SerializedPathList};
12}
13mod persistence;
14pub mod searchable;
15mod security_modal;
16pub mod shared_screen;
17use db::smol::future::yield_now;
18pub use shared_screen::SharedScreen;
19mod status_bar;
20pub mod tasks;
21mod theme_preview;
22mod toast_layer;
23mod toolbar;
24pub mod welcome;
25mod workspace_settings;
26
27pub use crate::notifications::NotificationFrame;
28pub use dock::Panel;
29pub use multi_workspace::{
30 DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace, MultiWorkspaceEvent,
31 NewWorkspaceInWindow, NextWorkspaceInWindow, PreviousWorkspaceInWindow,
32 SIDEBAR_RESIZE_HANDLE_SIZE, ToggleWorkspaceSidebar, multi_workspace_enabled,
33};
34pub use path_list::{PathList, SerializedPathList};
35pub use toast_layer::{ToastAction, ToastLayer, ToastView};
36
37use anyhow::{Context as _, Result, anyhow};
38use client::{
39 ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
40 proto::{self, ErrorCode, PanelId, PeerId},
41};
42use collections::{HashMap, HashSet, hash_map};
43use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
44use fs::Fs;
45use futures::{
46 Future, FutureExt, StreamExt,
47 channel::{
48 mpsc::{self, UnboundedReceiver, UnboundedSender},
49 oneshot,
50 },
51 future::{Shared, try_join_all},
52};
53use gpui::{
54 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
55 CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
56 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
57 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
58 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
59 WindowOptions, actions, canvas, point, relative, size, transparent_black,
60};
61pub use history_manager::*;
62pub use item::{
63 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
64 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
65};
66use itertools::Itertools;
67use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
68pub use modal_layer::*;
69use node_runtime::NodeRuntime;
70use notifications::{
71 DetachAndPromptErr, Notifications, dismiss_app_notification,
72 simple_message_notification::MessageNotification,
73};
74pub use pane::*;
75pub use pane_group::{
76 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
77 SplitDirection,
78};
79use persistence::{DB, SerializedWindowBounds, model::SerializedWorkspace};
80pub use persistence::{
81 DB as WORKSPACE_DB, WorkspaceDb, delete_unloaded_items,
82 model::{
83 DockStructure, ItemId, MultiWorkspaceId, SerializedMultiWorkspace,
84 SerializedWorkspaceLocation, SessionWorkspace,
85 },
86 read_serialized_multi_workspaces,
87};
88use postage::stream::Stream;
89use project::{
90 DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
91 WorktreeSettings,
92 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
93 project_settings::ProjectSettings,
94 toolchain_store::ToolchainStoreEvent,
95 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
96};
97use remote::{
98 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
99 remote_client::ConnectionIdentifier,
100};
101use schemars::JsonSchema;
102use serde::Deserialize;
103use session::AppSession;
104use settings::{
105 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
106};
107
108use sqlez::{
109 bindable::{Bind, Column, StaticColumnCount},
110 statement::Statement,
111};
112use status_bar::StatusBar;
113pub use status_bar::StatusItemView;
114use std::{
115 any::TypeId,
116 borrow::Cow,
117 cell::RefCell,
118 cmp,
119 collections::VecDeque,
120 env,
121 hash::Hash,
122 path::{Path, PathBuf},
123 process::ExitStatus,
124 rc::Rc,
125 sync::{
126 Arc, LazyLock, Weak,
127 atomic::{AtomicBool, AtomicUsize},
128 },
129 time::Duration,
130};
131use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
132use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
133pub use toolbar::{
134 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
135};
136pub use ui;
137use ui::{Window, prelude::*};
138use util::{
139 ResultExt, TryFutureExt,
140 paths::{PathStyle, SanitizedPath},
141 rel_path::RelPath,
142 serde::default_true,
143};
144use uuid::Uuid;
145pub use workspace_settings::{
146 AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
147 WorkspaceSettings,
148};
149use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
150
151use crate::{item::ItemBufferKind, notifications::NotificationId};
152use crate::{
153 persistence::{
154 SerializedAxis,
155 model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
156 },
157 security_modal::SecurityModal,
158};
159
160pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
161
162static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
163 env::var("ZED_WINDOW_SIZE")
164 .ok()
165 .as_deref()
166 .and_then(parse_pixel_size_env_var)
167});
168
169static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
170 env::var("ZED_WINDOW_POSITION")
171 .ok()
172 .as_deref()
173 .and_then(parse_pixel_position_env_var)
174});
175
176pub trait TerminalProvider {
177 fn spawn(
178 &self,
179 task: SpawnInTerminal,
180 window: &mut Window,
181 cx: &mut App,
182 ) -> Task<Option<Result<ExitStatus>>>;
183}
184
185pub trait DebuggerProvider {
186 // `active_buffer` is used to resolve build task's name against language-specific tasks.
187 fn start_session(
188 &self,
189 definition: DebugScenario,
190 task_context: SharedTaskContext,
191 active_buffer: Option<Entity<Buffer>>,
192 worktree_id: Option<WorktreeId>,
193 window: &mut Window,
194 cx: &mut App,
195 );
196
197 fn spawn_task_or_modal(
198 &self,
199 workspace: &mut Workspace,
200 action: &Spawn,
201 window: &mut Window,
202 cx: &mut Context<Workspace>,
203 );
204
205 fn task_scheduled(&self, cx: &mut App);
206 fn debug_scenario_scheduled(&self, cx: &mut App);
207 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
208
209 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
210}
211
212/// Opens a file or directory.
213#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
214#[action(namespace = workspace)]
215pub struct Open {
216 /// When true, opens in a new window. When false, adds to the current
217 /// window as a new workspace (multi-workspace).
218 #[serde(default = "Open::default_create_new_window")]
219 pub create_new_window: bool,
220}
221
222impl Open {
223 pub const DEFAULT: Self = Self {
224 create_new_window: true,
225 };
226
227 /// Used by `#[serde(default)]` on the `create_new_window` field so that
228 /// the serde default and `Open::DEFAULT` stay in sync.
229 fn default_create_new_window() -> bool {
230 Self::DEFAULT.create_new_window
231 }
232}
233
234impl Default for Open {
235 fn default() -> Self {
236 Self::DEFAULT
237 }
238}
239
240actions!(
241 workspace,
242 [
243 /// Activates the next pane in the workspace.
244 ActivateNextPane,
245 /// Activates the previous pane in the workspace.
246 ActivatePreviousPane,
247 /// Activates the last pane in the workspace.
248 ActivateLastPane,
249 /// Switches to the next window.
250 ActivateNextWindow,
251 /// Switches to the previous window.
252 ActivatePreviousWindow,
253 /// Adds a folder to the current project.
254 AddFolderToProject,
255 /// Clears all notifications.
256 ClearAllNotifications,
257 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
258 ClearNavigationHistory,
259 /// Closes the active dock.
260 CloseActiveDock,
261 /// Closes all docks.
262 CloseAllDocks,
263 /// Toggles all docks.
264 ToggleAllDocks,
265 /// Closes the current window.
266 CloseWindow,
267 /// Closes the current project.
268 CloseProject,
269 /// Opens the feedback dialog.
270 Feedback,
271 /// Follows the next collaborator in the session.
272 FollowNextCollaborator,
273 /// Moves the focused panel to the next position.
274 MoveFocusedPanelToNextPosition,
275 /// Creates a new file.
276 NewFile,
277 /// Creates a new file in a vertical split.
278 NewFileSplitVertical,
279 /// Creates a new file in a horizontal split.
280 NewFileSplitHorizontal,
281 /// Opens a new search.
282 NewSearch,
283 /// Opens a new window.
284 NewWindow,
285 /// Opens multiple files.
286 OpenFiles,
287 /// Opens the current location in terminal.
288 OpenInTerminal,
289 /// Opens the component preview.
290 OpenComponentPreview,
291 /// Reloads the active item.
292 ReloadActiveItem,
293 /// Resets the active dock to its default size.
294 ResetActiveDockSize,
295 /// Resets all open docks to their default sizes.
296 ResetOpenDocksSize,
297 /// Reloads the application
298 Reload,
299 /// Saves the current file with a new name.
300 SaveAs,
301 /// Saves without formatting.
302 SaveWithoutFormat,
303 /// Shuts down all debug adapters.
304 ShutdownDebugAdapters,
305 /// Suppresses the current notification.
306 SuppressNotification,
307 /// Toggles the bottom dock.
308 ToggleBottomDock,
309 /// Toggles centered layout mode.
310 ToggleCenteredLayout,
311 /// Toggles edit prediction feature globally for all files.
312 ToggleEditPrediction,
313 /// Toggles the left dock.
314 ToggleLeftDock,
315 /// Toggles the right dock.
316 ToggleRightDock,
317 /// Toggles zoom on the active pane.
318 ToggleZoom,
319 /// Toggles read-only mode for the active item (if supported by that item).
320 ToggleReadOnlyFile,
321 /// Zooms in on the active pane.
322 ZoomIn,
323 /// Zooms out of the active pane.
324 ZoomOut,
325 /// If any worktrees are in restricted mode, shows a modal with possible actions.
326 /// If the modal is shown already, closes it without trusting any worktree.
327 ToggleWorktreeSecurity,
328 /// Clears all trusted worktrees, placing them in restricted mode on next open.
329 /// Requires restart to take effect on already opened projects.
330 ClearTrustedWorktrees,
331 /// Stops following a collaborator.
332 Unfollow,
333 /// Restores the banner.
334 RestoreBanner,
335 /// Toggles expansion of the selected item.
336 ToggleExpandItem,
337 ]
338);
339
340/// Activates a specific pane by its index.
341#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
342#[action(namespace = workspace)]
343pub struct ActivatePane(pub usize);
344
345/// Moves an item to a specific pane by index.
346#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
347#[action(namespace = workspace)]
348#[serde(deny_unknown_fields)]
349pub struct MoveItemToPane {
350 #[serde(default = "default_1")]
351 pub destination: usize,
352 #[serde(default = "default_true")]
353 pub focus: bool,
354 #[serde(default)]
355 pub clone: bool,
356}
357
358fn default_1() -> usize {
359 1
360}
361
362/// Moves an item to a pane in the specified direction.
363#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
364#[action(namespace = workspace)]
365#[serde(deny_unknown_fields)]
366pub struct MoveItemToPaneInDirection {
367 #[serde(default = "default_right")]
368 pub direction: SplitDirection,
369 #[serde(default = "default_true")]
370 pub focus: bool,
371 #[serde(default)]
372 pub clone: bool,
373}
374
375/// Creates a new file in a split of the desired direction.
376#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
377#[action(namespace = workspace)]
378#[serde(deny_unknown_fields)]
379pub struct NewFileSplit(pub SplitDirection);
380
381fn default_right() -> SplitDirection {
382 SplitDirection::Right
383}
384
385/// Saves all open files in the workspace.
386#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
387#[action(namespace = workspace)]
388#[serde(deny_unknown_fields)]
389pub struct SaveAll {
390 #[serde(default)]
391 pub save_intent: Option<SaveIntent>,
392}
393
394/// Saves the current file with the specified options.
395#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
396#[action(namespace = workspace)]
397#[serde(deny_unknown_fields)]
398pub struct Save {
399 #[serde(default)]
400 pub save_intent: Option<SaveIntent>,
401}
402
403/// Closes all items and panes in the workspace.
404#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
405#[action(namespace = workspace)]
406#[serde(deny_unknown_fields)]
407pub struct CloseAllItemsAndPanes {
408 #[serde(default)]
409 pub save_intent: Option<SaveIntent>,
410}
411
412/// Closes all inactive tabs and panes in the workspace.
413#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
414#[action(namespace = workspace)]
415#[serde(deny_unknown_fields)]
416pub struct CloseInactiveTabsAndPanes {
417 #[serde(default)]
418 pub save_intent: Option<SaveIntent>,
419}
420
421/// Closes the active item across all panes.
422#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
423#[action(namespace = workspace)]
424#[serde(deny_unknown_fields)]
425pub struct CloseItemInAllPanes {
426 #[serde(default)]
427 pub save_intent: Option<SaveIntent>,
428 #[serde(default)]
429 pub close_pinned: bool,
430}
431
432/// Sends a sequence of keystrokes to the active element.
433#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
434#[action(namespace = workspace)]
435pub struct SendKeystrokes(pub String);
436
437actions!(
438 project_symbols,
439 [
440 /// Toggles the project symbols search.
441 #[action(name = "Toggle")]
442 ToggleProjectSymbols
443 ]
444);
445
446/// Toggles the file finder interface.
447#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
448#[action(namespace = file_finder, name = "Toggle")]
449#[serde(deny_unknown_fields)]
450pub struct ToggleFileFinder {
451 #[serde(default)]
452 pub separate_history: bool,
453}
454
455/// Opens a new terminal in the center.
456#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
457#[action(namespace = workspace)]
458#[serde(deny_unknown_fields)]
459pub struct NewCenterTerminal {
460 /// If true, creates a local terminal even in remote projects.
461 #[serde(default)]
462 pub local: bool,
463}
464
465/// Opens a new terminal.
466#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
467#[action(namespace = workspace)]
468#[serde(deny_unknown_fields)]
469pub struct NewTerminal {
470 /// If true, creates a local terminal even in remote projects.
471 #[serde(default)]
472 pub local: bool,
473}
474
475/// Increases size of a currently focused dock by a given amount of pixels.
476#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
477#[action(namespace = workspace)]
478#[serde(deny_unknown_fields)]
479pub struct IncreaseActiveDockSize {
480 /// For 0px parameter, uses UI font size value.
481 #[serde(default)]
482 pub px: u32,
483}
484
485/// Decreases size of a currently focused dock by a given amount of pixels.
486#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
487#[action(namespace = workspace)]
488#[serde(deny_unknown_fields)]
489pub struct DecreaseActiveDockSize {
490 /// For 0px parameter, uses UI font size value.
491 #[serde(default)]
492 pub px: u32,
493}
494
495/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
496#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
497#[action(namespace = workspace)]
498#[serde(deny_unknown_fields)]
499pub struct IncreaseOpenDocksSize {
500 /// For 0px parameter, uses UI font size value.
501 #[serde(default)]
502 pub px: u32,
503}
504
505/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
506#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
507#[action(namespace = workspace)]
508#[serde(deny_unknown_fields)]
509pub struct DecreaseOpenDocksSize {
510 /// For 0px parameter, uses UI font size value.
511 #[serde(default)]
512 pub px: u32,
513}
514
515actions!(
516 workspace,
517 [
518 /// Activates the pane to the left.
519 ActivatePaneLeft,
520 /// Activates the pane to the right.
521 ActivatePaneRight,
522 /// Activates the pane above.
523 ActivatePaneUp,
524 /// Activates the pane below.
525 ActivatePaneDown,
526 /// Swaps the current pane with the one to the left.
527 SwapPaneLeft,
528 /// Swaps the current pane with the one to the right.
529 SwapPaneRight,
530 /// Swaps the current pane with the one above.
531 SwapPaneUp,
532 /// Swaps the current pane with the one below.
533 SwapPaneDown,
534 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
535 SwapPaneAdjacent,
536 /// Move the current pane to be at the far left.
537 MovePaneLeft,
538 /// Move the current pane to be at the far right.
539 MovePaneRight,
540 /// Move the current pane to be at the very top.
541 MovePaneUp,
542 /// Move the current pane to be at the very bottom.
543 MovePaneDown,
544 ]
545);
546
547#[derive(PartialEq, Eq, Debug)]
548pub enum CloseIntent {
549 /// Quit the program entirely.
550 Quit,
551 /// Close a window.
552 CloseWindow,
553 /// Replace the workspace in an existing window.
554 ReplaceWindow,
555}
556
557#[derive(Clone)]
558pub struct Toast {
559 id: NotificationId,
560 msg: Cow<'static, str>,
561 autohide: bool,
562 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
563}
564
565impl Toast {
566 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
567 Toast {
568 id,
569 msg: msg.into(),
570 on_click: None,
571 autohide: false,
572 }
573 }
574
575 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
576 where
577 M: Into<Cow<'static, str>>,
578 F: Fn(&mut Window, &mut App) + 'static,
579 {
580 self.on_click = Some((message.into(), Arc::new(on_click)));
581 self
582 }
583
584 pub fn autohide(mut self) -> Self {
585 self.autohide = true;
586 self
587 }
588}
589
590impl PartialEq for Toast {
591 fn eq(&self, other: &Self) -> bool {
592 self.id == other.id
593 && self.msg == other.msg
594 && self.on_click.is_some() == other.on_click.is_some()
595 }
596}
597
598/// Opens a new terminal with the specified working directory.
599#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
600#[action(namespace = workspace)]
601#[serde(deny_unknown_fields)]
602pub struct OpenTerminal {
603 pub working_directory: PathBuf,
604 /// If true, creates a local terminal even in remote projects.
605 #[serde(default)]
606 pub local: bool,
607}
608
609#[derive(
610 Clone,
611 Copy,
612 Debug,
613 Default,
614 Hash,
615 PartialEq,
616 Eq,
617 PartialOrd,
618 Ord,
619 serde::Serialize,
620 serde::Deserialize,
621)]
622pub struct WorkspaceId(i64);
623
624impl WorkspaceId {
625 pub fn from_i64(value: i64) -> Self {
626 Self(value)
627 }
628}
629
630impl StaticColumnCount for WorkspaceId {}
631impl Bind for WorkspaceId {
632 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
633 self.0.bind(statement, start_index)
634 }
635}
636impl Column for WorkspaceId {
637 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
638 i64::column(statement, start_index)
639 .map(|(i, next_index)| (Self(i), next_index))
640 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
641 }
642}
643impl From<WorkspaceId> for i64 {
644 fn from(val: WorkspaceId) -> Self {
645 val.0
646 }
647}
648
649fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
650 if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
651 workspace_window
652 .update(cx, |multi_workspace, window, cx| {
653 let workspace = multi_workspace.workspace().clone();
654 workspace.update(cx, |workspace, cx| {
655 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
656 });
657 })
658 .ok();
659 } else {
660 let task = Workspace::new_local(Vec::new(), app_state.clone(), None, None, None, true, cx);
661 cx.spawn(async move |cx| {
662 let OpenResult { window, .. } = task.await?;
663 window.update(cx, |multi_workspace, window, cx| {
664 window.activate_window();
665 let workspace = multi_workspace.workspace().clone();
666 workspace.update(cx, |workspace, cx| {
667 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
668 });
669 })?;
670 anyhow::Ok(())
671 })
672 .detach_and_log_err(cx);
673 }
674}
675
676pub fn prompt_for_open_path_and_open(
677 workspace: &mut Workspace,
678 app_state: Arc<AppState>,
679 options: PathPromptOptions,
680 create_new_window: bool,
681 window: &mut Window,
682 cx: &mut Context<Workspace>,
683) {
684 let paths = workspace.prompt_for_open_path(
685 options,
686 DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
687 window,
688 cx,
689 );
690 let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
691 cx.spawn_in(window, async move |this, cx| {
692 let Some(paths) = paths.await.log_err().flatten() else {
693 return;
694 };
695 if !create_new_window {
696 if let Some(handle) = multi_workspace_handle {
697 if let Some(task) = handle
698 .update(cx, |multi_workspace, window, cx| {
699 multi_workspace.open_project(paths, window, cx)
700 })
701 .log_err()
702 {
703 task.await.log_err();
704 }
705 return;
706 }
707 }
708 if let Some(task) = this
709 .update_in(cx, |this, window, cx| {
710 this.open_workspace_for_paths(false, paths, window, cx)
711 })
712 .log_err()
713 {
714 task.await.log_err();
715 }
716 })
717 .detach();
718}
719
720pub fn init(app_state: Arc<AppState>, cx: &mut App) {
721 component::init();
722 theme_preview::init(cx);
723 toast_layer::init(cx);
724 history_manager::init(app_state.fs.clone(), cx);
725
726 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
727 .on_action(|_: &Reload, cx| reload(cx))
728 .on_action({
729 let app_state = Arc::downgrade(&app_state);
730 move |_: &Open, cx: &mut App| {
731 if let Some(app_state) = app_state.upgrade() {
732 prompt_and_open_paths(
733 app_state,
734 PathPromptOptions {
735 files: true,
736 directories: true,
737 multiple: true,
738 prompt: None,
739 },
740 cx,
741 );
742 }
743 }
744 })
745 .on_action({
746 let app_state = Arc::downgrade(&app_state);
747 move |_: &OpenFiles, cx: &mut App| {
748 let directories = cx.can_select_mixed_files_and_dirs();
749 if let Some(app_state) = app_state.upgrade() {
750 prompt_and_open_paths(
751 app_state,
752 PathPromptOptions {
753 files: true,
754 directories,
755 multiple: true,
756 prompt: None,
757 },
758 cx,
759 );
760 }
761 }
762 });
763}
764
765type BuildProjectItemFn =
766 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
767
768type BuildProjectItemForPathFn =
769 fn(
770 &Entity<Project>,
771 &ProjectPath,
772 &mut Window,
773 &mut App,
774 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
775
776#[derive(Clone, Default)]
777struct ProjectItemRegistry {
778 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
779 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
780}
781
782impl ProjectItemRegistry {
783 fn register<T: ProjectItem>(&mut self) {
784 self.build_project_item_fns_by_type.insert(
785 TypeId::of::<T::Item>(),
786 |item, project, pane, window, cx| {
787 let item = item.downcast().unwrap();
788 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
789 as Box<dyn ItemHandle>
790 },
791 );
792 self.build_project_item_for_path_fns
793 .push(|project, project_path, window, cx| {
794 let project_path = project_path.clone();
795 let is_file = project
796 .read(cx)
797 .entry_for_path(&project_path, cx)
798 .is_some_and(|entry| entry.is_file());
799 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
800 let is_local = project.read(cx).is_local();
801 let project_item =
802 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
803 let project = project.clone();
804 Some(window.spawn(cx, async move |cx| {
805 match project_item.await.with_context(|| {
806 format!(
807 "opening project path {:?}",
808 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
809 )
810 }) {
811 Ok(project_item) => {
812 let project_item = project_item;
813 let project_entry_id: Option<ProjectEntryId> =
814 project_item.read_with(cx, project::ProjectItem::entry_id);
815 let build_workspace_item = Box::new(
816 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
817 Box::new(cx.new(|cx| {
818 T::for_project_item(
819 project,
820 Some(pane),
821 project_item,
822 window,
823 cx,
824 )
825 })) as Box<dyn ItemHandle>
826 },
827 ) as Box<_>;
828 Ok((project_entry_id, build_workspace_item))
829 }
830 Err(e) => {
831 log::warn!("Failed to open a project item: {e:#}");
832 if e.error_code() == ErrorCode::Internal {
833 if let Some(abs_path) =
834 entry_abs_path.as_deref().filter(|_| is_file)
835 {
836 if let Some(broken_project_item_view) =
837 cx.update(|window, cx| {
838 T::for_broken_project_item(
839 abs_path, is_local, &e, window, cx,
840 )
841 })?
842 {
843 let build_workspace_item = Box::new(
844 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
845 cx.new(|_| broken_project_item_view).boxed_clone()
846 },
847 )
848 as Box<_>;
849 return Ok((None, build_workspace_item));
850 }
851 }
852 }
853 Err(e)
854 }
855 }
856 }))
857 });
858 }
859
860 fn open_path(
861 &self,
862 project: &Entity<Project>,
863 path: &ProjectPath,
864 window: &mut Window,
865 cx: &mut App,
866 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
867 let Some(open_project_item) = self
868 .build_project_item_for_path_fns
869 .iter()
870 .rev()
871 .find_map(|open_project_item| open_project_item(project, path, window, cx))
872 else {
873 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
874 };
875 open_project_item
876 }
877
878 fn build_item<T: project::ProjectItem>(
879 &self,
880 item: Entity<T>,
881 project: Entity<Project>,
882 pane: Option<&Pane>,
883 window: &mut Window,
884 cx: &mut App,
885 ) -> Option<Box<dyn ItemHandle>> {
886 let build = self
887 .build_project_item_fns_by_type
888 .get(&TypeId::of::<T>())?;
889 Some(build(item.into_any(), project, pane, window, cx))
890 }
891}
892
893type WorkspaceItemBuilder =
894 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
895
896impl Global for ProjectItemRegistry {}
897
898/// Registers a [ProjectItem] for the app. When opening a file, all the registered
899/// items will get a chance to open the file, starting from the project item that
900/// was added last.
901pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
902 cx.default_global::<ProjectItemRegistry>().register::<I>();
903}
904
905#[derive(Default)]
906pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
907
908struct FollowableViewDescriptor {
909 from_state_proto: fn(
910 Entity<Workspace>,
911 ViewId,
912 &mut Option<proto::view::Variant>,
913 &mut Window,
914 &mut App,
915 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
916 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
917}
918
919impl Global for FollowableViewRegistry {}
920
921impl FollowableViewRegistry {
922 pub fn register<I: FollowableItem>(cx: &mut App) {
923 cx.default_global::<Self>().0.insert(
924 TypeId::of::<I>(),
925 FollowableViewDescriptor {
926 from_state_proto: |workspace, id, state, window, cx| {
927 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
928 cx.foreground_executor()
929 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
930 })
931 },
932 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
933 },
934 );
935 }
936
937 pub fn from_state_proto(
938 workspace: Entity<Workspace>,
939 view_id: ViewId,
940 mut state: Option<proto::view::Variant>,
941 window: &mut Window,
942 cx: &mut App,
943 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
944 cx.update_default_global(|this: &mut Self, cx| {
945 this.0.values().find_map(|descriptor| {
946 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
947 })
948 })
949 }
950
951 pub fn to_followable_view(
952 view: impl Into<AnyView>,
953 cx: &App,
954 ) -> Option<Box<dyn FollowableItemHandle>> {
955 let this = cx.try_global::<Self>()?;
956 let view = view.into();
957 let descriptor = this.0.get(&view.entity_type())?;
958 Some((descriptor.to_followable_view)(&view))
959 }
960}
961
962#[derive(Copy, Clone)]
963struct SerializableItemDescriptor {
964 deserialize: fn(
965 Entity<Project>,
966 WeakEntity<Workspace>,
967 WorkspaceId,
968 ItemId,
969 &mut Window,
970 &mut Context<Pane>,
971 ) -> Task<Result<Box<dyn ItemHandle>>>,
972 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
973 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
974}
975
976#[derive(Default)]
977struct SerializableItemRegistry {
978 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
979 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
980}
981
982impl Global for SerializableItemRegistry {}
983
984impl SerializableItemRegistry {
985 fn deserialize(
986 item_kind: &str,
987 project: Entity<Project>,
988 workspace: WeakEntity<Workspace>,
989 workspace_id: WorkspaceId,
990 item_item: ItemId,
991 window: &mut Window,
992 cx: &mut Context<Pane>,
993 ) -> Task<Result<Box<dyn ItemHandle>>> {
994 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
995 return Task::ready(Err(anyhow!(
996 "cannot deserialize {}, descriptor not found",
997 item_kind
998 )));
999 };
1000
1001 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
1002 }
1003
1004 fn cleanup(
1005 item_kind: &str,
1006 workspace_id: WorkspaceId,
1007 loaded_items: Vec<ItemId>,
1008 window: &mut Window,
1009 cx: &mut App,
1010 ) -> Task<Result<()>> {
1011 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1012 return Task::ready(Err(anyhow!(
1013 "cannot cleanup {}, descriptor not found",
1014 item_kind
1015 )));
1016 };
1017
1018 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
1019 }
1020
1021 fn view_to_serializable_item_handle(
1022 view: AnyView,
1023 cx: &App,
1024 ) -> Option<Box<dyn SerializableItemHandle>> {
1025 let this = cx.try_global::<Self>()?;
1026 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
1027 Some((descriptor.view_to_serializable_item)(view))
1028 }
1029
1030 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
1031 let this = cx.try_global::<Self>()?;
1032 this.descriptors_by_kind.get(item_kind).copied()
1033 }
1034}
1035
1036pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
1037 let serialized_item_kind = I::serialized_item_kind();
1038
1039 let registry = cx.default_global::<SerializableItemRegistry>();
1040 let descriptor = SerializableItemDescriptor {
1041 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
1042 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
1043 cx.foreground_executor()
1044 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
1045 },
1046 cleanup: |workspace_id, loaded_items, window, cx| {
1047 I::cleanup(workspace_id, loaded_items, window, cx)
1048 },
1049 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
1050 };
1051 registry
1052 .descriptors_by_kind
1053 .insert(Arc::from(serialized_item_kind), descriptor);
1054 registry
1055 .descriptors_by_type
1056 .insert(TypeId::of::<I>(), descriptor);
1057}
1058
1059pub struct AppState {
1060 pub languages: Arc<LanguageRegistry>,
1061 pub client: Arc<Client>,
1062 pub user_store: Entity<UserStore>,
1063 pub workspace_store: Entity<WorkspaceStore>,
1064 pub fs: Arc<dyn fs::Fs>,
1065 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1066 pub node_runtime: NodeRuntime,
1067 pub session: Entity<AppSession>,
1068}
1069
1070struct GlobalAppState(Weak<AppState>);
1071
1072impl Global for GlobalAppState {}
1073
1074pub struct WorkspaceStore {
1075 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1076 client: Arc<Client>,
1077 _subscriptions: Vec<client::Subscription>,
1078}
1079
1080#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1081pub enum CollaboratorId {
1082 PeerId(PeerId),
1083 Agent,
1084}
1085
1086impl From<PeerId> for CollaboratorId {
1087 fn from(peer_id: PeerId) -> Self {
1088 CollaboratorId::PeerId(peer_id)
1089 }
1090}
1091
1092impl From<&PeerId> for CollaboratorId {
1093 fn from(peer_id: &PeerId) -> Self {
1094 CollaboratorId::PeerId(*peer_id)
1095 }
1096}
1097
1098#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1099struct Follower {
1100 project_id: Option<u64>,
1101 peer_id: PeerId,
1102}
1103
1104impl AppState {
1105 #[track_caller]
1106 pub fn global(cx: &App) -> Weak<Self> {
1107 cx.global::<GlobalAppState>().0.clone()
1108 }
1109 pub fn try_global(cx: &App) -> Option<Weak<Self>> {
1110 cx.try_global::<GlobalAppState>()
1111 .map(|state| state.0.clone())
1112 }
1113 pub fn set_global(state: Weak<AppState>, cx: &mut App) {
1114 cx.set_global(GlobalAppState(state));
1115 }
1116
1117 #[cfg(any(test, feature = "test-support"))]
1118 pub fn test(cx: &mut App) -> Arc<Self> {
1119 use fs::Fs;
1120 use node_runtime::NodeRuntime;
1121 use session::Session;
1122 use settings::SettingsStore;
1123
1124 if !cx.has_global::<SettingsStore>() {
1125 let settings_store = SettingsStore::test(cx);
1126 cx.set_global(settings_store);
1127 }
1128
1129 let fs = fs::FakeFs::new(cx.background_executor().clone());
1130 <dyn Fs>::set_global(fs.clone(), cx);
1131 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1132 let clock = Arc::new(clock::FakeSystemClock::new());
1133 let http_client = http_client::FakeHttpClient::with_404_response();
1134 let client = Client::new(clock, http_client, cx);
1135 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1136 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1137 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1138
1139 theme::init(theme::LoadThemes::JustBase, cx);
1140 client::init(&client, cx);
1141
1142 Arc::new(Self {
1143 client,
1144 fs,
1145 languages,
1146 user_store,
1147 workspace_store,
1148 node_runtime: NodeRuntime::unavailable(),
1149 build_window_options: |_, _| Default::default(),
1150 session,
1151 })
1152 }
1153}
1154
1155struct DelayedDebouncedEditAction {
1156 task: Option<Task<()>>,
1157 cancel_channel: Option<oneshot::Sender<()>>,
1158}
1159
1160impl DelayedDebouncedEditAction {
1161 fn new() -> DelayedDebouncedEditAction {
1162 DelayedDebouncedEditAction {
1163 task: None,
1164 cancel_channel: None,
1165 }
1166 }
1167
1168 fn fire_new<F>(
1169 &mut self,
1170 delay: Duration,
1171 window: &mut Window,
1172 cx: &mut Context<Workspace>,
1173 func: F,
1174 ) where
1175 F: 'static
1176 + Send
1177 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1178 {
1179 if let Some(channel) = self.cancel_channel.take() {
1180 _ = channel.send(());
1181 }
1182
1183 let (sender, mut receiver) = oneshot::channel::<()>();
1184 self.cancel_channel = Some(sender);
1185
1186 let previous_task = self.task.take();
1187 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1188 let mut timer = cx.background_executor().timer(delay).fuse();
1189 if let Some(previous_task) = previous_task {
1190 previous_task.await;
1191 }
1192
1193 futures::select_biased! {
1194 _ = receiver => return,
1195 _ = timer => {}
1196 }
1197
1198 if let Some(result) = workspace
1199 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1200 .log_err()
1201 {
1202 result.await.log_err();
1203 }
1204 }));
1205 }
1206}
1207
1208pub enum Event {
1209 PaneAdded(Entity<Pane>),
1210 PaneRemoved,
1211 ItemAdded {
1212 item: Box<dyn ItemHandle>,
1213 },
1214 ActiveItemChanged,
1215 ItemRemoved {
1216 item_id: EntityId,
1217 },
1218 UserSavedItem {
1219 pane: WeakEntity<Pane>,
1220 item: Box<dyn WeakItemHandle>,
1221 save_intent: SaveIntent,
1222 },
1223 ContactRequestedJoin(u64),
1224 WorkspaceCreated(WeakEntity<Workspace>),
1225 OpenBundledFile {
1226 text: Cow<'static, str>,
1227 title: &'static str,
1228 language: &'static str,
1229 },
1230 ZoomChanged,
1231 ModalOpened,
1232 Activate,
1233 PanelAdded(AnyView),
1234}
1235
1236#[derive(Debug, Clone)]
1237pub enum OpenVisible {
1238 All,
1239 None,
1240 OnlyFiles,
1241 OnlyDirectories,
1242}
1243
1244enum WorkspaceLocation {
1245 // Valid local paths or SSH project to serialize
1246 Location(SerializedWorkspaceLocation, PathList),
1247 // No valid location found hence clear session id
1248 DetachFromSession,
1249 // No valid location found to serialize
1250 None,
1251}
1252
1253type PromptForNewPath = Box<
1254 dyn Fn(
1255 &mut Workspace,
1256 DirectoryLister,
1257 Option<String>,
1258 &mut Window,
1259 &mut Context<Workspace>,
1260 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1261>;
1262
1263type PromptForOpenPath = Box<
1264 dyn Fn(
1265 &mut Workspace,
1266 DirectoryLister,
1267 &mut Window,
1268 &mut Context<Workspace>,
1269 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1270>;
1271
1272#[derive(Default)]
1273struct DispatchingKeystrokes {
1274 dispatched: HashSet<Vec<Keystroke>>,
1275 queue: VecDeque<Keystroke>,
1276 task: Option<Shared<Task<()>>>,
1277}
1278
1279/// Collects everything project-related for a certain window opened.
1280/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1281///
1282/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1283/// The `Workspace` owns everybody's state and serves as a default, "global context",
1284/// that can be used to register a global action to be triggered from any place in the window.
1285pub struct Workspace {
1286 weak_self: WeakEntity<Self>,
1287 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1288 zoomed: Option<AnyWeakView>,
1289 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1290 zoomed_position: Option<DockPosition>,
1291 center: PaneGroup,
1292 left_dock: Entity<Dock>,
1293 bottom_dock: Entity<Dock>,
1294 right_dock: Entity<Dock>,
1295 panes: Vec<Entity<Pane>>,
1296 active_worktree_override: Option<WorktreeId>,
1297 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1298 active_pane: Entity<Pane>,
1299 last_active_center_pane: Option<WeakEntity<Pane>>,
1300 last_active_view_id: Option<proto::ViewId>,
1301 status_bar: Entity<StatusBar>,
1302 pub(crate) modal_layer: Entity<ModalLayer>,
1303 toast_layer: Entity<ToastLayer>,
1304 titlebar_item: Option<AnyView>,
1305 notifications: Notifications,
1306 suppressed_notifications: HashSet<NotificationId>,
1307 project: Entity<Project>,
1308 follower_states: HashMap<CollaboratorId, FollowerState>,
1309 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1310 window_edited: bool,
1311 last_window_title: Option<String>,
1312 dirty_items: HashMap<EntityId, Subscription>,
1313 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1314 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1315 database_id: Option<WorkspaceId>,
1316 app_state: Arc<AppState>,
1317 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1318 _subscriptions: Vec<Subscription>,
1319 _apply_leader_updates: Task<Result<()>>,
1320 _observe_current_user: Task<Result<()>>,
1321 _schedule_serialize_workspace: Option<Task<()>>,
1322 _serialize_workspace_task: Option<Task<()>>,
1323 _schedule_serialize_ssh_paths: Option<Task<()>>,
1324 pane_history_timestamp: Arc<AtomicUsize>,
1325 bounds: Bounds<Pixels>,
1326 pub centered_layout: bool,
1327 bounds_save_task_queued: Option<Task<()>>,
1328 on_prompt_for_new_path: Option<PromptForNewPath>,
1329 on_prompt_for_open_path: Option<PromptForOpenPath>,
1330 terminal_provider: Option<Box<dyn TerminalProvider>>,
1331 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1332 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1333 _items_serializer: Task<Result<()>>,
1334 session_id: Option<String>,
1335 scheduled_tasks: Vec<Task<()>>,
1336 last_open_dock_positions: Vec<DockPosition>,
1337 removing: bool,
1338 _panels_task: Option<Task<Result<()>>>,
1339}
1340
1341impl EventEmitter<Event> for Workspace {}
1342
1343#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1344pub struct ViewId {
1345 pub creator: CollaboratorId,
1346 pub id: u64,
1347}
1348
1349pub struct FollowerState {
1350 center_pane: Entity<Pane>,
1351 dock_pane: Option<Entity<Pane>>,
1352 active_view_id: Option<ViewId>,
1353 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1354}
1355
1356struct FollowerView {
1357 view: Box<dyn FollowableItemHandle>,
1358 location: Option<proto::PanelId>,
1359}
1360
1361impl Workspace {
1362 pub fn new(
1363 workspace_id: Option<WorkspaceId>,
1364 project: Entity<Project>,
1365 app_state: Arc<AppState>,
1366 window: &mut Window,
1367 cx: &mut Context<Self>,
1368 ) -> Self {
1369 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1370 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1371 if let TrustedWorktreesEvent::Trusted(..) = e {
1372 // Do not persist auto trusted worktrees
1373 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1374 worktrees_store.update(cx, |worktrees_store, cx| {
1375 worktrees_store.schedule_serialization(
1376 cx,
1377 |new_trusted_worktrees, cx| {
1378 let timeout =
1379 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1380 cx.background_spawn(async move {
1381 timeout.await;
1382 persistence::DB
1383 .save_trusted_worktrees(new_trusted_worktrees)
1384 .await
1385 .log_err();
1386 })
1387 },
1388 )
1389 });
1390 }
1391 }
1392 })
1393 .detach();
1394
1395 cx.observe_global::<SettingsStore>(|_, cx| {
1396 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1397 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1398 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1399 trusted_worktrees.auto_trust_all(cx);
1400 })
1401 }
1402 }
1403 })
1404 .detach();
1405 }
1406
1407 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1408 match event {
1409 project::Event::RemoteIdChanged(_) => {
1410 this.update_window_title(window, cx);
1411 }
1412
1413 project::Event::CollaboratorLeft(peer_id) => {
1414 this.collaborator_left(*peer_id, window, cx);
1415 }
1416
1417 &project::Event::WorktreeRemoved(id) | &project::Event::WorktreeAdded(id) => {
1418 this.update_window_title(window, cx);
1419 if this
1420 .project()
1421 .read(cx)
1422 .worktree_for_id(id, cx)
1423 .is_some_and(|wt| wt.read(cx).is_visible())
1424 {
1425 this.serialize_workspace(window, cx);
1426 this.update_history(cx);
1427 }
1428 }
1429 project::Event::WorktreeUpdatedEntries(..) => {
1430 this.update_window_title(window, cx);
1431 this.serialize_workspace(window, cx);
1432 }
1433
1434 project::Event::DisconnectedFromHost => {
1435 this.update_window_edited(window, cx);
1436 let leaders_to_unfollow =
1437 this.follower_states.keys().copied().collect::<Vec<_>>();
1438 for leader_id in leaders_to_unfollow {
1439 this.unfollow(leader_id, window, cx);
1440 }
1441 }
1442
1443 project::Event::DisconnectedFromRemote {
1444 server_not_running: _,
1445 } => {
1446 this.update_window_edited(window, cx);
1447 }
1448
1449 project::Event::Closed => {
1450 window.remove_window();
1451 }
1452
1453 project::Event::DeletedEntry(_, entry_id) => {
1454 for pane in this.panes.iter() {
1455 pane.update(cx, |pane, cx| {
1456 pane.handle_deleted_project_item(*entry_id, window, cx)
1457 });
1458 }
1459 }
1460
1461 project::Event::Toast {
1462 notification_id,
1463 message,
1464 link,
1465 } => this.show_notification(
1466 NotificationId::named(notification_id.clone()),
1467 cx,
1468 |cx| {
1469 let mut notification = MessageNotification::new(message.clone(), cx);
1470 if let Some(link) = link {
1471 notification = notification
1472 .more_info_message(link.label)
1473 .more_info_url(link.url);
1474 }
1475
1476 cx.new(|_| notification)
1477 },
1478 ),
1479
1480 project::Event::HideToast { notification_id } => {
1481 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1482 }
1483
1484 project::Event::LanguageServerPrompt(request) => {
1485 struct LanguageServerPrompt;
1486
1487 this.show_notification(
1488 NotificationId::composite::<LanguageServerPrompt>(request.id),
1489 cx,
1490 |cx| {
1491 cx.new(|cx| {
1492 notifications::LanguageServerPrompt::new(request.clone(), cx)
1493 })
1494 },
1495 );
1496 }
1497
1498 project::Event::AgentLocationChanged => {
1499 this.handle_agent_location_changed(window, cx)
1500 }
1501
1502 _ => {}
1503 }
1504 cx.notify()
1505 })
1506 .detach();
1507
1508 cx.subscribe_in(
1509 &project.read(cx).breakpoint_store(),
1510 window,
1511 |workspace, _, event, window, cx| match event {
1512 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1513 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1514 workspace.serialize_workspace(window, cx);
1515 }
1516 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1517 },
1518 )
1519 .detach();
1520 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1521 cx.subscribe_in(
1522 &toolchain_store,
1523 window,
1524 |workspace, _, event, window, cx| match event {
1525 ToolchainStoreEvent::CustomToolchainsModified => {
1526 workspace.serialize_workspace(window, cx);
1527 }
1528 _ => {}
1529 },
1530 )
1531 .detach();
1532 }
1533
1534 cx.on_focus_lost(window, |this, window, cx| {
1535 let focus_handle = this.focus_handle(cx);
1536 window.focus(&focus_handle, cx);
1537 })
1538 .detach();
1539
1540 let weak_handle = cx.entity().downgrade();
1541 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1542
1543 let center_pane = cx.new(|cx| {
1544 let mut center_pane = Pane::new(
1545 weak_handle.clone(),
1546 project.clone(),
1547 pane_history_timestamp.clone(),
1548 None,
1549 NewFile.boxed_clone(),
1550 true,
1551 window,
1552 cx,
1553 );
1554 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1555 center_pane.set_should_display_welcome_page(true);
1556 center_pane
1557 });
1558 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1559 .detach();
1560
1561 window.focus(¢er_pane.focus_handle(cx), cx);
1562
1563 cx.emit(Event::PaneAdded(center_pane.clone()));
1564
1565 let any_window_handle = window.window_handle();
1566 app_state.workspace_store.update(cx, |store, _| {
1567 store
1568 .workspaces
1569 .insert((any_window_handle, weak_handle.clone()));
1570 });
1571
1572 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1573 let mut connection_status = app_state.client.status();
1574 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1575 current_user.next().await;
1576 connection_status.next().await;
1577 let mut stream =
1578 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1579
1580 while stream.recv().await.is_some() {
1581 this.update(cx, |_, cx| cx.notify())?;
1582 }
1583 anyhow::Ok(())
1584 });
1585
1586 // All leader updates are enqueued and then processed in a single task, so
1587 // that each asynchronous operation can be run in order.
1588 let (leader_updates_tx, mut leader_updates_rx) =
1589 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1590 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1591 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1592 Self::process_leader_update(&this, leader_id, update, cx)
1593 .await
1594 .log_err();
1595 }
1596
1597 Ok(())
1598 });
1599
1600 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1601 let modal_layer = cx.new(|_| ModalLayer::new());
1602 let toast_layer = cx.new(|_| ToastLayer::new());
1603 cx.subscribe(
1604 &modal_layer,
1605 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1606 cx.emit(Event::ModalOpened);
1607 },
1608 )
1609 .detach();
1610
1611 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1612 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1613 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1614 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1615 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1616 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1617 let status_bar = cx.new(|cx| {
1618 let mut status_bar = StatusBar::new(¢er_pane.clone(), window, cx);
1619 status_bar.add_left_item(left_dock_buttons, window, cx);
1620 status_bar.add_right_item(right_dock_buttons, window, cx);
1621 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1622 status_bar
1623 });
1624
1625 let session_id = app_state.session.read(cx).id().to_owned();
1626
1627 let mut active_call = None;
1628 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1629 let subscriptions =
1630 vec![
1631 call.0
1632 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1633 ];
1634 active_call = Some((call, subscriptions));
1635 }
1636
1637 let (serializable_items_tx, serializable_items_rx) =
1638 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1639 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1640 Self::serialize_items(&this, serializable_items_rx, cx).await
1641 });
1642
1643 let subscriptions = vec![
1644 cx.observe_window_activation(window, Self::on_window_activation_changed),
1645 cx.observe_window_bounds(window, move |this, window, cx| {
1646 if this.bounds_save_task_queued.is_some() {
1647 return;
1648 }
1649 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1650 cx.background_executor()
1651 .timer(Duration::from_millis(100))
1652 .await;
1653 this.update_in(cx, |this, window, cx| {
1654 this.save_window_bounds(window, cx).detach();
1655 this.bounds_save_task_queued.take();
1656 })
1657 .ok();
1658 }));
1659 cx.notify();
1660 }),
1661 cx.observe_window_appearance(window, |_, window, cx| {
1662 let window_appearance = window.appearance();
1663
1664 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1665
1666 GlobalTheme::reload_theme(cx);
1667 GlobalTheme::reload_icon_theme(cx);
1668 }),
1669 cx.on_release({
1670 let weak_handle = weak_handle.clone();
1671 move |this, cx| {
1672 this.app_state.workspace_store.update(cx, move |store, _| {
1673 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1674 })
1675 }
1676 }),
1677 ];
1678
1679 cx.defer_in(window, move |this, window, cx| {
1680 this.update_window_title(window, cx);
1681 this.show_initial_notifications(cx);
1682 });
1683
1684 let mut center = PaneGroup::new(center_pane.clone());
1685 center.set_is_center(true);
1686 center.mark_positions(cx);
1687
1688 Workspace {
1689 weak_self: weak_handle.clone(),
1690 zoomed: None,
1691 zoomed_position: None,
1692 previous_dock_drag_coordinates: None,
1693 center,
1694 panes: vec![center_pane.clone()],
1695 panes_by_item: Default::default(),
1696 active_pane: center_pane.clone(),
1697 last_active_center_pane: Some(center_pane.downgrade()),
1698 last_active_view_id: None,
1699 status_bar,
1700 modal_layer,
1701 toast_layer,
1702 titlebar_item: None,
1703 active_worktree_override: None,
1704 notifications: Notifications::default(),
1705 suppressed_notifications: HashSet::default(),
1706 left_dock,
1707 bottom_dock,
1708 right_dock,
1709 _panels_task: None,
1710 project: project.clone(),
1711 follower_states: Default::default(),
1712 last_leaders_by_pane: Default::default(),
1713 dispatching_keystrokes: Default::default(),
1714 window_edited: false,
1715 last_window_title: None,
1716 dirty_items: Default::default(),
1717 active_call,
1718 database_id: workspace_id,
1719 app_state,
1720 _observe_current_user,
1721 _apply_leader_updates,
1722 _schedule_serialize_workspace: None,
1723 _serialize_workspace_task: None,
1724 _schedule_serialize_ssh_paths: None,
1725 leader_updates_tx,
1726 _subscriptions: subscriptions,
1727 pane_history_timestamp,
1728 workspace_actions: Default::default(),
1729 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1730 bounds: Default::default(),
1731 centered_layout: false,
1732 bounds_save_task_queued: None,
1733 on_prompt_for_new_path: None,
1734 on_prompt_for_open_path: None,
1735 terminal_provider: None,
1736 debugger_provider: None,
1737 serializable_items_tx,
1738 _items_serializer,
1739 session_id: Some(session_id),
1740
1741 scheduled_tasks: Vec::new(),
1742 last_open_dock_positions: Vec::new(),
1743 removing: false,
1744 }
1745 }
1746
1747 pub fn new_local(
1748 abs_paths: Vec<PathBuf>,
1749 app_state: Arc<AppState>,
1750 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1751 env: Option<HashMap<String, String>>,
1752 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1753 activate: bool,
1754 cx: &mut App,
1755 ) -> Task<anyhow::Result<OpenResult>> {
1756 let project_handle = Project::local(
1757 app_state.client.clone(),
1758 app_state.node_runtime.clone(),
1759 app_state.user_store.clone(),
1760 app_state.languages.clone(),
1761 app_state.fs.clone(),
1762 env,
1763 Default::default(),
1764 cx,
1765 );
1766
1767 cx.spawn(async move |cx| {
1768 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1769 for path in abs_paths.into_iter() {
1770 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1771 paths_to_open.push(canonical)
1772 } else {
1773 paths_to_open.push(path)
1774 }
1775 }
1776
1777 let serialized_workspace =
1778 persistence::DB.workspace_for_roots(paths_to_open.as_slice());
1779
1780 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1781 paths_to_open = paths.ordered_paths().cloned().collect();
1782 if !paths.is_lexicographically_ordered() {
1783 project_handle.update(cx, |project, cx| {
1784 project.set_worktrees_reordered(true, cx);
1785 });
1786 }
1787 }
1788
1789 // Get project paths for all of the abs_paths
1790 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1791 Vec::with_capacity(paths_to_open.len());
1792
1793 for path in paths_to_open.into_iter() {
1794 if let Some((_, project_entry)) = cx
1795 .update(|cx| {
1796 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1797 })
1798 .await
1799 .log_err()
1800 {
1801 project_paths.push((path, Some(project_entry)));
1802 } else {
1803 project_paths.push((path, None));
1804 }
1805 }
1806
1807 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1808 serialized_workspace.id
1809 } else {
1810 DB.next_id().await.unwrap_or_else(|_| Default::default())
1811 };
1812
1813 let toolchains = DB.toolchains(workspace_id).await?;
1814
1815 for (toolchain, worktree_path, path) in toolchains {
1816 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1817 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1818 this.find_worktree(&worktree_path, cx)
1819 .and_then(|(worktree, rel_path)| {
1820 if rel_path.is_empty() {
1821 Some(worktree.read(cx).id())
1822 } else {
1823 None
1824 }
1825 })
1826 }) else {
1827 // We did not find a worktree with a given path, but that's whatever.
1828 continue;
1829 };
1830 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1831 continue;
1832 }
1833
1834 project_handle
1835 .update(cx, |this, cx| {
1836 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1837 })
1838 .await;
1839 }
1840 if let Some(workspace) = serialized_workspace.as_ref() {
1841 project_handle.update(cx, |this, cx| {
1842 for (scope, toolchains) in &workspace.user_toolchains {
1843 for toolchain in toolchains {
1844 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1845 }
1846 }
1847 });
1848 }
1849
1850 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1851 if let Some(window) = requesting_window {
1852 let centered_layout = serialized_workspace
1853 .as_ref()
1854 .map(|w| w.centered_layout)
1855 .unwrap_or(false);
1856
1857 let workspace = window.update(cx, |multi_workspace, window, cx| {
1858 let workspace = cx.new(|cx| {
1859 let mut workspace = Workspace::new(
1860 Some(workspace_id),
1861 project_handle.clone(),
1862 app_state.clone(),
1863 window,
1864 cx,
1865 );
1866
1867 workspace.centered_layout = centered_layout;
1868
1869 // Call init callback to add items before window renders
1870 if let Some(init) = init {
1871 init(&mut workspace, window, cx);
1872 }
1873
1874 workspace
1875 });
1876 if activate {
1877 multi_workspace.activate(workspace.clone(), cx);
1878 } else {
1879 multi_workspace.add_workspace(workspace.clone(), cx);
1880 }
1881 workspace
1882 })?;
1883 (window, workspace)
1884 } else {
1885 let window_bounds_override = window_bounds_env_override();
1886
1887 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1888 (Some(WindowBounds::Windowed(bounds)), None)
1889 } else if let Some(workspace) = serialized_workspace.as_ref()
1890 && let Some(display) = workspace.display
1891 && let Some(bounds) = workspace.window_bounds.as_ref()
1892 {
1893 // Reopening an existing workspace - restore its saved bounds
1894 (Some(bounds.0), Some(display))
1895 } else if let Some((display, bounds)) =
1896 persistence::read_default_window_bounds()
1897 {
1898 // New or empty workspace - use the last known window bounds
1899 (Some(bounds), Some(display))
1900 } else {
1901 // New window - let GPUI's default_bounds() handle cascading
1902 (None, None)
1903 };
1904
1905 // Use the serialized workspace to construct the new window
1906 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1907 options.window_bounds = window_bounds;
1908 let centered_layout = serialized_workspace
1909 .as_ref()
1910 .map(|w| w.centered_layout)
1911 .unwrap_or(false);
1912 let window = cx.open_window(options, {
1913 let app_state = app_state.clone();
1914 let project_handle = project_handle.clone();
1915 move |window, cx| {
1916 let workspace = cx.new(|cx| {
1917 let mut workspace = Workspace::new(
1918 Some(workspace_id),
1919 project_handle,
1920 app_state,
1921 window,
1922 cx,
1923 );
1924 workspace.centered_layout = centered_layout;
1925
1926 // Call init callback to add items before window renders
1927 if let Some(init) = init {
1928 init(&mut workspace, window, cx);
1929 }
1930
1931 workspace
1932 });
1933 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1934 }
1935 })?;
1936 let workspace =
1937 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
1938 multi_workspace.workspace().clone()
1939 })?;
1940 (window, workspace)
1941 };
1942
1943 notify_if_database_failed(window, cx);
1944 // Check if this is an empty workspace (no paths to open)
1945 // An empty workspace is one where project_paths is empty
1946 let is_empty_workspace = project_paths.is_empty();
1947 // Check if serialized workspace has paths before it's moved
1948 let serialized_workspace_has_paths = serialized_workspace
1949 .as_ref()
1950 .map(|ws| !ws.paths.is_empty())
1951 .unwrap_or(false);
1952
1953 let opened_items = window
1954 .update(cx, |_, window, cx| {
1955 workspace.update(cx, |_workspace: &mut Workspace, cx| {
1956 open_items(serialized_workspace, project_paths, window, cx)
1957 })
1958 })?
1959 .await
1960 .unwrap_or_default();
1961
1962 // Restore default dock state for empty workspaces
1963 // Only restore if:
1964 // 1. This is an empty workspace (no paths), AND
1965 // 2. The serialized workspace either doesn't exist or has no paths
1966 if is_empty_workspace && !serialized_workspace_has_paths {
1967 if let Some(default_docks) = persistence::read_default_dock_state() {
1968 window
1969 .update(cx, |_, window, cx| {
1970 workspace.update(cx, |workspace, cx| {
1971 for (dock, serialized_dock) in [
1972 (&workspace.right_dock, &default_docks.right),
1973 (&workspace.left_dock, &default_docks.left),
1974 (&workspace.bottom_dock, &default_docks.bottom),
1975 ] {
1976 dock.update(cx, |dock, cx| {
1977 dock.serialized_dock = Some(serialized_dock.clone());
1978 dock.restore_state(window, cx);
1979 });
1980 }
1981 cx.notify();
1982 });
1983 })
1984 .log_err();
1985 }
1986 }
1987
1988 window
1989 .update(cx, |_, _window, cx| {
1990 workspace.update(cx, |this: &mut Workspace, cx| {
1991 this.update_history(cx);
1992 });
1993 })
1994 .log_err();
1995 Ok(OpenResult {
1996 window,
1997 workspace,
1998 opened_items,
1999 })
2000 })
2001 }
2002
2003 pub fn weak_handle(&self) -> WeakEntity<Self> {
2004 self.weak_self.clone()
2005 }
2006
2007 pub fn left_dock(&self) -> &Entity<Dock> {
2008 &self.left_dock
2009 }
2010
2011 pub fn bottom_dock(&self) -> &Entity<Dock> {
2012 &self.bottom_dock
2013 }
2014
2015 pub fn set_bottom_dock_layout(
2016 &mut self,
2017 layout: BottomDockLayout,
2018 window: &mut Window,
2019 cx: &mut Context<Self>,
2020 ) {
2021 let fs = self.project().read(cx).fs();
2022 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2023 content.workspace.bottom_dock_layout = Some(layout);
2024 });
2025
2026 cx.notify();
2027 self.serialize_workspace(window, cx);
2028 }
2029
2030 pub fn right_dock(&self) -> &Entity<Dock> {
2031 &self.right_dock
2032 }
2033
2034 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2035 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2036 }
2037
2038 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2039 let left_dock = self.left_dock.read(cx);
2040 let left_visible = left_dock.is_open();
2041 let left_active_panel = left_dock
2042 .active_panel()
2043 .map(|panel| panel.persistent_name().to_string());
2044 // `zoomed_position` is kept in sync with individual panel zoom state
2045 // by the dock code in `Dock::new` and `Dock::add_panel`.
2046 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2047
2048 let right_dock = self.right_dock.read(cx);
2049 let right_visible = right_dock.is_open();
2050 let right_active_panel = right_dock
2051 .active_panel()
2052 .map(|panel| panel.persistent_name().to_string());
2053 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2054
2055 let bottom_dock = self.bottom_dock.read(cx);
2056 let bottom_visible = bottom_dock.is_open();
2057 let bottom_active_panel = bottom_dock
2058 .active_panel()
2059 .map(|panel| panel.persistent_name().to_string());
2060 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2061
2062 DockStructure {
2063 left: DockData {
2064 visible: left_visible,
2065 active_panel: left_active_panel,
2066 zoom: left_dock_zoom,
2067 },
2068 right: DockData {
2069 visible: right_visible,
2070 active_panel: right_active_panel,
2071 zoom: right_dock_zoom,
2072 },
2073 bottom: DockData {
2074 visible: bottom_visible,
2075 active_panel: bottom_active_panel,
2076 zoom: bottom_dock_zoom,
2077 },
2078 }
2079 }
2080
2081 pub fn set_dock_structure(
2082 &self,
2083 docks: DockStructure,
2084 window: &mut Window,
2085 cx: &mut Context<Self>,
2086 ) {
2087 for (dock, data) in [
2088 (&self.left_dock, docks.left),
2089 (&self.bottom_dock, docks.bottom),
2090 (&self.right_dock, docks.right),
2091 ] {
2092 dock.update(cx, |dock, cx| {
2093 dock.serialized_dock = Some(data);
2094 dock.restore_state(window, cx);
2095 });
2096 }
2097 }
2098
2099 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2100 self.items(cx)
2101 .filter_map(|item| {
2102 let project_path = item.project_path(cx)?;
2103 self.project.read(cx).absolute_path(&project_path, cx)
2104 })
2105 .collect()
2106 }
2107
2108 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2109 match position {
2110 DockPosition::Left => &self.left_dock,
2111 DockPosition::Bottom => &self.bottom_dock,
2112 DockPosition::Right => &self.right_dock,
2113 }
2114 }
2115
2116 pub fn is_edited(&self) -> bool {
2117 self.window_edited
2118 }
2119
2120 pub fn add_panel<T: Panel>(
2121 &mut self,
2122 panel: Entity<T>,
2123 window: &mut Window,
2124 cx: &mut Context<Self>,
2125 ) {
2126 let focus_handle = panel.panel_focus_handle(cx);
2127 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2128 .detach();
2129
2130 let dock_position = panel.position(window, cx);
2131 let dock = self.dock_at_position(dock_position);
2132 let any_panel = panel.to_any();
2133
2134 dock.update(cx, |dock, cx| {
2135 dock.add_panel(panel, self.weak_self.clone(), window, cx)
2136 });
2137
2138 cx.emit(Event::PanelAdded(any_panel));
2139 }
2140
2141 pub fn remove_panel<T: Panel>(
2142 &mut self,
2143 panel: &Entity<T>,
2144 window: &mut Window,
2145 cx: &mut Context<Self>,
2146 ) {
2147 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2148 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2149 }
2150 }
2151
2152 pub fn status_bar(&self) -> &Entity<StatusBar> {
2153 &self.status_bar
2154 }
2155
2156 pub fn status_bar_visible(&self, cx: &App) -> bool {
2157 StatusBarSettings::get_global(cx).show
2158 }
2159
2160 pub fn app_state(&self) -> &Arc<AppState> {
2161 &self.app_state
2162 }
2163
2164 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2165 self._panels_task = Some(task);
2166 }
2167
2168 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2169 self._panels_task.take()
2170 }
2171
2172 pub fn user_store(&self) -> &Entity<UserStore> {
2173 &self.app_state.user_store
2174 }
2175
2176 pub fn project(&self) -> &Entity<Project> {
2177 &self.project
2178 }
2179
2180 pub fn path_style(&self, cx: &App) -> PathStyle {
2181 self.project.read(cx).path_style(cx)
2182 }
2183
2184 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2185 let mut history: HashMap<EntityId, usize> = HashMap::default();
2186
2187 for pane_handle in &self.panes {
2188 let pane = pane_handle.read(cx);
2189
2190 for entry in pane.activation_history() {
2191 history.insert(
2192 entry.entity_id,
2193 history
2194 .get(&entry.entity_id)
2195 .cloned()
2196 .unwrap_or(0)
2197 .max(entry.timestamp),
2198 );
2199 }
2200 }
2201
2202 history
2203 }
2204
2205 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2206 let mut recent_item: Option<Entity<T>> = None;
2207 let mut recent_timestamp = 0;
2208 for pane_handle in &self.panes {
2209 let pane = pane_handle.read(cx);
2210 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2211 pane.items().map(|item| (item.item_id(), item)).collect();
2212 for entry in pane.activation_history() {
2213 if entry.timestamp > recent_timestamp
2214 && let Some(&item) = item_map.get(&entry.entity_id)
2215 && let Some(typed_item) = item.act_as::<T>(cx)
2216 {
2217 recent_timestamp = entry.timestamp;
2218 recent_item = Some(typed_item);
2219 }
2220 }
2221 }
2222 recent_item
2223 }
2224
2225 pub fn recent_navigation_history_iter(
2226 &self,
2227 cx: &App,
2228 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2229 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2230 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2231
2232 for pane in &self.panes {
2233 let pane = pane.read(cx);
2234
2235 pane.nav_history()
2236 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2237 if let Some(fs_path) = &fs_path {
2238 abs_paths_opened
2239 .entry(fs_path.clone())
2240 .or_default()
2241 .insert(project_path.clone());
2242 }
2243 let timestamp = entry.timestamp;
2244 match history.entry(project_path) {
2245 hash_map::Entry::Occupied(mut entry) => {
2246 let (_, old_timestamp) = entry.get();
2247 if ×tamp > old_timestamp {
2248 entry.insert((fs_path, timestamp));
2249 }
2250 }
2251 hash_map::Entry::Vacant(entry) => {
2252 entry.insert((fs_path, timestamp));
2253 }
2254 }
2255 });
2256
2257 if let Some(item) = pane.active_item()
2258 && let Some(project_path) = item.project_path(cx)
2259 {
2260 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2261
2262 if let Some(fs_path) = &fs_path {
2263 abs_paths_opened
2264 .entry(fs_path.clone())
2265 .or_default()
2266 .insert(project_path.clone());
2267 }
2268
2269 history.insert(project_path, (fs_path, std::usize::MAX));
2270 }
2271 }
2272
2273 history
2274 .into_iter()
2275 .sorted_by_key(|(_, (_, order))| *order)
2276 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2277 .rev()
2278 .filter(move |(history_path, abs_path)| {
2279 let latest_project_path_opened = abs_path
2280 .as_ref()
2281 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2282 .and_then(|project_paths| {
2283 project_paths
2284 .iter()
2285 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2286 });
2287
2288 latest_project_path_opened.is_none_or(|path| path == history_path)
2289 })
2290 }
2291
2292 pub fn recent_navigation_history(
2293 &self,
2294 limit: Option<usize>,
2295 cx: &App,
2296 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2297 self.recent_navigation_history_iter(cx)
2298 .take(limit.unwrap_or(usize::MAX))
2299 .collect()
2300 }
2301
2302 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2303 for pane in &self.panes {
2304 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2305 }
2306 }
2307
2308 fn navigate_history(
2309 &mut self,
2310 pane: WeakEntity<Pane>,
2311 mode: NavigationMode,
2312 window: &mut Window,
2313 cx: &mut Context<Workspace>,
2314 ) -> Task<Result<()>> {
2315 self.navigate_history_impl(
2316 pane,
2317 mode,
2318 window,
2319 &mut |history, cx| history.pop(mode, cx),
2320 cx,
2321 )
2322 }
2323
2324 fn navigate_tag_history(
2325 &mut self,
2326 pane: WeakEntity<Pane>,
2327 mode: TagNavigationMode,
2328 window: &mut Window,
2329 cx: &mut Context<Workspace>,
2330 ) -> Task<Result<()>> {
2331 self.navigate_history_impl(
2332 pane,
2333 NavigationMode::Normal,
2334 window,
2335 &mut |history, _cx| history.pop_tag(mode),
2336 cx,
2337 )
2338 }
2339
2340 fn navigate_history_impl(
2341 &mut self,
2342 pane: WeakEntity<Pane>,
2343 mode: NavigationMode,
2344 window: &mut Window,
2345 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2346 cx: &mut Context<Workspace>,
2347 ) -> Task<Result<()>> {
2348 let to_load = if let Some(pane) = pane.upgrade() {
2349 pane.update(cx, |pane, cx| {
2350 window.focus(&pane.focus_handle(cx), cx);
2351 loop {
2352 // Retrieve the weak item handle from the history.
2353 let entry = cb(pane.nav_history_mut(), cx)?;
2354
2355 // If the item is still present in this pane, then activate it.
2356 if let Some(index) = entry
2357 .item
2358 .upgrade()
2359 .and_then(|v| pane.index_for_item(v.as_ref()))
2360 {
2361 let prev_active_item_index = pane.active_item_index();
2362 pane.nav_history_mut().set_mode(mode);
2363 pane.activate_item(index, true, true, window, cx);
2364 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2365
2366 let mut navigated = prev_active_item_index != pane.active_item_index();
2367 if let Some(data) = entry.data {
2368 navigated |= pane.active_item()?.navigate(data, window, cx);
2369 }
2370
2371 if navigated {
2372 break None;
2373 }
2374 } else {
2375 // If the item is no longer present in this pane, then retrieve its
2376 // path info in order to reopen it.
2377 break pane
2378 .nav_history()
2379 .path_for_item(entry.item.id())
2380 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2381 }
2382 }
2383 })
2384 } else {
2385 None
2386 };
2387
2388 if let Some((project_path, abs_path, entry)) = to_load {
2389 // If the item was no longer present, then load it again from its previous path, first try the local path
2390 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2391
2392 cx.spawn_in(window, async move |workspace, cx| {
2393 let open_by_project_path = open_by_project_path.await;
2394 let mut navigated = false;
2395 match open_by_project_path
2396 .with_context(|| format!("Navigating to {project_path:?}"))
2397 {
2398 Ok((project_entry_id, build_item)) => {
2399 let prev_active_item_id = pane.update(cx, |pane, _| {
2400 pane.nav_history_mut().set_mode(mode);
2401 pane.active_item().map(|p| p.item_id())
2402 })?;
2403
2404 pane.update_in(cx, |pane, window, cx| {
2405 let item = pane.open_item(
2406 project_entry_id,
2407 project_path,
2408 true,
2409 entry.is_preview,
2410 true,
2411 None,
2412 window, cx,
2413 build_item,
2414 );
2415 navigated |= Some(item.item_id()) != prev_active_item_id;
2416 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2417 if let Some(data) = entry.data {
2418 navigated |= item.navigate(data, window, cx);
2419 }
2420 })?;
2421 }
2422 Err(open_by_project_path_e) => {
2423 // Fall back to opening by abs path, in case an external file was opened and closed,
2424 // and its worktree is now dropped
2425 if let Some(abs_path) = abs_path {
2426 let prev_active_item_id = pane.update(cx, |pane, _| {
2427 pane.nav_history_mut().set_mode(mode);
2428 pane.active_item().map(|p| p.item_id())
2429 })?;
2430 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2431 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2432 })?;
2433 match open_by_abs_path
2434 .await
2435 .with_context(|| format!("Navigating to {abs_path:?}"))
2436 {
2437 Ok(item) => {
2438 pane.update_in(cx, |pane, window, cx| {
2439 navigated |= Some(item.item_id()) != prev_active_item_id;
2440 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2441 if let Some(data) = entry.data {
2442 navigated |= item.navigate(data, window, cx);
2443 }
2444 })?;
2445 }
2446 Err(open_by_abs_path_e) => {
2447 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2448 }
2449 }
2450 }
2451 }
2452 }
2453
2454 if !navigated {
2455 workspace
2456 .update_in(cx, |workspace, window, cx| {
2457 Self::navigate_history(workspace, pane, mode, window, cx)
2458 })?
2459 .await?;
2460 }
2461
2462 Ok(())
2463 })
2464 } else {
2465 Task::ready(Ok(()))
2466 }
2467 }
2468
2469 pub fn go_back(
2470 &mut self,
2471 pane: WeakEntity<Pane>,
2472 window: &mut Window,
2473 cx: &mut Context<Workspace>,
2474 ) -> Task<Result<()>> {
2475 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2476 }
2477
2478 pub fn go_forward(
2479 &mut self,
2480 pane: WeakEntity<Pane>,
2481 window: &mut Window,
2482 cx: &mut Context<Workspace>,
2483 ) -> Task<Result<()>> {
2484 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2485 }
2486
2487 pub fn reopen_closed_item(
2488 &mut self,
2489 window: &mut Window,
2490 cx: &mut Context<Workspace>,
2491 ) -> Task<Result<()>> {
2492 self.navigate_history(
2493 self.active_pane().downgrade(),
2494 NavigationMode::ReopeningClosedItem,
2495 window,
2496 cx,
2497 )
2498 }
2499
2500 pub fn client(&self) -> &Arc<Client> {
2501 &self.app_state.client
2502 }
2503
2504 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2505 self.titlebar_item = Some(item);
2506 cx.notify();
2507 }
2508
2509 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2510 self.on_prompt_for_new_path = Some(prompt)
2511 }
2512
2513 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2514 self.on_prompt_for_open_path = Some(prompt)
2515 }
2516
2517 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2518 self.terminal_provider = Some(Box::new(provider));
2519 }
2520
2521 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2522 self.debugger_provider = Some(Arc::new(provider));
2523 }
2524
2525 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2526 self.debugger_provider.clone()
2527 }
2528
2529 pub fn prompt_for_open_path(
2530 &mut self,
2531 path_prompt_options: PathPromptOptions,
2532 lister: DirectoryLister,
2533 window: &mut Window,
2534 cx: &mut Context<Self>,
2535 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2536 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2537 let prompt = self.on_prompt_for_open_path.take().unwrap();
2538 let rx = prompt(self, lister, window, cx);
2539 self.on_prompt_for_open_path = Some(prompt);
2540 rx
2541 } else {
2542 let (tx, rx) = oneshot::channel();
2543 let abs_path = cx.prompt_for_paths(path_prompt_options);
2544
2545 cx.spawn_in(window, async move |workspace, cx| {
2546 let Ok(result) = abs_path.await else {
2547 return Ok(());
2548 };
2549
2550 match result {
2551 Ok(result) => {
2552 tx.send(result).ok();
2553 }
2554 Err(err) => {
2555 let rx = workspace.update_in(cx, |workspace, window, cx| {
2556 workspace.show_portal_error(err.to_string(), cx);
2557 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2558 let rx = prompt(workspace, lister, window, cx);
2559 workspace.on_prompt_for_open_path = Some(prompt);
2560 rx
2561 })?;
2562 if let Ok(path) = rx.await {
2563 tx.send(path).ok();
2564 }
2565 }
2566 };
2567 anyhow::Ok(())
2568 })
2569 .detach();
2570
2571 rx
2572 }
2573 }
2574
2575 pub fn prompt_for_new_path(
2576 &mut self,
2577 lister: DirectoryLister,
2578 suggested_name: Option<String>,
2579 window: &mut Window,
2580 cx: &mut Context<Self>,
2581 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2582 if self.project.read(cx).is_via_collab()
2583 || self.project.read(cx).is_via_remote_server()
2584 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2585 {
2586 let prompt = self.on_prompt_for_new_path.take().unwrap();
2587 let rx = prompt(self, lister, suggested_name, window, cx);
2588 self.on_prompt_for_new_path = Some(prompt);
2589 return rx;
2590 }
2591
2592 let (tx, rx) = oneshot::channel();
2593 cx.spawn_in(window, async move |workspace, cx| {
2594 let abs_path = workspace.update(cx, |workspace, cx| {
2595 let relative_to = workspace
2596 .most_recent_active_path(cx)
2597 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2598 .or_else(|| {
2599 let project = workspace.project.read(cx);
2600 project.visible_worktrees(cx).find_map(|worktree| {
2601 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2602 })
2603 })
2604 .or_else(std::env::home_dir)
2605 .unwrap_or_else(|| PathBuf::from(""));
2606 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2607 })?;
2608 let abs_path = match abs_path.await? {
2609 Ok(path) => path,
2610 Err(err) => {
2611 let rx = workspace.update_in(cx, |workspace, window, cx| {
2612 workspace.show_portal_error(err.to_string(), cx);
2613
2614 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2615 let rx = prompt(workspace, lister, suggested_name, window, cx);
2616 workspace.on_prompt_for_new_path = Some(prompt);
2617 rx
2618 })?;
2619 if let Ok(path) = rx.await {
2620 tx.send(path).ok();
2621 }
2622 return anyhow::Ok(());
2623 }
2624 };
2625
2626 tx.send(abs_path.map(|path| vec![path])).ok();
2627 anyhow::Ok(())
2628 })
2629 .detach();
2630
2631 rx
2632 }
2633
2634 pub fn titlebar_item(&self) -> Option<AnyView> {
2635 self.titlebar_item.clone()
2636 }
2637
2638 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2639 /// When set, git-related operations should use this worktree instead of deriving
2640 /// the active worktree from the focused file.
2641 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2642 self.active_worktree_override
2643 }
2644
2645 pub fn set_active_worktree_override(
2646 &mut self,
2647 worktree_id: Option<WorktreeId>,
2648 cx: &mut Context<Self>,
2649 ) {
2650 self.active_worktree_override = worktree_id;
2651 cx.notify();
2652 }
2653
2654 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2655 self.active_worktree_override = None;
2656 cx.notify();
2657 }
2658
2659 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2660 ///
2661 /// If the given workspace has a local project, then it will be passed
2662 /// to the callback. Otherwise, a new empty window will be created.
2663 pub fn with_local_workspace<T, F>(
2664 &mut self,
2665 window: &mut Window,
2666 cx: &mut Context<Self>,
2667 callback: F,
2668 ) -> Task<Result<T>>
2669 where
2670 T: 'static,
2671 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2672 {
2673 if self.project.read(cx).is_local() {
2674 Task::ready(Ok(callback(self, window, cx)))
2675 } else {
2676 let env = self.project.read(cx).cli_environment(cx);
2677 let task = Self::new_local(
2678 Vec::new(),
2679 self.app_state.clone(),
2680 None,
2681 env,
2682 None,
2683 true,
2684 cx,
2685 );
2686 cx.spawn_in(window, async move |_vh, cx| {
2687 let OpenResult {
2688 window: multi_workspace_window,
2689 ..
2690 } = task.await?;
2691 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2692 let workspace = multi_workspace.workspace().clone();
2693 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2694 })
2695 })
2696 }
2697 }
2698
2699 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2700 ///
2701 /// If the given workspace has a local project, then it will be passed
2702 /// to the callback. Otherwise, a new empty window will be created.
2703 pub fn with_local_or_wsl_workspace<T, F>(
2704 &mut self,
2705 window: &mut Window,
2706 cx: &mut Context<Self>,
2707 callback: F,
2708 ) -> Task<Result<T>>
2709 where
2710 T: 'static,
2711 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2712 {
2713 let project = self.project.read(cx);
2714 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
2715 Task::ready(Ok(callback(self, window, cx)))
2716 } else {
2717 let env = self.project.read(cx).cli_environment(cx);
2718 let task = Self::new_local(
2719 Vec::new(),
2720 self.app_state.clone(),
2721 None,
2722 env,
2723 None,
2724 true,
2725 cx,
2726 );
2727 cx.spawn_in(window, async move |_vh, cx| {
2728 let OpenResult {
2729 window: multi_workspace_window,
2730 ..
2731 } = task.await?;
2732 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2733 let workspace = multi_workspace.workspace().clone();
2734 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2735 })
2736 })
2737 }
2738 }
2739
2740 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2741 self.project.read(cx).worktrees(cx)
2742 }
2743
2744 pub fn visible_worktrees<'a>(
2745 &self,
2746 cx: &'a App,
2747 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2748 self.project.read(cx).visible_worktrees(cx)
2749 }
2750
2751 #[cfg(any(test, feature = "test-support"))]
2752 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
2753 let futures = self
2754 .worktrees(cx)
2755 .filter_map(|worktree| worktree.read(cx).as_local())
2756 .map(|worktree| worktree.scan_complete())
2757 .collect::<Vec<_>>();
2758 async move {
2759 for future in futures {
2760 future.await;
2761 }
2762 }
2763 }
2764
2765 pub fn close_global(cx: &mut App) {
2766 cx.defer(|cx| {
2767 cx.windows().iter().find(|window| {
2768 window
2769 .update(cx, |_, window, _| {
2770 if window.is_window_active() {
2771 //This can only get called when the window's project connection has been lost
2772 //so we don't need to prompt the user for anything and instead just close the window
2773 window.remove_window();
2774 true
2775 } else {
2776 false
2777 }
2778 })
2779 .unwrap_or(false)
2780 });
2781 });
2782 }
2783
2784 pub fn move_focused_panel_to_next_position(
2785 &mut self,
2786 _: &MoveFocusedPanelToNextPosition,
2787 window: &mut Window,
2788 cx: &mut Context<Self>,
2789 ) {
2790 let docks = self.all_docks();
2791 let active_dock = docks
2792 .into_iter()
2793 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
2794
2795 if let Some(dock) = active_dock {
2796 dock.update(cx, |dock, cx| {
2797 let active_panel = dock
2798 .active_panel()
2799 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
2800
2801 if let Some(panel) = active_panel {
2802 panel.move_to_next_position(window, cx);
2803 }
2804 })
2805 }
2806 }
2807
2808 pub fn prepare_to_close(
2809 &mut self,
2810 close_intent: CloseIntent,
2811 window: &mut Window,
2812 cx: &mut Context<Self>,
2813 ) -> Task<Result<bool>> {
2814 let active_call = self.active_global_call();
2815
2816 cx.spawn_in(window, async move |this, cx| {
2817 this.update(cx, |this, _| {
2818 if close_intent == CloseIntent::CloseWindow {
2819 this.removing = true;
2820 }
2821 })?;
2822
2823 let workspace_count = cx.update(|_window, cx| {
2824 cx.windows()
2825 .iter()
2826 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
2827 .count()
2828 })?;
2829
2830 #[cfg(target_os = "macos")]
2831 let save_last_workspace = false;
2832
2833 // On Linux and Windows, closing the last window should restore the last workspace.
2834 #[cfg(not(target_os = "macos"))]
2835 let save_last_workspace = {
2836 let remaining_workspaces = cx.update(|_window, cx| {
2837 cx.windows()
2838 .iter()
2839 .filter_map(|window| window.downcast::<MultiWorkspace>())
2840 .filter_map(|multi_workspace| {
2841 multi_workspace
2842 .update(cx, |multi_workspace, _, cx| {
2843 multi_workspace.workspace().read(cx).removing
2844 })
2845 .ok()
2846 })
2847 .filter(|removing| !removing)
2848 .count()
2849 })?;
2850
2851 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
2852 };
2853
2854 if let Some(active_call) = active_call
2855 && workspace_count == 1
2856 && cx
2857 .update(|_window, cx| active_call.0.is_in_room(cx))
2858 .unwrap_or(false)
2859 {
2860 if close_intent == CloseIntent::CloseWindow {
2861 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
2862 let answer = cx.update(|window, cx| {
2863 window.prompt(
2864 PromptLevel::Warning,
2865 "Do you want to leave the current call?",
2866 None,
2867 &["Close window and hang up", "Cancel"],
2868 cx,
2869 )
2870 })?;
2871
2872 if answer.await.log_err() == Some(1) {
2873 return anyhow::Ok(false);
2874 } else {
2875 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
2876 task.await.log_err();
2877 }
2878 }
2879 }
2880 if close_intent == CloseIntent::ReplaceWindow {
2881 _ = cx.update(|_window, cx| {
2882 let multi_workspace = cx
2883 .windows()
2884 .iter()
2885 .filter_map(|window| window.downcast::<MultiWorkspace>())
2886 .next()
2887 .unwrap();
2888 let project = multi_workspace
2889 .read(cx)?
2890 .workspace()
2891 .read(cx)
2892 .project
2893 .clone();
2894 if project.read(cx).is_shared() {
2895 active_call.0.unshare_project(project, cx)?;
2896 }
2897 Ok::<_, anyhow::Error>(())
2898 });
2899 }
2900 }
2901
2902 let save_result = this
2903 .update_in(cx, |this, window, cx| {
2904 this.save_all_internal(SaveIntent::Close, window, cx)
2905 })?
2906 .await;
2907
2908 // If we're not quitting, but closing, we remove the workspace from
2909 // the current session.
2910 if close_intent != CloseIntent::Quit
2911 && !save_last_workspace
2912 && save_result.as_ref().is_ok_and(|&res| res)
2913 {
2914 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
2915 .await;
2916 }
2917
2918 save_result
2919 })
2920 }
2921
2922 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
2923 self.save_all_internal(
2924 action.save_intent.unwrap_or(SaveIntent::SaveAll),
2925 window,
2926 cx,
2927 )
2928 .detach_and_log_err(cx);
2929 }
2930
2931 fn send_keystrokes(
2932 &mut self,
2933 action: &SendKeystrokes,
2934 window: &mut Window,
2935 cx: &mut Context<Self>,
2936 ) {
2937 let keystrokes: Vec<Keystroke> = action
2938 .0
2939 .split(' ')
2940 .flat_map(|k| Keystroke::parse(k).log_err())
2941 .map(|k| {
2942 cx.keyboard_mapper()
2943 .map_key_equivalent(k, false)
2944 .inner()
2945 .clone()
2946 })
2947 .collect();
2948 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
2949 }
2950
2951 pub fn send_keystrokes_impl(
2952 &mut self,
2953 keystrokes: Vec<Keystroke>,
2954 window: &mut Window,
2955 cx: &mut Context<Self>,
2956 ) -> Shared<Task<()>> {
2957 let mut state = self.dispatching_keystrokes.borrow_mut();
2958 if !state.dispatched.insert(keystrokes.clone()) {
2959 cx.propagate();
2960 return state.task.clone().unwrap();
2961 }
2962
2963 state.queue.extend(keystrokes);
2964
2965 let keystrokes = self.dispatching_keystrokes.clone();
2966 if state.task.is_none() {
2967 state.task = Some(
2968 window
2969 .spawn(cx, async move |cx| {
2970 // limit to 100 keystrokes to avoid infinite recursion.
2971 for _ in 0..100 {
2972 let keystroke = {
2973 let mut state = keystrokes.borrow_mut();
2974 let Some(keystroke) = state.queue.pop_front() else {
2975 state.dispatched.clear();
2976 state.task.take();
2977 return;
2978 };
2979 keystroke
2980 };
2981 cx.update(|window, cx| {
2982 let focused = window.focused(cx);
2983 window.dispatch_keystroke(keystroke.clone(), cx);
2984 if window.focused(cx) != focused {
2985 // dispatch_keystroke may cause the focus to change.
2986 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
2987 // And we need that to happen before the next keystroke to keep vim mode happy...
2988 // (Note that the tests always do this implicitly, so you must manually test with something like:
2989 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
2990 // )
2991 window.draw(cx).clear();
2992 }
2993 })
2994 .ok();
2995
2996 // Yield between synthetic keystrokes so deferred focus and
2997 // other effects can settle before dispatching the next key.
2998 yield_now().await;
2999 }
3000
3001 *keystrokes.borrow_mut() = Default::default();
3002 log::error!("over 100 keystrokes passed to send_keystrokes");
3003 })
3004 .shared(),
3005 );
3006 }
3007 state.task.clone().unwrap()
3008 }
3009
3010 fn save_all_internal(
3011 &mut self,
3012 mut save_intent: SaveIntent,
3013 window: &mut Window,
3014 cx: &mut Context<Self>,
3015 ) -> Task<Result<bool>> {
3016 if self.project.read(cx).is_disconnected(cx) {
3017 return Task::ready(Ok(true));
3018 }
3019 let dirty_items = self
3020 .panes
3021 .iter()
3022 .flat_map(|pane| {
3023 pane.read(cx).items().filter_map(|item| {
3024 if item.is_dirty(cx) {
3025 item.tab_content_text(0, cx);
3026 Some((pane.downgrade(), item.boxed_clone()))
3027 } else {
3028 None
3029 }
3030 })
3031 })
3032 .collect::<Vec<_>>();
3033
3034 let project = self.project.clone();
3035 cx.spawn_in(window, async move |workspace, cx| {
3036 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3037 let (serialize_tasks, remaining_dirty_items) =
3038 workspace.update_in(cx, |workspace, window, cx| {
3039 let mut remaining_dirty_items = Vec::new();
3040 let mut serialize_tasks = Vec::new();
3041 for (pane, item) in dirty_items {
3042 if let Some(task) = item
3043 .to_serializable_item_handle(cx)
3044 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3045 {
3046 serialize_tasks.push(task);
3047 } else {
3048 remaining_dirty_items.push((pane, item));
3049 }
3050 }
3051 (serialize_tasks, remaining_dirty_items)
3052 })?;
3053
3054 futures::future::try_join_all(serialize_tasks).await?;
3055
3056 if !remaining_dirty_items.is_empty() {
3057 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3058 }
3059
3060 if remaining_dirty_items.len() > 1 {
3061 let answer = workspace.update_in(cx, |_, window, cx| {
3062 let detail = Pane::file_names_for_prompt(
3063 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3064 cx,
3065 );
3066 window.prompt(
3067 PromptLevel::Warning,
3068 "Do you want to save all changes in the following files?",
3069 Some(&detail),
3070 &["Save all", "Discard all", "Cancel"],
3071 cx,
3072 )
3073 })?;
3074 match answer.await.log_err() {
3075 Some(0) => save_intent = SaveIntent::SaveAll,
3076 Some(1) => save_intent = SaveIntent::Skip,
3077 Some(2) => return Ok(false),
3078 _ => {}
3079 }
3080 }
3081
3082 remaining_dirty_items
3083 } else {
3084 dirty_items
3085 };
3086
3087 for (pane, item) in dirty_items {
3088 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3089 (
3090 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3091 item.project_entry_ids(cx),
3092 )
3093 })?;
3094 if (singleton || !project_entry_ids.is_empty())
3095 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3096 {
3097 return Ok(false);
3098 }
3099 }
3100 Ok(true)
3101 })
3102 }
3103
3104 pub fn open_workspace_for_paths(
3105 &mut self,
3106 replace_current_window: bool,
3107 paths: Vec<PathBuf>,
3108 window: &mut Window,
3109 cx: &mut Context<Self>,
3110 ) -> Task<Result<Entity<Workspace>>> {
3111 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
3112 let is_remote = self.project.read(cx).is_via_collab();
3113 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3114 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3115
3116 let window_to_replace = if replace_current_window {
3117 window_handle
3118 } else if is_remote || has_worktree || has_dirty_items {
3119 None
3120 } else {
3121 window_handle
3122 };
3123 let app_state = self.app_state.clone();
3124
3125 cx.spawn(async move |_, cx| {
3126 let OpenResult { workspace, .. } = cx
3127 .update(|cx| {
3128 open_paths(
3129 &paths,
3130 app_state,
3131 OpenOptions {
3132 replace_window: window_to_replace,
3133 ..Default::default()
3134 },
3135 cx,
3136 )
3137 })
3138 .await?;
3139 Ok(workspace)
3140 })
3141 }
3142
3143 #[allow(clippy::type_complexity)]
3144 pub fn open_paths(
3145 &mut self,
3146 mut abs_paths: Vec<PathBuf>,
3147 options: OpenOptions,
3148 pane: Option<WeakEntity<Pane>>,
3149 window: &mut Window,
3150 cx: &mut Context<Self>,
3151 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3152 let fs = self.app_state.fs.clone();
3153
3154 let caller_ordered_abs_paths = abs_paths.clone();
3155
3156 // Sort the paths to ensure we add worktrees for parents before their children.
3157 abs_paths.sort_unstable();
3158 cx.spawn_in(window, async move |this, cx| {
3159 let mut tasks = Vec::with_capacity(abs_paths.len());
3160
3161 for abs_path in &abs_paths {
3162 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3163 OpenVisible::All => Some(true),
3164 OpenVisible::None => Some(false),
3165 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3166 Some(Some(metadata)) => Some(!metadata.is_dir),
3167 Some(None) => Some(true),
3168 None => None,
3169 },
3170 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3171 Some(Some(metadata)) => Some(metadata.is_dir),
3172 Some(None) => Some(false),
3173 None => None,
3174 },
3175 };
3176 let project_path = match visible {
3177 Some(visible) => match this
3178 .update(cx, |this, cx| {
3179 Workspace::project_path_for_path(
3180 this.project.clone(),
3181 abs_path,
3182 visible,
3183 cx,
3184 )
3185 })
3186 .log_err()
3187 {
3188 Some(project_path) => project_path.await.log_err(),
3189 None => None,
3190 },
3191 None => None,
3192 };
3193
3194 let this = this.clone();
3195 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3196 let fs = fs.clone();
3197 let pane = pane.clone();
3198 let task = cx.spawn(async move |cx| {
3199 let (_worktree, project_path) = project_path?;
3200 if fs.is_dir(&abs_path).await {
3201 // Opening a directory should not race to update the active entry.
3202 // We'll select/reveal a deterministic final entry after all paths finish opening.
3203 None
3204 } else {
3205 Some(
3206 this.update_in(cx, |this, window, cx| {
3207 this.open_path(
3208 project_path,
3209 pane,
3210 options.focus.unwrap_or(true),
3211 window,
3212 cx,
3213 )
3214 })
3215 .ok()?
3216 .await,
3217 )
3218 }
3219 });
3220 tasks.push(task);
3221 }
3222
3223 let results = futures::future::join_all(tasks).await;
3224
3225 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3226 let mut winner: Option<(PathBuf, bool)> = None;
3227 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3228 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3229 if !metadata.is_dir {
3230 winner = Some((abs_path, false));
3231 break;
3232 }
3233 if winner.is_none() {
3234 winner = Some((abs_path, true));
3235 }
3236 } else if winner.is_none() {
3237 winner = Some((abs_path, false));
3238 }
3239 }
3240
3241 // Compute the winner entry id on the foreground thread and emit once, after all
3242 // paths finish opening. This avoids races between concurrently-opening paths
3243 // (directories in particular) and makes the resulting project panel selection
3244 // deterministic.
3245 if let Some((winner_abs_path, winner_is_dir)) = winner {
3246 'emit_winner: {
3247 let winner_abs_path: Arc<Path> =
3248 SanitizedPath::new(&winner_abs_path).as_path().into();
3249
3250 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3251 OpenVisible::All => true,
3252 OpenVisible::None => false,
3253 OpenVisible::OnlyFiles => !winner_is_dir,
3254 OpenVisible::OnlyDirectories => winner_is_dir,
3255 };
3256
3257 let Some(worktree_task) = this
3258 .update(cx, |workspace, cx| {
3259 workspace.project.update(cx, |project, cx| {
3260 project.find_or_create_worktree(
3261 winner_abs_path.as_ref(),
3262 visible,
3263 cx,
3264 )
3265 })
3266 })
3267 .ok()
3268 else {
3269 break 'emit_winner;
3270 };
3271
3272 let Ok((worktree, _)) = worktree_task.await else {
3273 break 'emit_winner;
3274 };
3275
3276 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3277 let worktree = worktree.read(cx);
3278 let worktree_abs_path = worktree.abs_path();
3279 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3280 worktree.root_entry()
3281 } else {
3282 winner_abs_path
3283 .strip_prefix(worktree_abs_path.as_ref())
3284 .ok()
3285 .and_then(|relative_path| {
3286 let relative_path =
3287 RelPath::new(relative_path, PathStyle::local())
3288 .log_err()?;
3289 worktree.entry_for_path(&relative_path)
3290 })
3291 }?;
3292 Some(entry.id)
3293 }) else {
3294 break 'emit_winner;
3295 };
3296
3297 this.update(cx, |workspace, cx| {
3298 workspace.project.update(cx, |_, cx| {
3299 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3300 });
3301 })
3302 .ok();
3303 }
3304 }
3305
3306 results
3307 })
3308 }
3309
3310 pub fn open_resolved_path(
3311 &mut self,
3312 path: ResolvedPath,
3313 window: &mut Window,
3314 cx: &mut Context<Self>,
3315 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3316 match path {
3317 ResolvedPath::ProjectPath { project_path, .. } => {
3318 self.open_path(project_path, None, true, window, cx)
3319 }
3320 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3321 PathBuf::from(path),
3322 OpenOptions {
3323 visible: Some(OpenVisible::None),
3324 ..Default::default()
3325 },
3326 window,
3327 cx,
3328 ),
3329 }
3330 }
3331
3332 pub fn absolute_path_of_worktree(
3333 &self,
3334 worktree_id: WorktreeId,
3335 cx: &mut Context<Self>,
3336 ) -> Option<PathBuf> {
3337 self.project
3338 .read(cx)
3339 .worktree_for_id(worktree_id, cx)
3340 // TODO: use `abs_path` or `root_dir`
3341 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3342 }
3343
3344 fn add_folder_to_project(
3345 &mut self,
3346 _: &AddFolderToProject,
3347 window: &mut Window,
3348 cx: &mut Context<Self>,
3349 ) {
3350 let project = self.project.read(cx);
3351 if project.is_via_collab() {
3352 self.show_error(
3353 &anyhow!("You cannot add folders to someone else's project"),
3354 cx,
3355 );
3356 return;
3357 }
3358 let paths = self.prompt_for_open_path(
3359 PathPromptOptions {
3360 files: false,
3361 directories: true,
3362 multiple: true,
3363 prompt: None,
3364 },
3365 DirectoryLister::Project(self.project.clone()),
3366 window,
3367 cx,
3368 );
3369 cx.spawn_in(window, async move |this, cx| {
3370 if let Some(paths) = paths.await.log_err().flatten() {
3371 let results = this
3372 .update_in(cx, |this, window, cx| {
3373 this.open_paths(
3374 paths,
3375 OpenOptions {
3376 visible: Some(OpenVisible::All),
3377 ..Default::default()
3378 },
3379 None,
3380 window,
3381 cx,
3382 )
3383 })?
3384 .await;
3385 for result in results.into_iter().flatten() {
3386 result.log_err();
3387 }
3388 }
3389 anyhow::Ok(())
3390 })
3391 .detach_and_log_err(cx);
3392 }
3393
3394 pub fn project_path_for_path(
3395 project: Entity<Project>,
3396 abs_path: &Path,
3397 visible: bool,
3398 cx: &mut App,
3399 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3400 let entry = project.update(cx, |project, cx| {
3401 project.find_or_create_worktree(abs_path, visible, cx)
3402 });
3403 cx.spawn(async move |cx| {
3404 let (worktree, path) = entry.await?;
3405 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3406 Ok((worktree, ProjectPath { worktree_id, path }))
3407 })
3408 }
3409
3410 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3411 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3412 }
3413
3414 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3415 self.items_of_type(cx).max_by_key(|item| item.item_id())
3416 }
3417
3418 pub fn items_of_type<'a, T: Item>(
3419 &'a self,
3420 cx: &'a App,
3421 ) -> impl 'a + Iterator<Item = Entity<T>> {
3422 self.panes
3423 .iter()
3424 .flat_map(|pane| pane.read(cx).items_of_type())
3425 }
3426
3427 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3428 self.active_pane().read(cx).active_item()
3429 }
3430
3431 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3432 let item = self.active_item(cx)?;
3433 item.to_any_view().downcast::<I>().ok()
3434 }
3435
3436 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3437 self.active_item(cx).and_then(|item| item.project_path(cx))
3438 }
3439
3440 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3441 self.recent_navigation_history_iter(cx)
3442 .filter_map(|(path, abs_path)| {
3443 let worktree = self
3444 .project
3445 .read(cx)
3446 .worktree_for_id(path.worktree_id, cx)?;
3447 if worktree.read(cx).is_visible() {
3448 abs_path
3449 } else {
3450 None
3451 }
3452 })
3453 .next()
3454 }
3455
3456 pub fn save_active_item(
3457 &mut self,
3458 save_intent: SaveIntent,
3459 window: &mut Window,
3460 cx: &mut App,
3461 ) -> Task<Result<()>> {
3462 let project = self.project.clone();
3463 let pane = self.active_pane();
3464 let item = pane.read(cx).active_item();
3465 let pane = pane.downgrade();
3466
3467 window.spawn(cx, async move |cx| {
3468 if let Some(item) = item {
3469 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3470 .await
3471 .map(|_| ())
3472 } else {
3473 Ok(())
3474 }
3475 })
3476 }
3477
3478 pub fn close_inactive_items_and_panes(
3479 &mut self,
3480 action: &CloseInactiveTabsAndPanes,
3481 window: &mut Window,
3482 cx: &mut Context<Self>,
3483 ) {
3484 if let Some(task) = self.close_all_internal(
3485 true,
3486 action.save_intent.unwrap_or(SaveIntent::Close),
3487 window,
3488 cx,
3489 ) {
3490 task.detach_and_log_err(cx)
3491 }
3492 }
3493
3494 pub fn close_all_items_and_panes(
3495 &mut self,
3496 action: &CloseAllItemsAndPanes,
3497 window: &mut Window,
3498 cx: &mut Context<Self>,
3499 ) {
3500 if let Some(task) = self.close_all_internal(
3501 false,
3502 action.save_intent.unwrap_or(SaveIntent::Close),
3503 window,
3504 cx,
3505 ) {
3506 task.detach_and_log_err(cx)
3507 }
3508 }
3509
3510 /// Closes the active item across all panes.
3511 pub fn close_item_in_all_panes(
3512 &mut self,
3513 action: &CloseItemInAllPanes,
3514 window: &mut Window,
3515 cx: &mut Context<Self>,
3516 ) {
3517 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3518 return;
3519 };
3520
3521 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3522 let close_pinned = action.close_pinned;
3523
3524 if let Some(project_path) = active_item.project_path(cx) {
3525 self.close_items_with_project_path(
3526 &project_path,
3527 save_intent,
3528 close_pinned,
3529 window,
3530 cx,
3531 );
3532 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3533 let item_id = active_item.item_id();
3534 self.active_pane().update(cx, |pane, cx| {
3535 pane.close_item_by_id(item_id, save_intent, window, cx)
3536 .detach_and_log_err(cx);
3537 });
3538 }
3539 }
3540
3541 /// Closes all items with the given project path across all panes.
3542 pub fn close_items_with_project_path(
3543 &mut self,
3544 project_path: &ProjectPath,
3545 save_intent: SaveIntent,
3546 close_pinned: bool,
3547 window: &mut Window,
3548 cx: &mut Context<Self>,
3549 ) {
3550 let panes = self.panes().to_vec();
3551 for pane in panes {
3552 pane.update(cx, |pane, cx| {
3553 pane.close_items_for_project_path(
3554 project_path,
3555 save_intent,
3556 close_pinned,
3557 window,
3558 cx,
3559 )
3560 .detach_and_log_err(cx);
3561 });
3562 }
3563 }
3564
3565 fn close_all_internal(
3566 &mut self,
3567 retain_active_pane: bool,
3568 save_intent: SaveIntent,
3569 window: &mut Window,
3570 cx: &mut Context<Self>,
3571 ) -> Option<Task<Result<()>>> {
3572 let current_pane = self.active_pane();
3573
3574 let mut tasks = Vec::new();
3575
3576 if retain_active_pane {
3577 let current_pane_close = current_pane.update(cx, |pane, cx| {
3578 pane.close_other_items(
3579 &CloseOtherItems {
3580 save_intent: None,
3581 close_pinned: false,
3582 },
3583 None,
3584 window,
3585 cx,
3586 )
3587 });
3588
3589 tasks.push(current_pane_close);
3590 }
3591
3592 for pane in self.panes() {
3593 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3594 continue;
3595 }
3596
3597 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3598 pane.close_all_items(
3599 &CloseAllItems {
3600 save_intent: Some(save_intent),
3601 close_pinned: false,
3602 },
3603 window,
3604 cx,
3605 )
3606 });
3607
3608 tasks.push(close_pane_items)
3609 }
3610
3611 if tasks.is_empty() {
3612 None
3613 } else {
3614 Some(cx.spawn_in(window, async move |_, _| {
3615 for task in tasks {
3616 task.await?
3617 }
3618 Ok(())
3619 }))
3620 }
3621 }
3622
3623 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3624 self.dock_at_position(position).read(cx).is_open()
3625 }
3626
3627 pub fn toggle_dock(
3628 &mut self,
3629 dock_side: DockPosition,
3630 window: &mut Window,
3631 cx: &mut Context<Self>,
3632 ) {
3633 let mut focus_center = false;
3634 let mut reveal_dock = false;
3635
3636 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3637 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3638
3639 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3640 telemetry::event!(
3641 "Panel Button Clicked",
3642 name = panel.persistent_name(),
3643 toggle_state = !was_visible
3644 );
3645 }
3646 if was_visible {
3647 self.save_open_dock_positions(cx);
3648 }
3649
3650 let dock = self.dock_at_position(dock_side);
3651 dock.update(cx, |dock, cx| {
3652 dock.set_open(!was_visible, window, cx);
3653
3654 if dock.active_panel().is_none() {
3655 let Some(panel_ix) = dock
3656 .first_enabled_panel_idx(cx)
3657 .log_with_level(log::Level::Info)
3658 else {
3659 return;
3660 };
3661 dock.activate_panel(panel_ix, window, cx);
3662 }
3663
3664 if let Some(active_panel) = dock.active_panel() {
3665 if was_visible {
3666 if active_panel
3667 .panel_focus_handle(cx)
3668 .contains_focused(window, cx)
3669 {
3670 focus_center = true;
3671 }
3672 } else {
3673 let focus_handle = &active_panel.panel_focus_handle(cx);
3674 window.focus(focus_handle, cx);
3675 reveal_dock = true;
3676 }
3677 }
3678 });
3679
3680 if reveal_dock {
3681 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3682 }
3683
3684 if focus_center {
3685 self.active_pane
3686 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3687 }
3688
3689 cx.notify();
3690 self.serialize_workspace(window, cx);
3691 }
3692
3693 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3694 self.all_docks().into_iter().find(|&dock| {
3695 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3696 })
3697 }
3698
3699 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3700 if let Some(dock) = self.active_dock(window, cx).cloned() {
3701 self.save_open_dock_positions(cx);
3702 dock.update(cx, |dock, cx| {
3703 dock.set_open(false, window, cx);
3704 });
3705 return true;
3706 }
3707 false
3708 }
3709
3710 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3711 self.save_open_dock_positions(cx);
3712 for dock in self.all_docks() {
3713 dock.update(cx, |dock, cx| {
3714 dock.set_open(false, window, cx);
3715 });
3716 }
3717
3718 cx.focus_self(window);
3719 cx.notify();
3720 self.serialize_workspace(window, cx);
3721 }
3722
3723 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
3724 self.all_docks()
3725 .into_iter()
3726 .filter_map(|dock| {
3727 let dock_ref = dock.read(cx);
3728 if dock_ref.is_open() {
3729 Some(dock_ref.position())
3730 } else {
3731 None
3732 }
3733 })
3734 .collect()
3735 }
3736
3737 /// Saves the positions of currently open docks.
3738 ///
3739 /// Updates `last_open_dock_positions` with positions of all currently open
3740 /// docks, to later be restored by the 'Toggle All Docks' action.
3741 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
3742 let open_dock_positions = self.get_open_dock_positions(cx);
3743 if !open_dock_positions.is_empty() {
3744 self.last_open_dock_positions = open_dock_positions;
3745 }
3746 }
3747
3748 /// Toggles all docks between open and closed states.
3749 ///
3750 /// If any docks are open, closes all and remembers their positions. If all
3751 /// docks are closed, restores the last remembered dock configuration.
3752 fn toggle_all_docks(
3753 &mut self,
3754 _: &ToggleAllDocks,
3755 window: &mut Window,
3756 cx: &mut Context<Self>,
3757 ) {
3758 let open_dock_positions = self.get_open_dock_positions(cx);
3759
3760 if !open_dock_positions.is_empty() {
3761 self.close_all_docks(window, cx);
3762 } else if !self.last_open_dock_positions.is_empty() {
3763 self.restore_last_open_docks(window, cx);
3764 }
3765 }
3766
3767 /// Reopens docks from the most recently remembered configuration.
3768 ///
3769 /// Opens all docks whose positions are stored in `last_open_dock_positions`
3770 /// and clears the stored positions.
3771 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3772 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
3773
3774 for position in positions_to_open {
3775 let dock = self.dock_at_position(position);
3776 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
3777 }
3778
3779 cx.focus_self(window);
3780 cx.notify();
3781 self.serialize_workspace(window, cx);
3782 }
3783
3784 /// Transfer focus to the panel of the given type.
3785 pub fn focus_panel<T: Panel>(
3786 &mut self,
3787 window: &mut Window,
3788 cx: &mut Context<Self>,
3789 ) -> Option<Entity<T>> {
3790 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
3791 panel.to_any().downcast().ok()
3792 }
3793
3794 /// Focus the panel of the given type if it isn't already focused. If it is
3795 /// already focused, then transfer focus back to the workspace center.
3796 /// When the `close_panel_on_toggle` setting is enabled, also closes the
3797 /// panel when transferring focus back to the center.
3798 pub fn toggle_panel_focus<T: Panel>(
3799 &mut self,
3800 window: &mut Window,
3801 cx: &mut Context<Self>,
3802 ) -> bool {
3803 let mut did_focus_panel = false;
3804 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
3805 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
3806 did_focus_panel
3807 });
3808
3809 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
3810 self.close_panel::<T>(window, cx);
3811 }
3812
3813 telemetry::event!(
3814 "Panel Button Clicked",
3815 name = T::persistent_name(),
3816 toggle_state = did_focus_panel
3817 );
3818
3819 did_focus_panel
3820 }
3821
3822 pub fn activate_panel_for_proto_id(
3823 &mut self,
3824 panel_id: PanelId,
3825 window: &mut Window,
3826 cx: &mut Context<Self>,
3827 ) -> Option<Arc<dyn PanelHandle>> {
3828 let mut panel = None;
3829 for dock in self.all_docks() {
3830 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
3831 panel = dock.update(cx, |dock, cx| {
3832 dock.activate_panel(panel_index, window, cx);
3833 dock.set_open(true, window, cx);
3834 dock.active_panel().cloned()
3835 });
3836 break;
3837 }
3838 }
3839
3840 if panel.is_some() {
3841 cx.notify();
3842 self.serialize_workspace(window, cx);
3843 }
3844
3845 panel
3846 }
3847
3848 /// Focus or unfocus the given panel type, depending on the given callback.
3849 fn focus_or_unfocus_panel<T: Panel>(
3850 &mut self,
3851 window: &mut Window,
3852 cx: &mut Context<Self>,
3853 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
3854 ) -> Option<Arc<dyn PanelHandle>> {
3855 let mut result_panel = None;
3856 let mut serialize = false;
3857 for dock in self.all_docks() {
3858 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3859 let mut focus_center = false;
3860 let panel = dock.update(cx, |dock, cx| {
3861 dock.activate_panel(panel_index, window, cx);
3862
3863 let panel = dock.active_panel().cloned();
3864 if let Some(panel) = panel.as_ref() {
3865 if should_focus(&**panel, window, cx) {
3866 dock.set_open(true, window, cx);
3867 panel.panel_focus_handle(cx).focus(window, cx);
3868 } else {
3869 focus_center = true;
3870 }
3871 }
3872 panel
3873 });
3874
3875 if focus_center {
3876 self.active_pane
3877 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3878 }
3879
3880 result_panel = panel;
3881 serialize = true;
3882 break;
3883 }
3884 }
3885
3886 if serialize {
3887 self.serialize_workspace(window, cx);
3888 }
3889
3890 cx.notify();
3891 result_panel
3892 }
3893
3894 /// Open the panel of the given type
3895 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3896 for dock in self.all_docks() {
3897 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3898 dock.update(cx, |dock, cx| {
3899 dock.activate_panel(panel_index, window, cx);
3900 dock.set_open(true, window, cx);
3901 });
3902 }
3903 }
3904 }
3905
3906 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
3907 for dock in self.all_docks().iter() {
3908 dock.update(cx, |dock, cx| {
3909 if dock.panel::<T>().is_some() {
3910 dock.set_open(false, window, cx)
3911 }
3912 })
3913 }
3914 }
3915
3916 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
3917 self.all_docks()
3918 .iter()
3919 .find_map(|dock| dock.read(cx).panel::<T>())
3920 }
3921
3922 fn dismiss_zoomed_items_to_reveal(
3923 &mut self,
3924 dock_to_reveal: Option<DockPosition>,
3925 window: &mut Window,
3926 cx: &mut Context<Self>,
3927 ) {
3928 // If a center pane is zoomed, unzoom it.
3929 for pane in &self.panes {
3930 if pane != &self.active_pane || dock_to_reveal.is_some() {
3931 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
3932 }
3933 }
3934
3935 // If another dock is zoomed, hide it.
3936 let mut focus_center = false;
3937 for dock in self.all_docks() {
3938 dock.update(cx, |dock, cx| {
3939 if Some(dock.position()) != dock_to_reveal
3940 && let Some(panel) = dock.active_panel()
3941 && panel.is_zoomed(window, cx)
3942 {
3943 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
3944 dock.set_open(false, window, cx);
3945 }
3946 });
3947 }
3948
3949 if focus_center {
3950 self.active_pane
3951 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3952 }
3953
3954 if self.zoomed_position != dock_to_reveal {
3955 self.zoomed = None;
3956 self.zoomed_position = None;
3957 cx.emit(Event::ZoomChanged);
3958 }
3959
3960 cx.notify();
3961 }
3962
3963 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
3964 let pane = cx.new(|cx| {
3965 let mut pane = Pane::new(
3966 self.weak_handle(),
3967 self.project.clone(),
3968 self.pane_history_timestamp.clone(),
3969 None,
3970 NewFile.boxed_clone(),
3971 true,
3972 window,
3973 cx,
3974 );
3975 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
3976 pane
3977 });
3978 cx.subscribe_in(&pane, window, Self::handle_pane_event)
3979 .detach();
3980 self.panes.push(pane.clone());
3981
3982 window.focus(&pane.focus_handle(cx), cx);
3983
3984 cx.emit(Event::PaneAdded(pane.clone()));
3985 pane
3986 }
3987
3988 pub fn add_item_to_center(
3989 &mut self,
3990 item: Box<dyn ItemHandle>,
3991 window: &mut Window,
3992 cx: &mut Context<Self>,
3993 ) -> bool {
3994 if let Some(center_pane) = self.last_active_center_pane.clone() {
3995 if let Some(center_pane) = center_pane.upgrade() {
3996 center_pane.update(cx, |pane, cx| {
3997 pane.add_item(item, true, true, None, window, cx)
3998 });
3999 true
4000 } else {
4001 false
4002 }
4003 } else {
4004 false
4005 }
4006 }
4007
4008 pub fn add_item_to_active_pane(
4009 &mut self,
4010 item: Box<dyn ItemHandle>,
4011 destination_index: Option<usize>,
4012 focus_item: bool,
4013 window: &mut Window,
4014 cx: &mut App,
4015 ) {
4016 self.add_item(
4017 self.active_pane.clone(),
4018 item,
4019 destination_index,
4020 false,
4021 focus_item,
4022 window,
4023 cx,
4024 )
4025 }
4026
4027 pub fn add_item(
4028 &mut self,
4029 pane: Entity<Pane>,
4030 item: Box<dyn ItemHandle>,
4031 destination_index: Option<usize>,
4032 activate_pane: bool,
4033 focus_item: bool,
4034 window: &mut Window,
4035 cx: &mut App,
4036 ) {
4037 pane.update(cx, |pane, cx| {
4038 pane.add_item(
4039 item,
4040 activate_pane,
4041 focus_item,
4042 destination_index,
4043 window,
4044 cx,
4045 )
4046 });
4047 }
4048
4049 pub fn split_item(
4050 &mut self,
4051 split_direction: SplitDirection,
4052 item: Box<dyn ItemHandle>,
4053 window: &mut Window,
4054 cx: &mut Context<Self>,
4055 ) {
4056 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4057 self.add_item(new_pane, item, None, true, true, window, cx);
4058 }
4059
4060 pub fn open_abs_path(
4061 &mut self,
4062 abs_path: PathBuf,
4063 options: OpenOptions,
4064 window: &mut Window,
4065 cx: &mut Context<Self>,
4066 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4067 cx.spawn_in(window, async move |workspace, cx| {
4068 let open_paths_task_result = workspace
4069 .update_in(cx, |workspace, window, cx| {
4070 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4071 })
4072 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4073 .await;
4074 anyhow::ensure!(
4075 open_paths_task_result.len() == 1,
4076 "open abs path {abs_path:?} task returned incorrect number of results"
4077 );
4078 match open_paths_task_result
4079 .into_iter()
4080 .next()
4081 .expect("ensured single task result")
4082 {
4083 Some(open_result) => {
4084 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4085 }
4086 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4087 }
4088 })
4089 }
4090
4091 pub fn split_abs_path(
4092 &mut self,
4093 abs_path: PathBuf,
4094 visible: bool,
4095 window: &mut Window,
4096 cx: &mut Context<Self>,
4097 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4098 let project_path_task =
4099 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4100 cx.spawn_in(window, async move |this, cx| {
4101 let (_, path) = project_path_task.await?;
4102 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4103 .await
4104 })
4105 }
4106
4107 pub fn open_path(
4108 &mut self,
4109 path: impl Into<ProjectPath>,
4110 pane: Option<WeakEntity<Pane>>,
4111 focus_item: bool,
4112 window: &mut Window,
4113 cx: &mut App,
4114 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4115 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4116 }
4117
4118 pub fn open_path_preview(
4119 &mut self,
4120 path: impl Into<ProjectPath>,
4121 pane: Option<WeakEntity<Pane>>,
4122 focus_item: bool,
4123 allow_preview: bool,
4124 activate: bool,
4125 window: &mut Window,
4126 cx: &mut App,
4127 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4128 let pane = pane.unwrap_or_else(|| {
4129 self.last_active_center_pane.clone().unwrap_or_else(|| {
4130 self.panes
4131 .first()
4132 .expect("There must be an active pane")
4133 .downgrade()
4134 })
4135 });
4136
4137 let project_path = path.into();
4138 let task = self.load_path(project_path.clone(), window, cx);
4139 window.spawn(cx, async move |cx| {
4140 let (project_entry_id, build_item) = task.await?;
4141
4142 pane.update_in(cx, |pane, window, cx| {
4143 pane.open_item(
4144 project_entry_id,
4145 project_path,
4146 focus_item,
4147 allow_preview,
4148 activate,
4149 None,
4150 window,
4151 cx,
4152 build_item,
4153 )
4154 })
4155 })
4156 }
4157
4158 pub fn split_path(
4159 &mut self,
4160 path: impl Into<ProjectPath>,
4161 window: &mut Window,
4162 cx: &mut Context<Self>,
4163 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4164 self.split_path_preview(path, false, None, window, cx)
4165 }
4166
4167 pub fn split_path_preview(
4168 &mut self,
4169 path: impl Into<ProjectPath>,
4170 allow_preview: bool,
4171 split_direction: Option<SplitDirection>,
4172 window: &mut Window,
4173 cx: &mut Context<Self>,
4174 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4175 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4176 self.panes
4177 .first()
4178 .expect("There must be an active pane")
4179 .downgrade()
4180 });
4181
4182 if let Member::Pane(center_pane) = &self.center.root
4183 && center_pane.read(cx).items_len() == 0
4184 {
4185 return self.open_path(path, Some(pane), true, window, cx);
4186 }
4187
4188 let project_path = path.into();
4189 let task = self.load_path(project_path.clone(), window, cx);
4190 cx.spawn_in(window, async move |this, cx| {
4191 let (project_entry_id, build_item) = task.await?;
4192 this.update_in(cx, move |this, window, cx| -> Option<_> {
4193 let pane = pane.upgrade()?;
4194 let new_pane = this.split_pane(
4195 pane,
4196 split_direction.unwrap_or(SplitDirection::Right),
4197 window,
4198 cx,
4199 );
4200 new_pane.update(cx, |new_pane, cx| {
4201 Some(new_pane.open_item(
4202 project_entry_id,
4203 project_path,
4204 true,
4205 allow_preview,
4206 true,
4207 None,
4208 window,
4209 cx,
4210 build_item,
4211 ))
4212 })
4213 })
4214 .map(|option| option.context("pane was dropped"))?
4215 })
4216 }
4217
4218 fn load_path(
4219 &mut self,
4220 path: ProjectPath,
4221 window: &mut Window,
4222 cx: &mut App,
4223 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4224 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4225 registry.open_path(self.project(), &path, window, cx)
4226 }
4227
4228 pub fn find_project_item<T>(
4229 &self,
4230 pane: &Entity<Pane>,
4231 project_item: &Entity<T::Item>,
4232 cx: &App,
4233 ) -> Option<Entity<T>>
4234 where
4235 T: ProjectItem,
4236 {
4237 use project::ProjectItem as _;
4238 let project_item = project_item.read(cx);
4239 let entry_id = project_item.entry_id(cx);
4240 let project_path = project_item.project_path(cx);
4241
4242 let mut item = None;
4243 if let Some(entry_id) = entry_id {
4244 item = pane.read(cx).item_for_entry(entry_id, cx);
4245 }
4246 if item.is_none()
4247 && let Some(project_path) = project_path
4248 {
4249 item = pane.read(cx).item_for_path(project_path, cx);
4250 }
4251
4252 item.and_then(|item| item.downcast::<T>())
4253 }
4254
4255 pub fn is_project_item_open<T>(
4256 &self,
4257 pane: &Entity<Pane>,
4258 project_item: &Entity<T::Item>,
4259 cx: &App,
4260 ) -> bool
4261 where
4262 T: ProjectItem,
4263 {
4264 self.find_project_item::<T>(pane, project_item, cx)
4265 .is_some()
4266 }
4267
4268 pub fn open_project_item<T>(
4269 &mut self,
4270 pane: Entity<Pane>,
4271 project_item: Entity<T::Item>,
4272 activate_pane: bool,
4273 focus_item: bool,
4274 keep_old_preview: bool,
4275 allow_new_preview: bool,
4276 window: &mut Window,
4277 cx: &mut Context<Self>,
4278 ) -> Entity<T>
4279 where
4280 T: ProjectItem,
4281 {
4282 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4283
4284 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4285 if !keep_old_preview
4286 && let Some(old_id) = old_item_id
4287 && old_id != item.item_id()
4288 {
4289 // switching to a different item, so unpreview old active item
4290 pane.update(cx, |pane, _| {
4291 pane.unpreview_item_if_preview(old_id);
4292 });
4293 }
4294
4295 self.activate_item(&item, activate_pane, focus_item, window, cx);
4296 if !allow_new_preview {
4297 pane.update(cx, |pane, _| {
4298 pane.unpreview_item_if_preview(item.item_id());
4299 });
4300 }
4301 return item;
4302 }
4303
4304 let item = pane.update(cx, |pane, cx| {
4305 cx.new(|cx| {
4306 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4307 })
4308 });
4309 let mut destination_index = None;
4310 pane.update(cx, |pane, cx| {
4311 if !keep_old_preview && let Some(old_id) = old_item_id {
4312 pane.unpreview_item_if_preview(old_id);
4313 }
4314 if allow_new_preview {
4315 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4316 }
4317 });
4318
4319 self.add_item(
4320 pane,
4321 Box::new(item.clone()),
4322 destination_index,
4323 activate_pane,
4324 focus_item,
4325 window,
4326 cx,
4327 );
4328 item
4329 }
4330
4331 pub fn open_shared_screen(
4332 &mut self,
4333 peer_id: PeerId,
4334 window: &mut Window,
4335 cx: &mut Context<Self>,
4336 ) {
4337 if let Some(shared_screen) =
4338 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4339 {
4340 self.active_pane.update(cx, |pane, cx| {
4341 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4342 });
4343 }
4344 }
4345
4346 pub fn activate_item(
4347 &mut self,
4348 item: &dyn ItemHandle,
4349 activate_pane: bool,
4350 focus_item: bool,
4351 window: &mut Window,
4352 cx: &mut App,
4353 ) -> bool {
4354 let result = self.panes.iter().find_map(|pane| {
4355 pane.read(cx)
4356 .index_for_item(item)
4357 .map(|ix| (pane.clone(), ix))
4358 });
4359 if let Some((pane, ix)) = result {
4360 pane.update(cx, |pane, cx| {
4361 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4362 });
4363 true
4364 } else {
4365 false
4366 }
4367 }
4368
4369 fn activate_pane_at_index(
4370 &mut self,
4371 action: &ActivatePane,
4372 window: &mut Window,
4373 cx: &mut Context<Self>,
4374 ) {
4375 let panes = self.center.panes();
4376 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4377 window.focus(&pane.focus_handle(cx), cx);
4378 } else {
4379 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4380 .detach();
4381 }
4382 }
4383
4384 fn move_item_to_pane_at_index(
4385 &mut self,
4386 action: &MoveItemToPane,
4387 window: &mut Window,
4388 cx: &mut Context<Self>,
4389 ) {
4390 let panes = self.center.panes();
4391 let destination = match panes.get(action.destination) {
4392 Some(&destination) => destination.clone(),
4393 None => {
4394 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4395 return;
4396 }
4397 let direction = SplitDirection::Right;
4398 let split_off_pane = self
4399 .find_pane_in_direction(direction, cx)
4400 .unwrap_or_else(|| self.active_pane.clone());
4401 let new_pane = self.add_pane(window, cx);
4402 self.center.split(&split_off_pane, &new_pane, direction, cx);
4403 new_pane
4404 }
4405 };
4406
4407 if action.clone {
4408 if self
4409 .active_pane
4410 .read(cx)
4411 .active_item()
4412 .is_some_and(|item| item.can_split(cx))
4413 {
4414 clone_active_item(
4415 self.database_id(),
4416 &self.active_pane,
4417 &destination,
4418 action.focus,
4419 window,
4420 cx,
4421 );
4422 return;
4423 }
4424 }
4425 move_active_item(
4426 &self.active_pane,
4427 &destination,
4428 action.focus,
4429 true,
4430 window,
4431 cx,
4432 )
4433 }
4434
4435 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4436 let panes = self.center.panes();
4437 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4438 let next_ix = (ix + 1) % panes.len();
4439 let next_pane = panes[next_ix].clone();
4440 window.focus(&next_pane.focus_handle(cx), cx);
4441 }
4442 }
4443
4444 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4445 let panes = self.center.panes();
4446 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4447 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4448 let prev_pane = panes[prev_ix].clone();
4449 window.focus(&prev_pane.focus_handle(cx), cx);
4450 }
4451 }
4452
4453 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4454 let last_pane = self.center.last_pane();
4455 window.focus(&last_pane.focus_handle(cx), cx);
4456 }
4457
4458 pub fn activate_pane_in_direction(
4459 &mut self,
4460 direction: SplitDirection,
4461 window: &mut Window,
4462 cx: &mut App,
4463 ) {
4464 use ActivateInDirectionTarget as Target;
4465 enum Origin {
4466 LeftDock,
4467 RightDock,
4468 BottomDock,
4469 Center,
4470 }
4471
4472 let origin: Origin = [
4473 (&self.left_dock, Origin::LeftDock),
4474 (&self.right_dock, Origin::RightDock),
4475 (&self.bottom_dock, Origin::BottomDock),
4476 ]
4477 .into_iter()
4478 .find_map(|(dock, origin)| {
4479 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4480 Some(origin)
4481 } else {
4482 None
4483 }
4484 })
4485 .unwrap_or(Origin::Center);
4486
4487 let get_last_active_pane = || {
4488 let pane = self
4489 .last_active_center_pane
4490 .clone()
4491 .unwrap_or_else(|| {
4492 self.panes
4493 .first()
4494 .expect("There must be an active pane")
4495 .downgrade()
4496 })
4497 .upgrade()?;
4498 (pane.read(cx).items_len() != 0).then_some(pane)
4499 };
4500
4501 let try_dock =
4502 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4503
4504 let target = match (origin, direction) {
4505 // We're in the center, so we first try to go to a different pane,
4506 // otherwise try to go to a dock.
4507 (Origin::Center, direction) => {
4508 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4509 Some(Target::Pane(pane))
4510 } else {
4511 match direction {
4512 SplitDirection::Up => None,
4513 SplitDirection::Down => try_dock(&self.bottom_dock),
4514 SplitDirection::Left => try_dock(&self.left_dock),
4515 SplitDirection::Right => try_dock(&self.right_dock),
4516 }
4517 }
4518 }
4519
4520 (Origin::LeftDock, SplitDirection::Right) => {
4521 if let Some(last_active_pane) = get_last_active_pane() {
4522 Some(Target::Pane(last_active_pane))
4523 } else {
4524 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4525 }
4526 }
4527
4528 (Origin::LeftDock, SplitDirection::Down)
4529 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4530
4531 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4532 (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
4533 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4534
4535 (Origin::RightDock, SplitDirection::Left) => {
4536 if let Some(last_active_pane) = get_last_active_pane() {
4537 Some(Target::Pane(last_active_pane))
4538 } else {
4539 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
4540 }
4541 }
4542
4543 _ => None,
4544 };
4545
4546 match target {
4547 Some(ActivateInDirectionTarget::Pane(pane)) => {
4548 let pane = pane.read(cx);
4549 if let Some(item) = pane.active_item() {
4550 item.item_focus_handle(cx).focus(window, cx);
4551 } else {
4552 log::error!(
4553 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4554 );
4555 }
4556 }
4557 Some(ActivateInDirectionTarget::Dock(dock)) => {
4558 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4559 window.defer(cx, move |window, cx| {
4560 let dock = dock.read(cx);
4561 if let Some(panel) = dock.active_panel() {
4562 panel.panel_focus_handle(cx).focus(window, cx);
4563 } else {
4564 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4565 }
4566 })
4567 }
4568 None => {}
4569 }
4570 }
4571
4572 pub fn move_item_to_pane_in_direction(
4573 &mut self,
4574 action: &MoveItemToPaneInDirection,
4575 window: &mut Window,
4576 cx: &mut Context<Self>,
4577 ) {
4578 let destination = match self.find_pane_in_direction(action.direction, cx) {
4579 Some(destination) => destination,
4580 None => {
4581 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4582 return;
4583 }
4584 let new_pane = self.add_pane(window, cx);
4585 self.center
4586 .split(&self.active_pane, &new_pane, action.direction, cx);
4587 new_pane
4588 }
4589 };
4590
4591 if action.clone {
4592 if self
4593 .active_pane
4594 .read(cx)
4595 .active_item()
4596 .is_some_and(|item| item.can_split(cx))
4597 {
4598 clone_active_item(
4599 self.database_id(),
4600 &self.active_pane,
4601 &destination,
4602 action.focus,
4603 window,
4604 cx,
4605 );
4606 return;
4607 }
4608 }
4609 move_active_item(
4610 &self.active_pane,
4611 &destination,
4612 action.focus,
4613 true,
4614 window,
4615 cx,
4616 );
4617 }
4618
4619 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4620 self.center.bounding_box_for_pane(pane)
4621 }
4622
4623 pub fn find_pane_in_direction(
4624 &mut self,
4625 direction: SplitDirection,
4626 cx: &App,
4627 ) -> Option<Entity<Pane>> {
4628 self.center
4629 .find_pane_in_direction(&self.active_pane, direction, cx)
4630 .cloned()
4631 }
4632
4633 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4634 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4635 self.center.swap(&self.active_pane, &to, cx);
4636 cx.notify();
4637 }
4638 }
4639
4640 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4641 if self
4642 .center
4643 .move_to_border(&self.active_pane, direction, cx)
4644 .unwrap()
4645 {
4646 cx.notify();
4647 }
4648 }
4649
4650 pub fn resize_pane(
4651 &mut self,
4652 axis: gpui::Axis,
4653 amount: Pixels,
4654 window: &mut Window,
4655 cx: &mut Context<Self>,
4656 ) {
4657 let docks = self.all_docks();
4658 let active_dock = docks
4659 .into_iter()
4660 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4661
4662 if let Some(dock) = active_dock {
4663 let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
4664 return;
4665 };
4666 match dock.read(cx).position() {
4667 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4668 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4669 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4670 }
4671 } else {
4672 self.center
4673 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
4674 }
4675 cx.notify();
4676 }
4677
4678 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
4679 self.center.reset_pane_sizes(cx);
4680 cx.notify();
4681 }
4682
4683 fn handle_pane_focused(
4684 &mut self,
4685 pane: Entity<Pane>,
4686 window: &mut Window,
4687 cx: &mut Context<Self>,
4688 ) {
4689 // This is explicitly hoisted out of the following check for pane identity as
4690 // terminal panel panes are not registered as a center panes.
4691 self.status_bar.update(cx, |status_bar, cx| {
4692 status_bar.set_active_pane(&pane, window, cx);
4693 });
4694 if self.active_pane != pane {
4695 self.set_active_pane(&pane, window, cx);
4696 }
4697
4698 if self.last_active_center_pane.is_none() {
4699 self.last_active_center_pane = Some(pane.downgrade());
4700 }
4701
4702 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
4703 // This prevents the dock from closing when focus events fire during window activation.
4704 // We also preserve any dock whose active panel itself has focus — this covers
4705 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
4706 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
4707 let dock_read = dock.read(cx);
4708 if let Some(panel) = dock_read.active_panel() {
4709 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
4710 || panel.panel_focus_handle(cx).contains_focused(window, cx)
4711 {
4712 return Some(dock_read.position());
4713 }
4714 }
4715 None
4716 });
4717
4718 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
4719 if pane.read(cx).is_zoomed() {
4720 self.zoomed = Some(pane.downgrade().into());
4721 } else {
4722 self.zoomed = None;
4723 }
4724 self.zoomed_position = None;
4725 cx.emit(Event::ZoomChanged);
4726 self.update_active_view_for_followers(window, cx);
4727 pane.update(cx, |pane, _| {
4728 pane.track_alternate_file_items();
4729 });
4730
4731 cx.notify();
4732 }
4733
4734 fn set_active_pane(
4735 &mut self,
4736 pane: &Entity<Pane>,
4737 window: &mut Window,
4738 cx: &mut Context<Self>,
4739 ) {
4740 self.active_pane = pane.clone();
4741 self.active_item_path_changed(true, window, cx);
4742 self.last_active_center_pane = Some(pane.downgrade());
4743 }
4744
4745 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4746 self.update_active_view_for_followers(window, cx);
4747 }
4748
4749 fn handle_pane_event(
4750 &mut self,
4751 pane: &Entity<Pane>,
4752 event: &pane::Event,
4753 window: &mut Window,
4754 cx: &mut Context<Self>,
4755 ) {
4756 let mut serialize_workspace = true;
4757 match event {
4758 pane::Event::AddItem { item } => {
4759 item.added_to_pane(self, pane.clone(), window, cx);
4760 cx.emit(Event::ItemAdded {
4761 item: item.boxed_clone(),
4762 });
4763 }
4764 pane::Event::Split { direction, mode } => {
4765 match mode {
4766 SplitMode::ClonePane => {
4767 self.split_and_clone(pane.clone(), *direction, window, cx)
4768 .detach();
4769 }
4770 SplitMode::EmptyPane => {
4771 self.split_pane(pane.clone(), *direction, window, cx);
4772 }
4773 SplitMode::MovePane => {
4774 self.split_and_move(pane.clone(), *direction, window, cx);
4775 }
4776 };
4777 }
4778 pane::Event::JoinIntoNext => {
4779 self.join_pane_into_next(pane.clone(), window, cx);
4780 }
4781 pane::Event::JoinAll => {
4782 self.join_all_panes(window, cx);
4783 }
4784 pane::Event::Remove { focus_on_pane } => {
4785 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
4786 }
4787 pane::Event::ActivateItem {
4788 local,
4789 focus_changed,
4790 } => {
4791 window.invalidate_character_coordinates();
4792
4793 pane.update(cx, |pane, _| {
4794 pane.track_alternate_file_items();
4795 });
4796 if *local {
4797 self.unfollow_in_pane(pane, window, cx);
4798 }
4799 serialize_workspace = *focus_changed || pane != self.active_pane();
4800 if pane == self.active_pane() {
4801 self.active_item_path_changed(*focus_changed, window, cx);
4802 self.update_active_view_for_followers(window, cx);
4803 } else if *local {
4804 self.set_active_pane(pane, window, cx);
4805 }
4806 }
4807 pane::Event::UserSavedItem { item, save_intent } => {
4808 cx.emit(Event::UserSavedItem {
4809 pane: pane.downgrade(),
4810 item: item.boxed_clone(),
4811 save_intent: *save_intent,
4812 });
4813 serialize_workspace = false;
4814 }
4815 pane::Event::ChangeItemTitle => {
4816 if *pane == self.active_pane {
4817 self.active_item_path_changed(false, window, cx);
4818 }
4819 serialize_workspace = false;
4820 }
4821 pane::Event::RemovedItem { item } => {
4822 cx.emit(Event::ActiveItemChanged);
4823 self.update_window_edited(window, cx);
4824 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
4825 && entry.get().entity_id() == pane.entity_id()
4826 {
4827 entry.remove();
4828 }
4829 cx.emit(Event::ItemRemoved {
4830 item_id: item.item_id(),
4831 });
4832 }
4833 pane::Event::Focus => {
4834 window.invalidate_character_coordinates();
4835 self.handle_pane_focused(pane.clone(), window, cx);
4836 }
4837 pane::Event::ZoomIn => {
4838 if *pane == self.active_pane {
4839 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
4840 if pane.read(cx).has_focus(window, cx) {
4841 self.zoomed = Some(pane.downgrade().into());
4842 self.zoomed_position = None;
4843 cx.emit(Event::ZoomChanged);
4844 }
4845 cx.notify();
4846 }
4847 }
4848 pane::Event::ZoomOut => {
4849 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4850 if self.zoomed_position.is_none() {
4851 self.zoomed = None;
4852 cx.emit(Event::ZoomChanged);
4853 }
4854 cx.notify();
4855 }
4856 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
4857 }
4858
4859 if serialize_workspace {
4860 self.serialize_workspace(window, cx);
4861 }
4862 }
4863
4864 pub fn unfollow_in_pane(
4865 &mut self,
4866 pane: &Entity<Pane>,
4867 window: &mut Window,
4868 cx: &mut Context<Workspace>,
4869 ) -> Option<CollaboratorId> {
4870 let leader_id = self.leader_for_pane(pane)?;
4871 self.unfollow(leader_id, window, cx);
4872 Some(leader_id)
4873 }
4874
4875 pub fn split_pane(
4876 &mut self,
4877 pane_to_split: Entity<Pane>,
4878 split_direction: SplitDirection,
4879 window: &mut Window,
4880 cx: &mut Context<Self>,
4881 ) -> Entity<Pane> {
4882 let new_pane = self.add_pane(window, cx);
4883 self.center
4884 .split(&pane_to_split, &new_pane, split_direction, cx);
4885 cx.notify();
4886 new_pane
4887 }
4888
4889 pub fn split_and_move(
4890 &mut self,
4891 pane: Entity<Pane>,
4892 direction: SplitDirection,
4893 window: &mut Window,
4894 cx: &mut Context<Self>,
4895 ) {
4896 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
4897 return;
4898 };
4899 let new_pane = self.add_pane(window, cx);
4900 new_pane.update(cx, |pane, cx| {
4901 pane.add_item(item, true, true, None, window, cx)
4902 });
4903 self.center.split(&pane, &new_pane, direction, cx);
4904 cx.notify();
4905 }
4906
4907 pub fn split_and_clone(
4908 &mut self,
4909 pane: Entity<Pane>,
4910 direction: SplitDirection,
4911 window: &mut Window,
4912 cx: &mut Context<Self>,
4913 ) -> Task<Option<Entity<Pane>>> {
4914 let Some(item) = pane.read(cx).active_item() else {
4915 return Task::ready(None);
4916 };
4917 if !item.can_split(cx) {
4918 return Task::ready(None);
4919 }
4920 let task = item.clone_on_split(self.database_id(), window, cx);
4921 cx.spawn_in(window, async move |this, cx| {
4922 if let Some(clone) = task.await {
4923 this.update_in(cx, |this, window, cx| {
4924 let new_pane = this.add_pane(window, cx);
4925 let nav_history = pane.read(cx).fork_nav_history();
4926 new_pane.update(cx, |pane, cx| {
4927 pane.set_nav_history(nav_history, cx);
4928 pane.add_item(clone, true, true, None, window, cx)
4929 });
4930 this.center.split(&pane, &new_pane, direction, cx);
4931 cx.notify();
4932 new_pane
4933 })
4934 .ok()
4935 } else {
4936 None
4937 }
4938 })
4939 }
4940
4941 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4942 let active_item = self.active_pane.read(cx).active_item();
4943 for pane in &self.panes {
4944 join_pane_into_active(&self.active_pane, pane, window, cx);
4945 }
4946 if let Some(active_item) = active_item {
4947 self.activate_item(active_item.as_ref(), true, true, window, cx);
4948 }
4949 cx.notify();
4950 }
4951
4952 pub fn join_pane_into_next(
4953 &mut self,
4954 pane: Entity<Pane>,
4955 window: &mut Window,
4956 cx: &mut Context<Self>,
4957 ) {
4958 let next_pane = self
4959 .find_pane_in_direction(SplitDirection::Right, cx)
4960 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
4961 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
4962 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
4963 let Some(next_pane) = next_pane else {
4964 return;
4965 };
4966 move_all_items(&pane, &next_pane, window, cx);
4967 cx.notify();
4968 }
4969
4970 fn remove_pane(
4971 &mut self,
4972 pane: Entity<Pane>,
4973 focus_on: Option<Entity<Pane>>,
4974 window: &mut Window,
4975 cx: &mut Context<Self>,
4976 ) {
4977 if self.center.remove(&pane, cx).unwrap() {
4978 self.force_remove_pane(&pane, &focus_on, window, cx);
4979 self.unfollow_in_pane(&pane, window, cx);
4980 self.last_leaders_by_pane.remove(&pane.downgrade());
4981 for removed_item in pane.read(cx).items() {
4982 self.panes_by_item.remove(&removed_item.item_id());
4983 }
4984
4985 cx.notify();
4986 } else {
4987 self.active_item_path_changed(true, window, cx);
4988 }
4989 cx.emit(Event::PaneRemoved);
4990 }
4991
4992 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
4993 &mut self.panes
4994 }
4995
4996 pub fn panes(&self) -> &[Entity<Pane>] {
4997 &self.panes
4998 }
4999
5000 pub fn active_pane(&self) -> &Entity<Pane> {
5001 &self.active_pane
5002 }
5003
5004 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5005 for dock in self.all_docks() {
5006 if dock.focus_handle(cx).contains_focused(window, cx)
5007 && let Some(pane) = dock
5008 .read(cx)
5009 .active_panel()
5010 .and_then(|panel| panel.pane(cx))
5011 {
5012 return pane;
5013 }
5014 }
5015 self.active_pane().clone()
5016 }
5017
5018 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5019 self.find_pane_in_direction(SplitDirection::Right, cx)
5020 .unwrap_or_else(|| {
5021 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5022 })
5023 }
5024
5025 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5026 self.pane_for_item_id(handle.item_id())
5027 }
5028
5029 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5030 let weak_pane = self.panes_by_item.get(&item_id)?;
5031 weak_pane.upgrade()
5032 }
5033
5034 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5035 self.panes
5036 .iter()
5037 .find(|pane| pane.entity_id() == entity_id)
5038 .cloned()
5039 }
5040
5041 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5042 self.follower_states.retain(|leader_id, state| {
5043 if *leader_id == CollaboratorId::PeerId(peer_id) {
5044 for item in state.items_by_leader_view_id.values() {
5045 item.view.set_leader_id(None, window, cx);
5046 }
5047 false
5048 } else {
5049 true
5050 }
5051 });
5052 cx.notify();
5053 }
5054
5055 pub fn start_following(
5056 &mut self,
5057 leader_id: impl Into<CollaboratorId>,
5058 window: &mut Window,
5059 cx: &mut Context<Self>,
5060 ) -> Option<Task<Result<()>>> {
5061 let leader_id = leader_id.into();
5062 let pane = self.active_pane().clone();
5063
5064 self.last_leaders_by_pane
5065 .insert(pane.downgrade(), leader_id);
5066 self.unfollow(leader_id, window, cx);
5067 self.unfollow_in_pane(&pane, window, cx);
5068 self.follower_states.insert(
5069 leader_id,
5070 FollowerState {
5071 center_pane: pane.clone(),
5072 dock_pane: None,
5073 active_view_id: None,
5074 items_by_leader_view_id: Default::default(),
5075 },
5076 );
5077 cx.notify();
5078
5079 match leader_id {
5080 CollaboratorId::PeerId(leader_peer_id) => {
5081 let room_id = self.active_call()?.room_id(cx)?;
5082 let project_id = self.project.read(cx).remote_id();
5083 let request = self.app_state.client.request(proto::Follow {
5084 room_id,
5085 project_id,
5086 leader_id: Some(leader_peer_id),
5087 });
5088
5089 Some(cx.spawn_in(window, async move |this, cx| {
5090 let response = request.await?;
5091 this.update(cx, |this, _| {
5092 let state = this
5093 .follower_states
5094 .get_mut(&leader_id)
5095 .context("following interrupted")?;
5096 state.active_view_id = response
5097 .active_view
5098 .as_ref()
5099 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5100 anyhow::Ok(())
5101 })??;
5102 if let Some(view) = response.active_view {
5103 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5104 }
5105 this.update_in(cx, |this, window, cx| {
5106 this.leader_updated(leader_id, window, cx)
5107 })?;
5108 Ok(())
5109 }))
5110 }
5111 CollaboratorId::Agent => {
5112 self.leader_updated(leader_id, window, cx)?;
5113 Some(Task::ready(Ok(())))
5114 }
5115 }
5116 }
5117
5118 pub fn follow_next_collaborator(
5119 &mut self,
5120 _: &FollowNextCollaborator,
5121 window: &mut Window,
5122 cx: &mut Context<Self>,
5123 ) {
5124 let collaborators = self.project.read(cx).collaborators();
5125 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5126 let mut collaborators = collaborators.keys().copied();
5127 for peer_id in collaborators.by_ref() {
5128 if CollaboratorId::PeerId(peer_id) == leader_id {
5129 break;
5130 }
5131 }
5132 collaborators.next().map(CollaboratorId::PeerId)
5133 } else if let Some(last_leader_id) =
5134 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5135 {
5136 match last_leader_id {
5137 CollaboratorId::PeerId(peer_id) => {
5138 if collaborators.contains_key(peer_id) {
5139 Some(*last_leader_id)
5140 } else {
5141 None
5142 }
5143 }
5144 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5145 }
5146 } else {
5147 None
5148 };
5149
5150 let pane = self.active_pane.clone();
5151 let Some(leader_id) = next_leader_id.or_else(|| {
5152 Some(CollaboratorId::PeerId(
5153 collaborators.keys().copied().next()?,
5154 ))
5155 }) else {
5156 return;
5157 };
5158 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5159 return;
5160 }
5161 if let Some(task) = self.start_following(leader_id, window, cx) {
5162 task.detach_and_log_err(cx)
5163 }
5164 }
5165
5166 pub fn follow(
5167 &mut self,
5168 leader_id: impl Into<CollaboratorId>,
5169 window: &mut Window,
5170 cx: &mut Context<Self>,
5171 ) {
5172 let leader_id = leader_id.into();
5173
5174 if let CollaboratorId::PeerId(peer_id) = leader_id {
5175 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5176 return;
5177 };
5178 let Some(remote_participant) =
5179 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5180 else {
5181 return;
5182 };
5183
5184 let project = self.project.read(cx);
5185
5186 let other_project_id = match remote_participant.location {
5187 ParticipantLocation::External => None,
5188 ParticipantLocation::UnsharedProject => None,
5189 ParticipantLocation::SharedProject { project_id } => {
5190 if Some(project_id) == project.remote_id() {
5191 None
5192 } else {
5193 Some(project_id)
5194 }
5195 }
5196 };
5197
5198 // if they are active in another project, follow there.
5199 if let Some(project_id) = other_project_id {
5200 let app_state = self.app_state.clone();
5201 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5202 .detach_and_log_err(cx);
5203 }
5204 }
5205
5206 // if you're already following, find the right pane and focus it.
5207 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5208 window.focus(&follower_state.pane().focus_handle(cx), cx);
5209
5210 return;
5211 }
5212
5213 // Otherwise, follow.
5214 if let Some(task) = self.start_following(leader_id, window, cx) {
5215 task.detach_and_log_err(cx)
5216 }
5217 }
5218
5219 pub fn unfollow(
5220 &mut self,
5221 leader_id: impl Into<CollaboratorId>,
5222 window: &mut Window,
5223 cx: &mut Context<Self>,
5224 ) -> Option<()> {
5225 cx.notify();
5226
5227 let leader_id = leader_id.into();
5228 let state = self.follower_states.remove(&leader_id)?;
5229 for (_, item) in state.items_by_leader_view_id {
5230 item.view.set_leader_id(None, window, cx);
5231 }
5232
5233 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5234 let project_id = self.project.read(cx).remote_id();
5235 let room_id = self.active_call()?.room_id(cx)?;
5236 self.app_state
5237 .client
5238 .send(proto::Unfollow {
5239 room_id,
5240 project_id,
5241 leader_id: Some(leader_peer_id),
5242 })
5243 .log_err();
5244 }
5245
5246 Some(())
5247 }
5248
5249 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5250 self.follower_states.contains_key(&id.into())
5251 }
5252
5253 fn active_item_path_changed(
5254 &mut self,
5255 focus_changed: bool,
5256 window: &mut Window,
5257 cx: &mut Context<Self>,
5258 ) {
5259 cx.emit(Event::ActiveItemChanged);
5260 let active_entry = self.active_project_path(cx);
5261 self.project.update(cx, |project, cx| {
5262 project.set_active_path(active_entry.clone(), cx)
5263 });
5264
5265 if focus_changed && let Some(project_path) = &active_entry {
5266 let git_store_entity = self.project.read(cx).git_store().clone();
5267 git_store_entity.update(cx, |git_store, cx| {
5268 git_store.set_active_repo_for_path(project_path, cx);
5269 });
5270 }
5271
5272 self.update_window_title(window, cx);
5273 }
5274
5275 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5276 let project = self.project().read(cx);
5277 let mut title = String::new();
5278
5279 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5280 let name = {
5281 let settings_location = SettingsLocation {
5282 worktree_id: worktree.read(cx).id(),
5283 path: RelPath::empty(),
5284 };
5285
5286 let settings = WorktreeSettings::get(Some(settings_location), cx);
5287 match &settings.project_name {
5288 Some(name) => name.as_str(),
5289 None => worktree.read(cx).root_name_str(),
5290 }
5291 };
5292 if i > 0 {
5293 title.push_str(", ");
5294 }
5295 title.push_str(name);
5296 }
5297
5298 if title.is_empty() {
5299 title = "empty project".to_string();
5300 }
5301
5302 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5303 let filename = path.path.file_name().or_else(|| {
5304 Some(
5305 project
5306 .worktree_for_id(path.worktree_id, cx)?
5307 .read(cx)
5308 .root_name_str(),
5309 )
5310 });
5311
5312 if let Some(filename) = filename {
5313 title.push_str(" — ");
5314 title.push_str(filename.as_ref());
5315 }
5316 }
5317
5318 if project.is_via_collab() {
5319 title.push_str(" ↙");
5320 } else if project.is_shared() {
5321 title.push_str(" ↗");
5322 }
5323
5324 if let Some(last_title) = self.last_window_title.as_ref()
5325 && &title == last_title
5326 {
5327 return;
5328 }
5329 window.set_window_title(&title);
5330 SystemWindowTabController::update_tab_title(
5331 cx,
5332 window.window_handle().window_id(),
5333 SharedString::from(&title),
5334 );
5335 self.last_window_title = Some(title);
5336 }
5337
5338 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5339 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5340 if is_edited != self.window_edited {
5341 self.window_edited = is_edited;
5342 window.set_window_edited(self.window_edited)
5343 }
5344 }
5345
5346 fn update_item_dirty_state(
5347 &mut self,
5348 item: &dyn ItemHandle,
5349 window: &mut Window,
5350 cx: &mut App,
5351 ) {
5352 let is_dirty = item.is_dirty(cx);
5353 let item_id = item.item_id();
5354 let was_dirty = self.dirty_items.contains_key(&item_id);
5355 if is_dirty == was_dirty {
5356 return;
5357 }
5358 if was_dirty {
5359 self.dirty_items.remove(&item_id);
5360 self.update_window_edited(window, cx);
5361 return;
5362 }
5363
5364 let workspace = self.weak_handle();
5365 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5366 return;
5367 };
5368 let on_release_callback = Box::new(move |cx: &mut App| {
5369 window_handle
5370 .update(cx, |_, window, cx| {
5371 workspace
5372 .update(cx, |workspace, cx| {
5373 workspace.dirty_items.remove(&item_id);
5374 workspace.update_window_edited(window, cx)
5375 })
5376 .ok();
5377 })
5378 .ok();
5379 });
5380
5381 let s = item.on_release(cx, on_release_callback);
5382 self.dirty_items.insert(item_id, s);
5383 self.update_window_edited(window, cx);
5384 }
5385
5386 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5387 if self.notifications.is_empty() {
5388 None
5389 } else {
5390 Some(
5391 div()
5392 .absolute()
5393 .right_3()
5394 .bottom_3()
5395 .w_112()
5396 .h_full()
5397 .flex()
5398 .flex_col()
5399 .justify_end()
5400 .gap_2()
5401 .children(
5402 self.notifications
5403 .iter()
5404 .map(|(_, notification)| notification.clone().into_any()),
5405 ),
5406 )
5407 }
5408 }
5409
5410 // RPC handlers
5411
5412 fn active_view_for_follower(
5413 &self,
5414 follower_project_id: Option<u64>,
5415 window: &mut Window,
5416 cx: &mut Context<Self>,
5417 ) -> Option<proto::View> {
5418 let (item, panel_id) = self.active_item_for_followers(window, cx);
5419 let item = item?;
5420 let leader_id = self
5421 .pane_for(&*item)
5422 .and_then(|pane| self.leader_for_pane(&pane));
5423 let leader_peer_id = match leader_id {
5424 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5425 Some(CollaboratorId::Agent) | None => None,
5426 };
5427
5428 let item_handle = item.to_followable_item_handle(cx)?;
5429 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5430 let variant = item_handle.to_state_proto(window, cx)?;
5431
5432 if item_handle.is_project_item(window, cx)
5433 && (follower_project_id.is_none()
5434 || follower_project_id != self.project.read(cx).remote_id())
5435 {
5436 return None;
5437 }
5438
5439 Some(proto::View {
5440 id: id.to_proto(),
5441 leader_id: leader_peer_id,
5442 variant: Some(variant),
5443 panel_id: panel_id.map(|id| id as i32),
5444 })
5445 }
5446
5447 fn handle_follow(
5448 &mut self,
5449 follower_project_id: Option<u64>,
5450 window: &mut Window,
5451 cx: &mut Context<Self>,
5452 ) -> proto::FollowResponse {
5453 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5454
5455 cx.notify();
5456 proto::FollowResponse {
5457 views: active_view.iter().cloned().collect(),
5458 active_view,
5459 }
5460 }
5461
5462 fn handle_update_followers(
5463 &mut self,
5464 leader_id: PeerId,
5465 message: proto::UpdateFollowers,
5466 _window: &mut Window,
5467 _cx: &mut Context<Self>,
5468 ) {
5469 self.leader_updates_tx
5470 .unbounded_send((leader_id, message))
5471 .ok();
5472 }
5473
5474 async fn process_leader_update(
5475 this: &WeakEntity<Self>,
5476 leader_id: PeerId,
5477 update: proto::UpdateFollowers,
5478 cx: &mut AsyncWindowContext,
5479 ) -> Result<()> {
5480 match update.variant.context("invalid update")? {
5481 proto::update_followers::Variant::CreateView(view) => {
5482 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5483 let should_add_view = this.update(cx, |this, _| {
5484 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5485 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5486 } else {
5487 anyhow::Ok(false)
5488 }
5489 })??;
5490
5491 if should_add_view {
5492 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5493 }
5494 }
5495 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5496 let should_add_view = this.update(cx, |this, _| {
5497 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5498 state.active_view_id = update_active_view
5499 .view
5500 .as_ref()
5501 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5502
5503 if state.active_view_id.is_some_and(|view_id| {
5504 !state.items_by_leader_view_id.contains_key(&view_id)
5505 }) {
5506 anyhow::Ok(true)
5507 } else {
5508 anyhow::Ok(false)
5509 }
5510 } else {
5511 anyhow::Ok(false)
5512 }
5513 })??;
5514
5515 if should_add_view && let Some(view) = update_active_view.view {
5516 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5517 }
5518 }
5519 proto::update_followers::Variant::UpdateView(update_view) => {
5520 let variant = update_view.variant.context("missing update view variant")?;
5521 let id = update_view.id.context("missing update view id")?;
5522 let mut tasks = Vec::new();
5523 this.update_in(cx, |this, window, cx| {
5524 let project = this.project.clone();
5525 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5526 let view_id = ViewId::from_proto(id.clone())?;
5527 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5528 tasks.push(item.view.apply_update_proto(
5529 &project,
5530 variant.clone(),
5531 window,
5532 cx,
5533 ));
5534 }
5535 }
5536 anyhow::Ok(())
5537 })??;
5538 try_join_all(tasks).await.log_err();
5539 }
5540 }
5541 this.update_in(cx, |this, window, cx| {
5542 this.leader_updated(leader_id, window, cx)
5543 })?;
5544 Ok(())
5545 }
5546
5547 async fn add_view_from_leader(
5548 this: WeakEntity<Self>,
5549 leader_id: PeerId,
5550 view: &proto::View,
5551 cx: &mut AsyncWindowContext,
5552 ) -> Result<()> {
5553 let this = this.upgrade().context("workspace dropped")?;
5554
5555 let Some(id) = view.id.clone() else {
5556 anyhow::bail!("no id for view");
5557 };
5558 let id = ViewId::from_proto(id)?;
5559 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5560
5561 let pane = this.update(cx, |this, _cx| {
5562 let state = this
5563 .follower_states
5564 .get(&leader_id.into())
5565 .context("stopped following")?;
5566 anyhow::Ok(state.pane().clone())
5567 })?;
5568 let existing_item = pane.update_in(cx, |pane, window, cx| {
5569 let client = this.read(cx).client().clone();
5570 pane.items().find_map(|item| {
5571 let item = item.to_followable_item_handle(cx)?;
5572 if item.remote_id(&client, window, cx) == Some(id) {
5573 Some(item)
5574 } else {
5575 None
5576 }
5577 })
5578 })?;
5579 let item = if let Some(existing_item) = existing_item {
5580 existing_item
5581 } else {
5582 let variant = view.variant.clone();
5583 anyhow::ensure!(variant.is_some(), "missing view variant");
5584
5585 let task = cx.update(|window, cx| {
5586 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5587 })?;
5588
5589 let Some(task) = task else {
5590 anyhow::bail!(
5591 "failed to construct view from leader (maybe from a different version of zed?)"
5592 );
5593 };
5594
5595 let mut new_item = task.await?;
5596 pane.update_in(cx, |pane, window, cx| {
5597 let mut item_to_remove = None;
5598 for (ix, item) in pane.items().enumerate() {
5599 if let Some(item) = item.to_followable_item_handle(cx) {
5600 match new_item.dedup(item.as_ref(), window, cx) {
5601 Some(item::Dedup::KeepExisting) => {
5602 new_item =
5603 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5604 break;
5605 }
5606 Some(item::Dedup::ReplaceExisting) => {
5607 item_to_remove = Some((ix, item.item_id()));
5608 break;
5609 }
5610 None => {}
5611 }
5612 }
5613 }
5614
5615 if let Some((ix, id)) = item_to_remove {
5616 pane.remove_item(id, false, false, window, cx);
5617 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5618 }
5619 })?;
5620
5621 new_item
5622 };
5623
5624 this.update_in(cx, |this, window, cx| {
5625 let state = this.follower_states.get_mut(&leader_id.into())?;
5626 item.set_leader_id(Some(leader_id.into()), window, cx);
5627 state.items_by_leader_view_id.insert(
5628 id,
5629 FollowerView {
5630 view: item,
5631 location: panel_id,
5632 },
5633 );
5634
5635 Some(())
5636 })
5637 .context("no follower state")?;
5638
5639 Ok(())
5640 }
5641
5642 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5643 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5644 return;
5645 };
5646
5647 if let Some(agent_location) = self.project.read(cx).agent_location() {
5648 let buffer_entity_id = agent_location.buffer.entity_id();
5649 let view_id = ViewId {
5650 creator: CollaboratorId::Agent,
5651 id: buffer_entity_id.as_u64(),
5652 };
5653 follower_state.active_view_id = Some(view_id);
5654
5655 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5656 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5657 hash_map::Entry::Vacant(entry) => {
5658 let existing_view =
5659 follower_state
5660 .center_pane
5661 .read(cx)
5662 .items()
5663 .find_map(|item| {
5664 let item = item.to_followable_item_handle(cx)?;
5665 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5666 && item.project_item_model_ids(cx).as_slice()
5667 == [buffer_entity_id]
5668 {
5669 Some(item)
5670 } else {
5671 None
5672 }
5673 });
5674 let view = existing_view.or_else(|| {
5675 agent_location.buffer.upgrade().and_then(|buffer| {
5676 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
5677 registry.build_item(buffer, self.project.clone(), None, window, cx)
5678 })?
5679 .to_followable_item_handle(cx)
5680 })
5681 });
5682
5683 view.map(|view| {
5684 entry.insert(FollowerView {
5685 view,
5686 location: None,
5687 })
5688 })
5689 }
5690 };
5691
5692 if let Some(item) = item {
5693 item.view
5694 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
5695 item.view
5696 .update_agent_location(agent_location.position, window, cx);
5697 }
5698 } else {
5699 follower_state.active_view_id = None;
5700 }
5701
5702 self.leader_updated(CollaboratorId::Agent, window, cx);
5703 }
5704
5705 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
5706 let mut is_project_item = true;
5707 let mut update = proto::UpdateActiveView::default();
5708 if window.is_window_active() {
5709 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
5710
5711 if let Some(item) = active_item
5712 && item.item_focus_handle(cx).contains_focused(window, cx)
5713 {
5714 let leader_id = self
5715 .pane_for(&*item)
5716 .and_then(|pane| self.leader_for_pane(&pane));
5717 let leader_peer_id = match leader_id {
5718 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5719 Some(CollaboratorId::Agent) | None => None,
5720 };
5721
5722 if let Some(item) = item.to_followable_item_handle(cx) {
5723 let id = item
5724 .remote_id(&self.app_state.client, window, cx)
5725 .map(|id| id.to_proto());
5726
5727 if let Some(id) = id
5728 && let Some(variant) = item.to_state_proto(window, cx)
5729 {
5730 let view = Some(proto::View {
5731 id,
5732 leader_id: leader_peer_id,
5733 variant: Some(variant),
5734 panel_id: panel_id.map(|id| id as i32),
5735 });
5736
5737 is_project_item = item.is_project_item(window, cx);
5738 update = proto::UpdateActiveView { view };
5739 };
5740 }
5741 }
5742 }
5743
5744 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
5745 if active_view_id != self.last_active_view_id.as_ref() {
5746 self.last_active_view_id = active_view_id.cloned();
5747 self.update_followers(
5748 is_project_item,
5749 proto::update_followers::Variant::UpdateActiveView(update),
5750 window,
5751 cx,
5752 );
5753 }
5754 }
5755
5756 fn active_item_for_followers(
5757 &self,
5758 window: &mut Window,
5759 cx: &mut App,
5760 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
5761 let mut active_item = None;
5762 let mut panel_id = None;
5763 for dock in self.all_docks() {
5764 if dock.focus_handle(cx).contains_focused(window, cx)
5765 && let Some(panel) = dock.read(cx).active_panel()
5766 && let Some(pane) = panel.pane(cx)
5767 && let Some(item) = pane.read(cx).active_item()
5768 {
5769 active_item = Some(item);
5770 panel_id = panel.remote_id();
5771 break;
5772 }
5773 }
5774
5775 if active_item.is_none() {
5776 active_item = self.active_pane().read(cx).active_item();
5777 }
5778 (active_item, panel_id)
5779 }
5780
5781 fn update_followers(
5782 &self,
5783 project_only: bool,
5784 update: proto::update_followers::Variant,
5785 _: &mut Window,
5786 cx: &mut App,
5787 ) -> Option<()> {
5788 // If this update only applies to for followers in the current project,
5789 // then skip it unless this project is shared. If it applies to all
5790 // followers, regardless of project, then set `project_id` to none,
5791 // indicating that it goes to all followers.
5792 let project_id = if project_only {
5793 Some(self.project.read(cx).remote_id()?)
5794 } else {
5795 None
5796 };
5797 self.app_state().workspace_store.update(cx, |store, cx| {
5798 store.update_followers(project_id, update, cx)
5799 })
5800 }
5801
5802 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
5803 self.follower_states.iter().find_map(|(leader_id, state)| {
5804 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
5805 Some(*leader_id)
5806 } else {
5807 None
5808 }
5809 })
5810 }
5811
5812 fn leader_updated(
5813 &mut self,
5814 leader_id: impl Into<CollaboratorId>,
5815 window: &mut Window,
5816 cx: &mut Context<Self>,
5817 ) -> Option<Box<dyn ItemHandle>> {
5818 cx.notify();
5819
5820 let leader_id = leader_id.into();
5821 let (panel_id, item) = match leader_id {
5822 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
5823 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
5824 };
5825
5826 let state = self.follower_states.get(&leader_id)?;
5827 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
5828 let pane;
5829 if let Some(panel_id) = panel_id {
5830 pane = self
5831 .activate_panel_for_proto_id(panel_id, window, cx)?
5832 .pane(cx)?;
5833 let state = self.follower_states.get_mut(&leader_id)?;
5834 state.dock_pane = Some(pane.clone());
5835 } else {
5836 pane = state.center_pane.clone();
5837 let state = self.follower_states.get_mut(&leader_id)?;
5838 if let Some(dock_pane) = state.dock_pane.take() {
5839 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
5840 }
5841 }
5842
5843 pane.update(cx, |pane, cx| {
5844 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
5845 if let Some(index) = pane.index_for_item(item.as_ref()) {
5846 pane.activate_item(index, false, false, window, cx);
5847 } else {
5848 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
5849 }
5850
5851 if focus_active_item {
5852 pane.focus_active_item(window, cx)
5853 }
5854 });
5855
5856 Some(item)
5857 }
5858
5859 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
5860 let state = self.follower_states.get(&CollaboratorId::Agent)?;
5861 let active_view_id = state.active_view_id?;
5862 Some(
5863 state
5864 .items_by_leader_view_id
5865 .get(&active_view_id)?
5866 .view
5867 .boxed_clone(),
5868 )
5869 }
5870
5871 fn active_item_for_peer(
5872 &self,
5873 peer_id: PeerId,
5874 window: &mut Window,
5875 cx: &mut Context<Self>,
5876 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
5877 let call = self.active_call()?;
5878 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
5879 let leader_in_this_app;
5880 let leader_in_this_project;
5881 match participant.location {
5882 ParticipantLocation::SharedProject { project_id } => {
5883 leader_in_this_app = true;
5884 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
5885 }
5886 ParticipantLocation::UnsharedProject => {
5887 leader_in_this_app = true;
5888 leader_in_this_project = false;
5889 }
5890 ParticipantLocation::External => {
5891 leader_in_this_app = false;
5892 leader_in_this_project = false;
5893 }
5894 };
5895 let state = self.follower_states.get(&peer_id.into())?;
5896 let mut item_to_activate = None;
5897 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
5898 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
5899 && (leader_in_this_project || !item.view.is_project_item(window, cx))
5900 {
5901 item_to_activate = Some((item.location, item.view.boxed_clone()));
5902 }
5903 } else if let Some(shared_screen) =
5904 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
5905 {
5906 item_to_activate = Some((None, Box::new(shared_screen)));
5907 }
5908 item_to_activate
5909 }
5910
5911 fn shared_screen_for_peer(
5912 &self,
5913 peer_id: PeerId,
5914 pane: &Entity<Pane>,
5915 window: &mut Window,
5916 cx: &mut App,
5917 ) -> Option<Entity<SharedScreen>> {
5918 self.active_call()?
5919 .create_shared_screen(peer_id, pane, window, cx)
5920 }
5921
5922 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5923 if window.is_window_active() {
5924 self.update_active_view_for_followers(window, cx);
5925
5926 if let Some(database_id) = self.database_id {
5927 cx.background_spawn(persistence::DB.update_timestamp(database_id))
5928 .detach();
5929 }
5930 } else {
5931 for pane in &self.panes {
5932 pane.update(cx, |pane, cx| {
5933 if let Some(item) = pane.active_item() {
5934 item.workspace_deactivated(window, cx);
5935 }
5936 for item in pane.items() {
5937 if matches!(
5938 item.workspace_settings(cx).autosave,
5939 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
5940 ) {
5941 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
5942 .detach_and_log_err(cx);
5943 }
5944 }
5945 });
5946 }
5947 }
5948 }
5949
5950 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
5951 self.active_call.as_ref().map(|(call, _)| &*call.0)
5952 }
5953
5954 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
5955 self.active_call.as_ref().map(|(call, _)| call.clone())
5956 }
5957
5958 fn on_active_call_event(
5959 &mut self,
5960 event: &ActiveCallEvent,
5961 window: &mut Window,
5962 cx: &mut Context<Self>,
5963 ) {
5964 match event {
5965 ActiveCallEvent::ParticipantLocationChanged { participant_id }
5966 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
5967 self.leader_updated(participant_id, window, cx);
5968 }
5969 }
5970 }
5971
5972 pub fn database_id(&self) -> Option<WorkspaceId> {
5973 self.database_id
5974 }
5975
5976 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
5977 self.database_id = Some(id);
5978 }
5979
5980 pub fn session_id(&self) -> Option<String> {
5981 self.session_id.clone()
5982 }
5983
5984 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
5985 let Some(display) = window.display(cx) else {
5986 return Task::ready(());
5987 };
5988 let Ok(display_uuid) = display.uuid() else {
5989 return Task::ready(());
5990 };
5991
5992 let window_bounds = window.inner_window_bounds();
5993 let database_id = self.database_id;
5994 let has_paths = !self.root_paths(cx).is_empty();
5995
5996 cx.background_executor().spawn(async move {
5997 if !has_paths {
5998 persistence::write_default_window_bounds(window_bounds, display_uuid)
5999 .await
6000 .log_err();
6001 }
6002 if let Some(database_id) = database_id {
6003 DB.set_window_open_status(
6004 database_id,
6005 SerializedWindowBounds(window_bounds),
6006 display_uuid,
6007 )
6008 .await
6009 .log_err();
6010 } else {
6011 persistence::write_default_window_bounds(window_bounds, display_uuid)
6012 .await
6013 .log_err();
6014 }
6015 })
6016 }
6017
6018 /// Bypass the 200ms serialization throttle and write workspace state to
6019 /// the DB immediately. Returns a task the caller can await to ensure the
6020 /// write completes. Used by the quit handler so the most recent state
6021 /// isn't lost to a pending throttle timer when the process exits.
6022 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6023 self._schedule_serialize_workspace.take();
6024 self._serialize_workspace_task.take();
6025 self.bounds_save_task_queued.take();
6026
6027 let bounds_task = self.save_window_bounds(window, cx);
6028 let serialize_task = self.serialize_workspace_internal(window, cx);
6029 cx.spawn(async move |_| {
6030 bounds_task.await;
6031 serialize_task.await;
6032 })
6033 }
6034
6035 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6036 let project = self.project().read(cx);
6037 project
6038 .visible_worktrees(cx)
6039 .map(|worktree| worktree.read(cx).abs_path())
6040 .collect::<Vec<_>>()
6041 }
6042
6043 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6044 match member {
6045 Member::Axis(PaneAxis { members, .. }) => {
6046 for child in members.iter() {
6047 self.remove_panes(child.clone(), window, cx)
6048 }
6049 }
6050 Member::Pane(pane) => {
6051 self.force_remove_pane(&pane, &None, window, cx);
6052 }
6053 }
6054 }
6055
6056 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6057 self.session_id.take();
6058 self.serialize_workspace_internal(window, cx)
6059 }
6060
6061 fn force_remove_pane(
6062 &mut self,
6063 pane: &Entity<Pane>,
6064 focus_on: &Option<Entity<Pane>>,
6065 window: &mut Window,
6066 cx: &mut Context<Workspace>,
6067 ) {
6068 self.panes.retain(|p| p != pane);
6069 if let Some(focus_on) = focus_on {
6070 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6071 } else if self.active_pane() == pane {
6072 self.panes
6073 .last()
6074 .unwrap()
6075 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6076 }
6077 if self.last_active_center_pane == Some(pane.downgrade()) {
6078 self.last_active_center_pane = None;
6079 }
6080 cx.notify();
6081 }
6082
6083 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6084 if self._schedule_serialize_workspace.is_none() {
6085 self._schedule_serialize_workspace =
6086 Some(cx.spawn_in(window, async move |this, cx| {
6087 cx.background_executor()
6088 .timer(SERIALIZATION_THROTTLE_TIME)
6089 .await;
6090 this.update_in(cx, |this, window, cx| {
6091 this._serialize_workspace_task =
6092 Some(this.serialize_workspace_internal(window, cx));
6093 this._schedule_serialize_workspace.take();
6094 })
6095 .log_err();
6096 }));
6097 }
6098 }
6099
6100 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6101 let Some(database_id) = self.database_id() else {
6102 return Task::ready(());
6103 };
6104
6105 fn serialize_pane_handle(
6106 pane_handle: &Entity<Pane>,
6107 window: &mut Window,
6108 cx: &mut App,
6109 ) -> SerializedPane {
6110 let (items, active, pinned_count) = {
6111 let pane = pane_handle.read(cx);
6112 let active_item_id = pane.active_item().map(|item| item.item_id());
6113 (
6114 pane.items()
6115 .filter_map(|handle| {
6116 let handle = handle.to_serializable_item_handle(cx)?;
6117
6118 Some(SerializedItem {
6119 kind: Arc::from(handle.serialized_item_kind()),
6120 item_id: handle.item_id().as_u64(),
6121 active: Some(handle.item_id()) == active_item_id,
6122 preview: pane.is_active_preview_item(handle.item_id()),
6123 })
6124 })
6125 .collect::<Vec<_>>(),
6126 pane.has_focus(window, cx),
6127 pane.pinned_count(),
6128 )
6129 };
6130
6131 SerializedPane::new(items, active, pinned_count)
6132 }
6133
6134 fn build_serialized_pane_group(
6135 pane_group: &Member,
6136 window: &mut Window,
6137 cx: &mut App,
6138 ) -> SerializedPaneGroup {
6139 match pane_group {
6140 Member::Axis(PaneAxis {
6141 axis,
6142 members,
6143 flexes,
6144 bounding_boxes: _,
6145 }) => SerializedPaneGroup::Group {
6146 axis: SerializedAxis(*axis),
6147 children: members
6148 .iter()
6149 .map(|member| build_serialized_pane_group(member, window, cx))
6150 .collect::<Vec<_>>(),
6151 flexes: Some(flexes.lock().clone()),
6152 },
6153 Member::Pane(pane_handle) => {
6154 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6155 }
6156 }
6157 }
6158
6159 fn build_serialized_docks(
6160 this: &Workspace,
6161 window: &mut Window,
6162 cx: &mut App,
6163 ) -> DockStructure {
6164 this.capture_dock_state(window, cx)
6165 }
6166
6167 match self.workspace_location(cx) {
6168 WorkspaceLocation::Location(location, paths) => {
6169 let breakpoints = self.project.update(cx, |project, cx| {
6170 project
6171 .breakpoint_store()
6172 .read(cx)
6173 .all_source_breakpoints(cx)
6174 });
6175 let user_toolchains = self
6176 .project
6177 .read(cx)
6178 .user_toolchains(cx)
6179 .unwrap_or_default();
6180
6181 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6182 let docks = build_serialized_docks(self, window, cx);
6183 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6184
6185 let serialized_workspace = SerializedWorkspace {
6186 id: database_id,
6187 location,
6188 paths,
6189 center_group,
6190 window_bounds,
6191 display: Default::default(),
6192 docks,
6193 centered_layout: self.centered_layout,
6194 session_id: self.session_id.clone(),
6195 breakpoints,
6196 window_id: Some(window.window_handle().window_id().as_u64()),
6197 user_toolchains,
6198 };
6199
6200 window.spawn(cx, async move |_| {
6201 persistence::DB.save_workspace(serialized_workspace).await;
6202 })
6203 }
6204 WorkspaceLocation::DetachFromSession => {
6205 let window_bounds = SerializedWindowBounds(window.window_bounds());
6206 let display = window.display(cx).and_then(|d| d.uuid().ok());
6207 // Save dock state for empty local workspaces
6208 let docks = build_serialized_docks(self, window, cx);
6209 window.spawn(cx, async move |_| {
6210 persistence::DB
6211 .set_window_open_status(
6212 database_id,
6213 window_bounds,
6214 display.unwrap_or_default(),
6215 )
6216 .await
6217 .log_err();
6218 persistence::DB
6219 .set_session_id(database_id, None)
6220 .await
6221 .log_err();
6222 persistence::write_default_dock_state(docks).await.log_err();
6223 })
6224 }
6225 WorkspaceLocation::None => {
6226 // Save dock state for empty non-local workspaces
6227 let docks = build_serialized_docks(self, window, cx);
6228 window.spawn(cx, async move |_| {
6229 persistence::write_default_dock_state(docks).await.log_err();
6230 })
6231 }
6232 }
6233 }
6234
6235 fn has_any_items_open(&self, cx: &App) -> bool {
6236 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6237 }
6238
6239 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6240 let paths = PathList::new(&self.root_paths(cx));
6241 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6242 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6243 } else if self.project.read(cx).is_local() {
6244 if !paths.is_empty() || self.has_any_items_open(cx) {
6245 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6246 } else {
6247 WorkspaceLocation::DetachFromSession
6248 }
6249 } else {
6250 WorkspaceLocation::None
6251 }
6252 }
6253
6254 fn update_history(&self, cx: &mut App) {
6255 let Some(id) = self.database_id() else {
6256 return;
6257 };
6258 if !self.project.read(cx).is_local() {
6259 return;
6260 }
6261 if let Some(manager) = HistoryManager::global(cx) {
6262 let paths = PathList::new(&self.root_paths(cx));
6263 manager.update(cx, |this, cx| {
6264 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6265 });
6266 }
6267 }
6268
6269 async fn serialize_items(
6270 this: &WeakEntity<Self>,
6271 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6272 cx: &mut AsyncWindowContext,
6273 ) -> Result<()> {
6274 const CHUNK_SIZE: usize = 200;
6275
6276 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6277
6278 while let Some(items_received) = serializable_items.next().await {
6279 let unique_items =
6280 items_received
6281 .into_iter()
6282 .fold(HashMap::default(), |mut acc, item| {
6283 acc.entry(item.item_id()).or_insert(item);
6284 acc
6285 });
6286
6287 // We use into_iter() here so that the references to the items are moved into
6288 // the tasks and not kept alive while we're sleeping.
6289 for (_, item) in unique_items.into_iter() {
6290 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6291 item.serialize(workspace, false, window, cx)
6292 }) {
6293 cx.background_spawn(async move { task.await.log_err() })
6294 .detach();
6295 }
6296 }
6297
6298 cx.background_executor()
6299 .timer(SERIALIZATION_THROTTLE_TIME)
6300 .await;
6301 }
6302
6303 Ok(())
6304 }
6305
6306 pub(crate) fn enqueue_item_serialization(
6307 &mut self,
6308 item: Box<dyn SerializableItemHandle>,
6309 ) -> Result<()> {
6310 self.serializable_items_tx
6311 .unbounded_send(item)
6312 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6313 }
6314
6315 pub(crate) fn load_workspace(
6316 serialized_workspace: SerializedWorkspace,
6317 paths_to_open: Vec<Option<ProjectPath>>,
6318 window: &mut Window,
6319 cx: &mut Context<Workspace>,
6320 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6321 cx.spawn_in(window, async move |workspace, cx| {
6322 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6323
6324 let mut center_group = None;
6325 let mut center_items = None;
6326
6327 // Traverse the splits tree and add to things
6328 if let Some((group, active_pane, items)) = serialized_workspace
6329 .center_group
6330 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6331 .await
6332 {
6333 center_items = Some(items);
6334 center_group = Some((group, active_pane))
6335 }
6336
6337 let mut items_by_project_path = HashMap::default();
6338 let mut item_ids_by_kind = HashMap::default();
6339 let mut all_deserialized_items = Vec::default();
6340 cx.update(|_, cx| {
6341 for item in center_items.unwrap_or_default().into_iter().flatten() {
6342 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6343 item_ids_by_kind
6344 .entry(serializable_item_handle.serialized_item_kind())
6345 .or_insert(Vec::new())
6346 .push(item.item_id().as_u64() as ItemId);
6347 }
6348
6349 if let Some(project_path) = item.project_path(cx) {
6350 items_by_project_path.insert(project_path, item.clone());
6351 }
6352 all_deserialized_items.push(item);
6353 }
6354 })?;
6355
6356 let opened_items = paths_to_open
6357 .into_iter()
6358 .map(|path_to_open| {
6359 path_to_open
6360 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6361 })
6362 .collect::<Vec<_>>();
6363
6364 // Remove old panes from workspace panes list
6365 workspace.update_in(cx, |workspace, window, cx| {
6366 if let Some((center_group, active_pane)) = center_group {
6367 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6368
6369 // Swap workspace center group
6370 workspace.center = PaneGroup::with_root(center_group);
6371 workspace.center.set_is_center(true);
6372 workspace.center.mark_positions(cx);
6373
6374 if let Some(active_pane) = active_pane {
6375 workspace.set_active_pane(&active_pane, window, cx);
6376 cx.focus_self(window);
6377 } else {
6378 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6379 }
6380 }
6381
6382 let docks = serialized_workspace.docks;
6383
6384 for (dock, serialized_dock) in [
6385 (&mut workspace.right_dock, docks.right),
6386 (&mut workspace.left_dock, docks.left),
6387 (&mut workspace.bottom_dock, docks.bottom),
6388 ]
6389 .iter_mut()
6390 {
6391 dock.update(cx, |dock, cx| {
6392 dock.serialized_dock = Some(serialized_dock.clone());
6393 dock.restore_state(window, cx);
6394 });
6395 }
6396
6397 cx.notify();
6398 })?;
6399
6400 let _ = project
6401 .update(cx, |project, cx| {
6402 project
6403 .breakpoint_store()
6404 .update(cx, |breakpoint_store, cx| {
6405 breakpoint_store
6406 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6407 })
6408 })
6409 .await;
6410
6411 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6412 // after loading the items, we might have different items and in order to avoid
6413 // the database filling up, we delete items that haven't been loaded now.
6414 //
6415 // The items that have been loaded, have been saved after they've been added to the workspace.
6416 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6417 item_ids_by_kind
6418 .into_iter()
6419 .map(|(item_kind, loaded_items)| {
6420 SerializableItemRegistry::cleanup(
6421 item_kind,
6422 serialized_workspace.id,
6423 loaded_items,
6424 window,
6425 cx,
6426 )
6427 .log_err()
6428 })
6429 .collect::<Vec<_>>()
6430 })?;
6431
6432 futures::future::join_all(clean_up_tasks).await;
6433
6434 workspace
6435 .update_in(cx, |workspace, window, cx| {
6436 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6437 workspace.serialize_workspace_internal(window, cx).detach();
6438
6439 // Ensure that we mark the window as edited if we did load dirty items
6440 workspace.update_window_edited(window, cx);
6441 })
6442 .ok();
6443
6444 Ok(opened_items)
6445 })
6446 }
6447
6448 pub fn key_context(&self, cx: &App) -> KeyContext {
6449 let mut context = KeyContext::new_with_defaults();
6450 context.add("Workspace");
6451 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6452 if let Some(status) = self
6453 .debugger_provider
6454 .as_ref()
6455 .and_then(|provider| provider.active_thread_state(cx))
6456 {
6457 match status {
6458 ThreadStatus::Running | ThreadStatus::Stepping => {
6459 context.add("debugger_running");
6460 }
6461 ThreadStatus::Stopped => context.add("debugger_stopped"),
6462 ThreadStatus::Exited | ThreadStatus::Ended => {}
6463 }
6464 }
6465
6466 if self.left_dock.read(cx).is_open() {
6467 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6468 context.set("left_dock", active_panel.panel_key());
6469 }
6470 }
6471
6472 if self.right_dock.read(cx).is_open() {
6473 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6474 context.set("right_dock", active_panel.panel_key());
6475 }
6476 }
6477
6478 if self.bottom_dock.read(cx).is_open() {
6479 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6480 context.set("bottom_dock", active_panel.panel_key());
6481 }
6482 }
6483
6484 context
6485 }
6486
6487 /// Multiworkspace uses this to add workspace action handling to itself
6488 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6489 self.add_workspace_actions_listeners(div, window, cx)
6490 .on_action(cx.listener(
6491 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6492 for action in &action_sequence.0 {
6493 window.dispatch_action(action.boxed_clone(), cx);
6494 }
6495 },
6496 ))
6497 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6498 .on_action(cx.listener(Self::close_all_items_and_panes))
6499 .on_action(cx.listener(Self::close_item_in_all_panes))
6500 .on_action(cx.listener(Self::save_all))
6501 .on_action(cx.listener(Self::send_keystrokes))
6502 .on_action(cx.listener(Self::add_folder_to_project))
6503 .on_action(cx.listener(Self::follow_next_collaborator))
6504 .on_action(cx.listener(Self::activate_pane_at_index))
6505 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6506 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6507 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6508 .on_action(cx.listener(Self::toggle_theme_mode))
6509 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6510 let pane = workspace.active_pane().clone();
6511 workspace.unfollow_in_pane(&pane, window, cx);
6512 }))
6513 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6514 workspace
6515 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6516 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6517 }))
6518 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6519 workspace
6520 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6521 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6522 }))
6523 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6524 workspace
6525 .save_active_item(SaveIntent::SaveAs, window, cx)
6526 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6527 }))
6528 .on_action(
6529 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6530 workspace.activate_previous_pane(window, cx)
6531 }),
6532 )
6533 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6534 workspace.activate_next_pane(window, cx)
6535 }))
6536 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6537 workspace.activate_last_pane(window, cx)
6538 }))
6539 .on_action(
6540 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6541 workspace.activate_next_window(cx)
6542 }),
6543 )
6544 .on_action(
6545 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6546 workspace.activate_previous_window(cx)
6547 }),
6548 )
6549 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6550 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6551 }))
6552 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6553 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6554 }))
6555 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6556 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6557 }))
6558 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6559 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6560 }))
6561 .on_action(cx.listener(
6562 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6563 workspace.move_item_to_pane_in_direction(action, window, cx)
6564 },
6565 ))
6566 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6567 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6568 }))
6569 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6570 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6571 }))
6572 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6573 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6574 }))
6575 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6576 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6577 }))
6578 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6579 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6580 SplitDirection::Down,
6581 SplitDirection::Up,
6582 SplitDirection::Right,
6583 SplitDirection::Left,
6584 ];
6585 for dir in DIRECTION_PRIORITY {
6586 if workspace.find_pane_in_direction(dir, cx).is_some() {
6587 workspace.swap_pane_in_direction(dir, cx);
6588 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6589 break;
6590 }
6591 }
6592 }))
6593 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6594 workspace.move_pane_to_border(SplitDirection::Left, cx)
6595 }))
6596 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6597 workspace.move_pane_to_border(SplitDirection::Right, cx)
6598 }))
6599 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6600 workspace.move_pane_to_border(SplitDirection::Up, cx)
6601 }))
6602 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6603 workspace.move_pane_to_border(SplitDirection::Down, cx)
6604 }))
6605 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6606 this.toggle_dock(DockPosition::Left, window, cx);
6607 }))
6608 .on_action(cx.listener(
6609 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6610 workspace.toggle_dock(DockPosition::Right, window, cx);
6611 },
6612 ))
6613 .on_action(cx.listener(
6614 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6615 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6616 },
6617 ))
6618 .on_action(cx.listener(
6619 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6620 if !workspace.close_active_dock(window, cx) {
6621 cx.propagate();
6622 }
6623 },
6624 ))
6625 .on_action(
6626 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6627 workspace.close_all_docks(window, cx);
6628 }),
6629 )
6630 .on_action(cx.listener(Self::toggle_all_docks))
6631 .on_action(cx.listener(
6632 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6633 workspace.clear_all_notifications(cx);
6634 },
6635 ))
6636 .on_action(cx.listener(
6637 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6638 workspace.clear_navigation_history(window, cx);
6639 },
6640 ))
6641 .on_action(cx.listener(
6642 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6643 if let Some((notification_id, _)) = workspace.notifications.pop() {
6644 workspace.suppress_notification(¬ification_id, cx);
6645 }
6646 },
6647 ))
6648 .on_action(cx.listener(
6649 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6650 workspace.show_worktree_trust_security_modal(true, window, cx);
6651 },
6652 ))
6653 .on_action(
6654 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6655 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6656 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6657 trusted_worktrees.clear_trusted_paths()
6658 });
6659 let clear_task = persistence::DB.clear_trusted_worktrees();
6660 cx.spawn(async move |_, cx| {
6661 if clear_task.await.log_err().is_some() {
6662 cx.update(|cx| reload(cx));
6663 }
6664 })
6665 .detach();
6666 }
6667 }),
6668 )
6669 .on_action(cx.listener(
6670 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
6671 workspace.reopen_closed_item(window, cx).detach();
6672 },
6673 ))
6674 .on_action(cx.listener(
6675 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
6676 for dock in workspace.all_docks() {
6677 if dock.focus_handle(cx).contains_focused(window, cx) {
6678 let Some(panel) = dock.read(cx).active_panel() else {
6679 return;
6680 };
6681
6682 // Set to `None`, then the size will fall back to the default.
6683 panel.clone().set_size(None, window, cx);
6684
6685 return;
6686 }
6687 }
6688 },
6689 ))
6690 .on_action(cx.listener(
6691 |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
6692 for dock in workspace.all_docks() {
6693 if let Some(panel) = dock.read(cx).visible_panel() {
6694 // Set to `None`, then the size will fall back to the default.
6695 panel.clone().set_size(None, window, cx);
6696 }
6697 }
6698 },
6699 ))
6700 .on_action(cx.listener(
6701 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
6702 adjust_active_dock_size_by_px(
6703 px_with_ui_font_fallback(act.px, cx),
6704 workspace,
6705 window,
6706 cx,
6707 );
6708 },
6709 ))
6710 .on_action(cx.listener(
6711 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
6712 adjust_active_dock_size_by_px(
6713 px_with_ui_font_fallback(act.px, cx) * -1.,
6714 workspace,
6715 window,
6716 cx,
6717 );
6718 },
6719 ))
6720 .on_action(cx.listener(
6721 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
6722 adjust_open_docks_size_by_px(
6723 px_with_ui_font_fallback(act.px, cx),
6724 workspace,
6725 window,
6726 cx,
6727 );
6728 },
6729 ))
6730 .on_action(cx.listener(
6731 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
6732 adjust_open_docks_size_by_px(
6733 px_with_ui_font_fallback(act.px, cx) * -1.,
6734 workspace,
6735 window,
6736 cx,
6737 );
6738 },
6739 ))
6740 .on_action(cx.listener(Workspace::toggle_centered_layout))
6741 .on_action(cx.listener(
6742 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
6743 if let Some(active_dock) = workspace.active_dock(window, cx) {
6744 let dock = active_dock.read(cx);
6745 if let Some(active_panel) = dock.active_panel() {
6746 if active_panel.pane(cx).is_none() {
6747 let mut recent_pane: Option<Entity<Pane>> = None;
6748 let mut recent_timestamp = 0;
6749 for pane_handle in workspace.panes() {
6750 let pane = pane_handle.read(cx);
6751 for entry in pane.activation_history() {
6752 if entry.timestamp > recent_timestamp {
6753 recent_timestamp = entry.timestamp;
6754 recent_pane = Some(pane_handle.clone());
6755 }
6756 }
6757 }
6758
6759 if let Some(pane) = recent_pane {
6760 pane.update(cx, |pane, cx| {
6761 let current_index = pane.active_item_index();
6762 let items_len = pane.items_len();
6763 if items_len > 0 {
6764 let next_index = if current_index + 1 < items_len {
6765 current_index + 1
6766 } else {
6767 0
6768 };
6769 pane.activate_item(
6770 next_index, false, false, window, cx,
6771 );
6772 }
6773 });
6774 return;
6775 }
6776 }
6777 }
6778 }
6779 cx.propagate();
6780 },
6781 ))
6782 .on_action(cx.listener(
6783 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
6784 if let Some(active_dock) = workspace.active_dock(window, cx) {
6785 let dock = active_dock.read(cx);
6786 if let Some(active_panel) = dock.active_panel() {
6787 if active_panel.pane(cx).is_none() {
6788 let mut recent_pane: Option<Entity<Pane>> = None;
6789 let mut recent_timestamp = 0;
6790 for pane_handle in workspace.panes() {
6791 let pane = pane_handle.read(cx);
6792 for entry in pane.activation_history() {
6793 if entry.timestamp > recent_timestamp {
6794 recent_timestamp = entry.timestamp;
6795 recent_pane = Some(pane_handle.clone());
6796 }
6797 }
6798 }
6799
6800 if let Some(pane) = recent_pane {
6801 pane.update(cx, |pane, cx| {
6802 let current_index = pane.active_item_index();
6803 let items_len = pane.items_len();
6804 if items_len > 0 {
6805 let prev_index = if current_index > 0 {
6806 current_index - 1
6807 } else {
6808 items_len.saturating_sub(1)
6809 };
6810 pane.activate_item(
6811 prev_index, false, false, window, cx,
6812 );
6813 }
6814 });
6815 return;
6816 }
6817 }
6818 }
6819 }
6820 cx.propagate();
6821 },
6822 ))
6823 .on_action(cx.listener(
6824 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
6825 if let Some(active_dock) = workspace.active_dock(window, cx) {
6826 let dock = active_dock.read(cx);
6827 if let Some(active_panel) = dock.active_panel() {
6828 if active_panel.pane(cx).is_none() {
6829 let active_pane = workspace.active_pane().clone();
6830 active_pane.update(cx, |pane, cx| {
6831 pane.close_active_item(action, window, cx)
6832 .detach_and_log_err(cx);
6833 });
6834 return;
6835 }
6836 }
6837 }
6838 cx.propagate();
6839 },
6840 ))
6841 .on_action(
6842 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
6843 let pane = workspace.active_pane().clone();
6844 if let Some(item) = pane.read(cx).active_item() {
6845 item.toggle_read_only(window, cx);
6846 }
6847 }),
6848 )
6849 .on_action(cx.listener(Workspace::cancel))
6850 }
6851
6852 #[cfg(any(test, feature = "test-support"))]
6853 pub fn set_random_database_id(&mut self) {
6854 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
6855 }
6856
6857 #[cfg(any(test, feature = "test-support"))]
6858 pub(crate) fn test_new(
6859 project: Entity<Project>,
6860 window: &mut Window,
6861 cx: &mut Context<Self>,
6862 ) -> Self {
6863 use node_runtime::NodeRuntime;
6864 use session::Session;
6865
6866 let client = project.read(cx).client();
6867 let user_store = project.read(cx).user_store();
6868 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
6869 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
6870 window.activate_window();
6871 let app_state = Arc::new(AppState {
6872 languages: project.read(cx).languages().clone(),
6873 workspace_store,
6874 client,
6875 user_store,
6876 fs: project.read(cx).fs().clone(),
6877 build_window_options: |_, _| Default::default(),
6878 node_runtime: NodeRuntime::unavailable(),
6879 session,
6880 });
6881 let workspace = Self::new(Default::default(), project, app_state, window, cx);
6882 workspace
6883 .active_pane
6884 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6885 workspace
6886 }
6887
6888 pub fn register_action<A: Action>(
6889 &mut self,
6890 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
6891 ) -> &mut Self {
6892 let callback = Arc::new(callback);
6893
6894 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
6895 let callback = callback.clone();
6896 div.on_action(cx.listener(move |workspace, event, window, cx| {
6897 (callback)(workspace, event, window, cx)
6898 }))
6899 }));
6900 self
6901 }
6902 pub fn register_action_renderer(
6903 &mut self,
6904 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
6905 ) -> &mut Self {
6906 self.workspace_actions.push(Box::new(callback));
6907 self
6908 }
6909
6910 fn add_workspace_actions_listeners(
6911 &self,
6912 mut div: Div,
6913 window: &mut Window,
6914 cx: &mut Context<Self>,
6915 ) -> Div {
6916 for action in self.workspace_actions.iter() {
6917 div = (action)(div, self, window, cx)
6918 }
6919 div
6920 }
6921
6922 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
6923 self.modal_layer.read(cx).has_active_modal()
6924 }
6925
6926 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
6927 self.modal_layer.read(cx).active_modal()
6928 }
6929
6930 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
6931 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
6932 /// If no modal is active, the new modal will be shown.
6933 ///
6934 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
6935 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
6936 /// will not be shown.
6937 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
6938 where
6939 B: FnOnce(&mut Window, &mut Context<V>) -> V,
6940 {
6941 self.modal_layer.update(cx, |modal_layer, cx| {
6942 modal_layer.toggle_modal(window, cx, build)
6943 })
6944 }
6945
6946 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
6947 self.modal_layer
6948 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
6949 }
6950
6951 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
6952 self.toast_layer
6953 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
6954 }
6955
6956 pub fn toggle_centered_layout(
6957 &mut self,
6958 _: &ToggleCenteredLayout,
6959 _: &mut Window,
6960 cx: &mut Context<Self>,
6961 ) {
6962 self.centered_layout = !self.centered_layout;
6963 if let Some(database_id) = self.database_id() {
6964 cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
6965 .detach_and_log_err(cx);
6966 }
6967 cx.notify();
6968 }
6969
6970 fn adjust_padding(padding: Option<f32>) -> f32 {
6971 padding
6972 .unwrap_or(CenteredPaddingSettings::default().0)
6973 .clamp(
6974 CenteredPaddingSettings::MIN_PADDING,
6975 CenteredPaddingSettings::MAX_PADDING,
6976 )
6977 }
6978
6979 fn render_dock(
6980 &self,
6981 position: DockPosition,
6982 dock: &Entity<Dock>,
6983 window: &mut Window,
6984 cx: &mut App,
6985 ) -> Option<Div> {
6986 if self.zoomed_position == Some(position) {
6987 return None;
6988 }
6989
6990 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
6991 let pane = panel.pane(cx)?;
6992 let follower_states = &self.follower_states;
6993 leader_border_for_pane(follower_states, &pane, window, cx)
6994 });
6995
6996 Some(
6997 div()
6998 .flex()
6999 .flex_none()
7000 .overflow_hidden()
7001 .child(dock.clone())
7002 .children(leader_border),
7003 )
7004 }
7005
7006 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7007 window
7008 .root::<MultiWorkspace>()
7009 .flatten()
7010 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7011 }
7012
7013 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7014 self.zoomed.as_ref()
7015 }
7016
7017 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7018 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7019 return;
7020 };
7021 let windows = cx.windows();
7022 let next_window =
7023 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7024 || {
7025 windows
7026 .iter()
7027 .cycle()
7028 .skip_while(|window| window.window_id() != current_window_id)
7029 .nth(1)
7030 },
7031 );
7032
7033 if let Some(window) = next_window {
7034 window
7035 .update(cx, |_, window, _| window.activate_window())
7036 .ok();
7037 }
7038 }
7039
7040 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7041 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7042 return;
7043 };
7044 let windows = cx.windows();
7045 let prev_window =
7046 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7047 || {
7048 windows
7049 .iter()
7050 .rev()
7051 .cycle()
7052 .skip_while(|window| window.window_id() != current_window_id)
7053 .nth(1)
7054 },
7055 );
7056
7057 if let Some(window) = prev_window {
7058 window
7059 .update(cx, |_, window, _| window.activate_window())
7060 .ok();
7061 }
7062 }
7063
7064 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7065 if cx.stop_active_drag(window) {
7066 } else if let Some((notification_id, _)) = self.notifications.pop() {
7067 dismiss_app_notification(¬ification_id, cx);
7068 } else {
7069 cx.propagate();
7070 }
7071 }
7072
7073 fn adjust_dock_size_by_px(
7074 &mut self,
7075 panel_size: Pixels,
7076 dock_pos: DockPosition,
7077 px: Pixels,
7078 window: &mut Window,
7079 cx: &mut Context<Self>,
7080 ) {
7081 match dock_pos {
7082 DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
7083 DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
7084 DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
7085 }
7086 }
7087
7088 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7089 let workspace_width = self.bounds.size.width;
7090 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7091
7092 self.right_dock.read_with(cx, |right_dock, cx| {
7093 let right_dock_size = right_dock
7094 .active_panel_size(window, cx)
7095 .unwrap_or(Pixels::ZERO);
7096 if right_dock_size + size > workspace_width {
7097 size = workspace_width - right_dock_size
7098 }
7099 });
7100
7101 self.left_dock.update(cx, |left_dock, cx| {
7102 if WorkspaceSettings::get_global(cx)
7103 .resize_all_panels_in_dock
7104 .contains(&DockPosition::Left)
7105 {
7106 left_dock.resize_all_panels(Some(size), window, cx);
7107 } else {
7108 left_dock.resize_active_panel(Some(size), window, cx);
7109 }
7110 });
7111 }
7112
7113 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7114 let workspace_width = self.bounds.size.width;
7115 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7116 self.left_dock.read_with(cx, |left_dock, cx| {
7117 let left_dock_size = left_dock
7118 .active_panel_size(window, cx)
7119 .unwrap_or(Pixels::ZERO);
7120 if left_dock_size + size > workspace_width {
7121 size = workspace_width - left_dock_size
7122 }
7123 });
7124 self.right_dock.update(cx, |right_dock, cx| {
7125 if WorkspaceSettings::get_global(cx)
7126 .resize_all_panels_in_dock
7127 .contains(&DockPosition::Right)
7128 {
7129 right_dock.resize_all_panels(Some(size), window, cx);
7130 } else {
7131 right_dock.resize_active_panel(Some(size), window, cx);
7132 }
7133 });
7134 }
7135
7136 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7137 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7138 self.bottom_dock.update(cx, |bottom_dock, cx| {
7139 if WorkspaceSettings::get_global(cx)
7140 .resize_all_panels_in_dock
7141 .contains(&DockPosition::Bottom)
7142 {
7143 bottom_dock.resize_all_panels(Some(size), window, cx);
7144 } else {
7145 bottom_dock.resize_active_panel(Some(size), window, cx);
7146 }
7147 });
7148 }
7149
7150 fn toggle_edit_predictions_all_files(
7151 &mut self,
7152 _: &ToggleEditPrediction,
7153 _window: &mut Window,
7154 cx: &mut Context<Self>,
7155 ) {
7156 let fs = self.project().read(cx).fs().clone();
7157 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7158 update_settings_file(fs, cx, move |file, _| {
7159 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7160 });
7161 }
7162
7163 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7164 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7165 let next_mode = match current_mode {
7166 Some(theme::ThemeAppearanceMode::Light) => theme::ThemeAppearanceMode::Dark,
7167 Some(theme::ThemeAppearanceMode::Dark) => theme::ThemeAppearanceMode::Light,
7168 Some(theme::ThemeAppearanceMode::System) | None => match cx.theme().appearance() {
7169 theme::Appearance::Light => theme::ThemeAppearanceMode::Dark,
7170 theme::Appearance::Dark => theme::ThemeAppearanceMode::Light,
7171 },
7172 };
7173
7174 let fs = self.project().read(cx).fs().clone();
7175 settings::update_settings_file(fs, cx, move |settings, _cx| {
7176 theme::set_mode(settings, next_mode);
7177 });
7178 }
7179
7180 pub fn show_worktree_trust_security_modal(
7181 &mut self,
7182 toggle: bool,
7183 window: &mut Window,
7184 cx: &mut Context<Self>,
7185 ) {
7186 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7187 if toggle {
7188 security_modal.update(cx, |security_modal, cx| {
7189 security_modal.dismiss(cx);
7190 })
7191 } else {
7192 security_modal.update(cx, |security_modal, cx| {
7193 security_modal.refresh_restricted_paths(cx);
7194 });
7195 }
7196 } else {
7197 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7198 .map(|trusted_worktrees| {
7199 trusted_worktrees
7200 .read(cx)
7201 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7202 })
7203 .unwrap_or(false);
7204 if has_restricted_worktrees {
7205 let project = self.project().read(cx);
7206 let remote_host = project
7207 .remote_connection_options(cx)
7208 .map(RemoteHostLocation::from);
7209 let worktree_store = project.worktree_store().downgrade();
7210 self.toggle_modal(window, cx, |_, cx| {
7211 SecurityModal::new(worktree_store, remote_host, cx)
7212 });
7213 }
7214 }
7215 }
7216}
7217
7218pub trait AnyActiveCall {
7219 fn entity(&self) -> AnyEntity;
7220 fn is_in_room(&self, _: &App) -> bool;
7221 fn room_id(&self, _: &App) -> Option<u64>;
7222 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7223 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7224 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7225 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7226 fn is_sharing_project(&self, _: &App) -> bool;
7227 fn has_remote_participants(&self, _: &App) -> bool;
7228 fn local_participant_is_guest(&self, _: &App) -> bool;
7229 fn client(&self, _: &App) -> Arc<Client>;
7230 fn share_on_join(&self, _: &App) -> bool;
7231 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7232 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7233 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7234 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7235 fn join_project(
7236 &self,
7237 _: u64,
7238 _: Arc<LanguageRegistry>,
7239 _: Arc<dyn Fs>,
7240 _: &mut App,
7241 ) -> Task<Result<Entity<Project>>>;
7242 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7243 fn subscribe(
7244 &self,
7245 _: &mut Window,
7246 _: &mut Context<Workspace>,
7247 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7248 ) -> Subscription;
7249 fn create_shared_screen(
7250 &self,
7251 _: PeerId,
7252 _: &Entity<Pane>,
7253 _: &mut Window,
7254 _: &mut App,
7255 ) -> Option<Entity<SharedScreen>>;
7256}
7257
7258#[derive(Clone)]
7259pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7260impl Global for GlobalAnyActiveCall {}
7261
7262impl GlobalAnyActiveCall {
7263 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7264 cx.try_global()
7265 }
7266
7267 pub(crate) fn global(cx: &App) -> &Self {
7268 cx.global()
7269 }
7270}
7271
7272pub fn merge_conflict_notification_id() -> NotificationId {
7273 struct MergeConflictNotification;
7274 NotificationId::unique::<MergeConflictNotification>()
7275}
7276
7277/// Workspace-local view of a remote participant's location.
7278#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7279pub enum ParticipantLocation {
7280 SharedProject { project_id: u64 },
7281 UnsharedProject,
7282 External,
7283}
7284
7285impl ParticipantLocation {
7286 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7287 match location
7288 .and_then(|l| l.variant)
7289 .context("participant location was not provided")?
7290 {
7291 proto::participant_location::Variant::SharedProject(project) => {
7292 Ok(Self::SharedProject {
7293 project_id: project.id,
7294 })
7295 }
7296 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7297 proto::participant_location::Variant::External(_) => Ok(Self::External),
7298 }
7299 }
7300}
7301/// Workspace-local view of a remote collaborator's state.
7302/// This is the subset of `call::RemoteParticipant` that workspace needs.
7303#[derive(Clone)]
7304pub struct RemoteCollaborator {
7305 pub user: Arc<User>,
7306 pub peer_id: PeerId,
7307 pub location: ParticipantLocation,
7308 pub participant_index: ParticipantIndex,
7309}
7310
7311pub enum ActiveCallEvent {
7312 ParticipantLocationChanged { participant_id: PeerId },
7313 RemoteVideoTracksChanged { participant_id: PeerId },
7314}
7315
7316fn leader_border_for_pane(
7317 follower_states: &HashMap<CollaboratorId, FollowerState>,
7318 pane: &Entity<Pane>,
7319 _: &Window,
7320 cx: &App,
7321) -> Option<Div> {
7322 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7323 if state.pane() == pane {
7324 Some((*leader_id, state))
7325 } else {
7326 None
7327 }
7328 })?;
7329
7330 let mut leader_color = match leader_id {
7331 CollaboratorId::PeerId(leader_peer_id) => {
7332 let leader = GlobalAnyActiveCall::try_global(cx)?
7333 .0
7334 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7335
7336 cx.theme()
7337 .players()
7338 .color_for_participant(leader.participant_index.0)
7339 .cursor
7340 }
7341 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7342 };
7343 leader_color.fade_out(0.3);
7344 Some(
7345 div()
7346 .absolute()
7347 .size_full()
7348 .left_0()
7349 .top_0()
7350 .border_2()
7351 .border_color(leader_color),
7352 )
7353}
7354
7355fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7356 ZED_WINDOW_POSITION
7357 .zip(*ZED_WINDOW_SIZE)
7358 .map(|(position, size)| Bounds {
7359 origin: position,
7360 size,
7361 })
7362}
7363
7364fn open_items(
7365 serialized_workspace: Option<SerializedWorkspace>,
7366 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7367 window: &mut Window,
7368 cx: &mut Context<Workspace>,
7369) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7370 let restored_items = serialized_workspace.map(|serialized_workspace| {
7371 Workspace::load_workspace(
7372 serialized_workspace,
7373 project_paths_to_open
7374 .iter()
7375 .map(|(_, project_path)| project_path)
7376 .cloned()
7377 .collect(),
7378 window,
7379 cx,
7380 )
7381 });
7382
7383 cx.spawn_in(window, async move |workspace, cx| {
7384 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7385
7386 if let Some(restored_items) = restored_items {
7387 let restored_items = restored_items.await?;
7388
7389 let restored_project_paths = restored_items
7390 .iter()
7391 .filter_map(|item| {
7392 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7393 .ok()
7394 .flatten()
7395 })
7396 .collect::<HashSet<_>>();
7397
7398 for restored_item in restored_items {
7399 opened_items.push(restored_item.map(Ok));
7400 }
7401
7402 project_paths_to_open
7403 .iter_mut()
7404 .for_each(|(_, project_path)| {
7405 if let Some(project_path_to_open) = project_path
7406 && restored_project_paths.contains(project_path_to_open)
7407 {
7408 *project_path = None;
7409 }
7410 });
7411 } else {
7412 for _ in 0..project_paths_to_open.len() {
7413 opened_items.push(None);
7414 }
7415 }
7416 assert!(opened_items.len() == project_paths_to_open.len());
7417
7418 let tasks =
7419 project_paths_to_open
7420 .into_iter()
7421 .enumerate()
7422 .map(|(ix, (abs_path, project_path))| {
7423 let workspace = workspace.clone();
7424 cx.spawn(async move |cx| {
7425 let file_project_path = project_path?;
7426 let abs_path_task = workspace.update(cx, |workspace, cx| {
7427 workspace.project().update(cx, |project, cx| {
7428 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7429 })
7430 });
7431
7432 // We only want to open file paths here. If one of the items
7433 // here is a directory, it was already opened further above
7434 // with a `find_or_create_worktree`.
7435 if let Ok(task) = abs_path_task
7436 && task.await.is_none_or(|p| p.is_file())
7437 {
7438 return Some((
7439 ix,
7440 workspace
7441 .update_in(cx, |workspace, window, cx| {
7442 workspace.open_path(
7443 file_project_path,
7444 None,
7445 true,
7446 window,
7447 cx,
7448 )
7449 })
7450 .log_err()?
7451 .await,
7452 ));
7453 }
7454 None
7455 })
7456 });
7457
7458 let tasks = tasks.collect::<Vec<_>>();
7459
7460 let tasks = futures::future::join_all(tasks);
7461 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7462 opened_items[ix] = Some(path_open_result);
7463 }
7464
7465 Ok(opened_items)
7466 })
7467}
7468
7469enum ActivateInDirectionTarget {
7470 Pane(Entity<Pane>),
7471 Dock(Entity<Dock>),
7472}
7473
7474fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7475 window
7476 .update(cx, |multi_workspace, _, cx| {
7477 let workspace = multi_workspace.workspace().clone();
7478 workspace.update(cx, |workspace, cx| {
7479 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7480 struct DatabaseFailedNotification;
7481
7482 workspace.show_notification(
7483 NotificationId::unique::<DatabaseFailedNotification>(),
7484 cx,
7485 |cx| {
7486 cx.new(|cx| {
7487 MessageNotification::new("Failed to load the database file.", cx)
7488 .primary_message("File an Issue")
7489 .primary_icon(IconName::Plus)
7490 .primary_on_click(|window, cx| {
7491 window.dispatch_action(Box::new(FileBugReport), cx)
7492 })
7493 })
7494 },
7495 );
7496 }
7497 });
7498 })
7499 .log_err();
7500}
7501
7502fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7503 if val == 0 {
7504 ThemeSettings::get_global(cx).ui_font_size(cx)
7505 } else {
7506 px(val as f32)
7507 }
7508}
7509
7510fn adjust_active_dock_size_by_px(
7511 px: Pixels,
7512 workspace: &mut Workspace,
7513 window: &mut Window,
7514 cx: &mut Context<Workspace>,
7515) {
7516 let Some(active_dock) = workspace
7517 .all_docks()
7518 .into_iter()
7519 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7520 else {
7521 return;
7522 };
7523 let dock = active_dock.read(cx);
7524 let Some(panel_size) = dock.active_panel_size(window, cx) else {
7525 return;
7526 };
7527 let dock_pos = dock.position();
7528 workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
7529}
7530
7531fn adjust_open_docks_size_by_px(
7532 px: Pixels,
7533 workspace: &mut Workspace,
7534 window: &mut Window,
7535 cx: &mut Context<Workspace>,
7536) {
7537 let docks = workspace
7538 .all_docks()
7539 .into_iter()
7540 .filter_map(|dock| {
7541 if dock.read(cx).is_open() {
7542 let dock = dock.read(cx);
7543 let panel_size = dock.active_panel_size(window, cx)?;
7544 let dock_pos = dock.position();
7545 Some((panel_size, dock_pos, px))
7546 } else {
7547 None
7548 }
7549 })
7550 .collect::<Vec<_>>();
7551
7552 docks
7553 .into_iter()
7554 .for_each(|(panel_size, dock_pos, offset)| {
7555 workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
7556 });
7557}
7558
7559impl Focusable for Workspace {
7560 fn focus_handle(&self, cx: &App) -> FocusHandle {
7561 self.active_pane.focus_handle(cx)
7562 }
7563}
7564
7565#[derive(Clone)]
7566struct DraggedDock(DockPosition);
7567
7568impl Render for DraggedDock {
7569 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7570 gpui::Empty
7571 }
7572}
7573
7574impl Render for Workspace {
7575 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7576 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7577 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7578 log::info!("Rendered first frame");
7579 }
7580
7581 let centered_layout = self.centered_layout
7582 && self.center.panes().len() == 1
7583 && self.active_item(cx).is_some();
7584 let render_padding = |size| {
7585 (size > 0.0).then(|| {
7586 div()
7587 .h_full()
7588 .w(relative(size))
7589 .bg(cx.theme().colors().editor_background)
7590 .border_color(cx.theme().colors().pane_group_border)
7591 })
7592 };
7593 let paddings = if centered_layout {
7594 let settings = WorkspaceSettings::get_global(cx).centered_layout;
7595 (
7596 render_padding(Self::adjust_padding(
7597 settings.left_padding.map(|padding| padding.0),
7598 )),
7599 render_padding(Self::adjust_padding(
7600 settings.right_padding.map(|padding| padding.0),
7601 )),
7602 )
7603 } else {
7604 (None, None)
7605 };
7606 let ui_font = theme::setup_ui_font(window, cx);
7607
7608 let theme = cx.theme().clone();
7609 let colors = theme.colors();
7610 let notification_entities = self
7611 .notifications
7612 .iter()
7613 .map(|(_, notification)| notification.entity_id())
7614 .collect::<Vec<_>>();
7615 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
7616
7617 div()
7618 .relative()
7619 .size_full()
7620 .flex()
7621 .flex_col()
7622 .font(ui_font)
7623 .gap_0()
7624 .justify_start()
7625 .items_start()
7626 .text_color(colors.text)
7627 .overflow_hidden()
7628 .children(self.titlebar_item.clone())
7629 .on_modifiers_changed(move |_, _, cx| {
7630 for &id in ¬ification_entities {
7631 cx.notify(id);
7632 }
7633 })
7634 .child(
7635 div()
7636 .size_full()
7637 .relative()
7638 .flex_1()
7639 .flex()
7640 .flex_col()
7641 .child(
7642 div()
7643 .id("workspace")
7644 .bg(colors.background)
7645 .relative()
7646 .flex_1()
7647 .w_full()
7648 .flex()
7649 .flex_col()
7650 .overflow_hidden()
7651 .border_t_1()
7652 .border_b_1()
7653 .border_color(colors.border)
7654 .child({
7655 let this = cx.entity();
7656 canvas(
7657 move |bounds, window, cx| {
7658 this.update(cx, |this, cx| {
7659 let bounds_changed = this.bounds != bounds;
7660 this.bounds = bounds;
7661
7662 if bounds_changed {
7663 this.left_dock.update(cx, |dock, cx| {
7664 dock.clamp_panel_size(
7665 bounds.size.width,
7666 window,
7667 cx,
7668 )
7669 });
7670
7671 this.right_dock.update(cx, |dock, cx| {
7672 dock.clamp_panel_size(
7673 bounds.size.width,
7674 window,
7675 cx,
7676 )
7677 });
7678
7679 this.bottom_dock.update(cx, |dock, cx| {
7680 dock.clamp_panel_size(
7681 bounds.size.height,
7682 window,
7683 cx,
7684 )
7685 });
7686 }
7687 })
7688 },
7689 |_, _, _, _| {},
7690 )
7691 .absolute()
7692 .size_full()
7693 })
7694 .when(self.zoomed.is_none(), |this| {
7695 this.on_drag_move(cx.listener(
7696 move |workspace,
7697 e: &DragMoveEvent<DraggedDock>,
7698 window,
7699 cx| {
7700 if workspace.previous_dock_drag_coordinates
7701 != Some(e.event.position)
7702 {
7703 workspace.previous_dock_drag_coordinates =
7704 Some(e.event.position);
7705
7706 match e.drag(cx).0 {
7707 DockPosition::Left => {
7708 workspace.resize_left_dock(
7709 e.event.position.x
7710 - workspace.bounds.left(),
7711 window,
7712 cx,
7713 );
7714 }
7715 DockPosition::Right => {
7716 workspace.resize_right_dock(
7717 workspace.bounds.right()
7718 - e.event.position.x,
7719 window,
7720 cx,
7721 );
7722 }
7723 DockPosition::Bottom => {
7724 workspace.resize_bottom_dock(
7725 workspace.bounds.bottom()
7726 - e.event.position.y,
7727 window,
7728 cx,
7729 );
7730 }
7731 };
7732 workspace.serialize_workspace(window, cx);
7733 }
7734 },
7735 ))
7736
7737 })
7738 .child({
7739 match bottom_dock_layout {
7740 BottomDockLayout::Full => div()
7741 .flex()
7742 .flex_col()
7743 .h_full()
7744 .child(
7745 div()
7746 .flex()
7747 .flex_row()
7748 .flex_1()
7749 .overflow_hidden()
7750 .children(self.render_dock(
7751 DockPosition::Left,
7752 &self.left_dock,
7753 window,
7754 cx,
7755 ))
7756
7757 .child(
7758 div()
7759 .flex()
7760 .flex_col()
7761 .flex_1()
7762 .overflow_hidden()
7763 .child(
7764 h_flex()
7765 .flex_1()
7766 .when_some(
7767 paddings.0,
7768 |this, p| {
7769 this.child(
7770 p.border_r_1(),
7771 )
7772 },
7773 )
7774 .child(self.center.render(
7775 self.zoomed.as_ref(),
7776 &PaneRenderContext {
7777 follower_states:
7778 &self.follower_states,
7779 active_call: self.active_call(),
7780 active_pane: &self.active_pane,
7781 app_state: &self.app_state,
7782 project: &self.project,
7783 workspace: &self.weak_self,
7784 },
7785 window,
7786 cx,
7787 ))
7788 .when_some(
7789 paddings.1,
7790 |this, p| {
7791 this.child(
7792 p.border_l_1(),
7793 )
7794 },
7795 ),
7796 ),
7797 )
7798
7799 .children(self.render_dock(
7800 DockPosition::Right,
7801 &self.right_dock,
7802 window,
7803 cx,
7804 )),
7805 )
7806 .child(div().w_full().children(self.render_dock(
7807 DockPosition::Bottom,
7808 &self.bottom_dock,
7809 window,
7810 cx
7811 ))),
7812
7813 BottomDockLayout::LeftAligned => div()
7814 .flex()
7815 .flex_row()
7816 .h_full()
7817 .child(
7818 div()
7819 .flex()
7820 .flex_col()
7821 .flex_1()
7822 .h_full()
7823 .child(
7824 div()
7825 .flex()
7826 .flex_row()
7827 .flex_1()
7828 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
7829
7830 .child(
7831 div()
7832 .flex()
7833 .flex_col()
7834 .flex_1()
7835 .overflow_hidden()
7836 .child(
7837 h_flex()
7838 .flex_1()
7839 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7840 .child(self.center.render(
7841 self.zoomed.as_ref(),
7842 &PaneRenderContext {
7843 follower_states:
7844 &self.follower_states,
7845 active_call: self.active_call(),
7846 active_pane: &self.active_pane,
7847 app_state: &self.app_state,
7848 project: &self.project,
7849 workspace: &self.weak_self,
7850 },
7851 window,
7852 cx,
7853 ))
7854 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7855 )
7856 )
7857
7858 )
7859 .child(
7860 div()
7861 .w_full()
7862 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7863 ),
7864 )
7865 .children(self.render_dock(
7866 DockPosition::Right,
7867 &self.right_dock,
7868 window,
7869 cx,
7870 )),
7871 BottomDockLayout::RightAligned => div()
7872 .flex()
7873 .flex_row()
7874 .h_full()
7875 .children(self.render_dock(
7876 DockPosition::Left,
7877 &self.left_dock,
7878 window,
7879 cx,
7880 ))
7881
7882 .child(
7883 div()
7884 .flex()
7885 .flex_col()
7886 .flex_1()
7887 .h_full()
7888 .child(
7889 div()
7890 .flex()
7891 .flex_row()
7892 .flex_1()
7893 .child(
7894 div()
7895 .flex()
7896 .flex_col()
7897 .flex_1()
7898 .overflow_hidden()
7899 .child(
7900 h_flex()
7901 .flex_1()
7902 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7903 .child(self.center.render(
7904 self.zoomed.as_ref(),
7905 &PaneRenderContext {
7906 follower_states:
7907 &self.follower_states,
7908 active_call: self.active_call(),
7909 active_pane: &self.active_pane,
7910 app_state: &self.app_state,
7911 project: &self.project,
7912 workspace: &self.weak_self,
7913 },
7914 window,
7915 cx,
7916 ))
7917 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7918 )
7919 )
7920
7921 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
7922 )
7923 .child(
7924 div()
7925 .w_full()
7926 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7927 ),
7928 ),
7929 BottomDockLayout::Contained => div()
7930 .flex()
7931 .flex_row()
7932 .h_full()
7933 .children(self.render_dock(
7934 DockPosition::Left,
7935 &self.left_dock,
7936 window,
7937 cx,
7938 ))
7939
7940 .child(
7941 div()
7942 .flex()
7943 .flex_col()
7944 .flex_1()
7945 .overflow_hidden()
7946 .child(
7947 h_flex()
7948 .flex_1()
7949 .when_some(paddings.0, |this, p| {
7950 this.child(p.border_r_1())
7951 })
7952 .child(self.center.render(
7953 self.zoomed.as_ref(),
7954 &PaneRenderContext {
7955 follower_states:
7956 &self.follower_states,
7957 active_call: self.active_call(),
7958 active_pane: &self.active_pane,
7959 app_state: &self.app_state,
7960 project: &self.project,
7961 workspace: &self.weak_self,
7962 },
7963 window,
7964 cx,
7965 ))
7966 .when_some(paddings.1, |this, p| {
7967 this.child(p.border_l_1())
7968 }),
7969 )
7970 .children(self.render_dock(
7971 DockPosition::Bottom,
7972 &self.bottom_dock,
7973 window,
7974 cx,
7975 )),
7976 )
7977
7978 .children(self.render_dock(
7979 DockPosition::Right,
7980 &self.right_dock,
7981 window,
7982 cx,
7983 )),
7984 }
7985 })
7986 .children(self.zoomed.as_ref().and_then(|view| {
7987 let zoomed_view = view.upgrade()?;
7988 let div = div()
7989 .occlude()
7990 .absolute()
7991 .overflow_hidden()
7992 .border_color(colors.border)
7993 .bg(colors.background)
7994 .child(zoomed_view)
7995 .inset_0()
7996 .shadow_lg();
7997
7998 if !WorkspaceSettings::get_global(cx).zoomed_padding {
7999 return Some(div);
8000 }
8001
8002 Some(match self.zoomed_position {
8003 Some(DockPosition::Left) => div.right_2().border_r_1(),
8004 Some(DockPosition::Right) => div.left_2().border_l_1(),
8005 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8006 None => {
8007 div.top_2().bottom_2().left_2().right_2().border_1()
8008 }
8009 })
8010 }))
8011 .children(self.render_notifications(window, cx)),
8012 )
8013 .when(self.status_bar_visible(cx), |parent| {
8014 parent.child(self.status_bar.clone())
8015 })
8016 .child(self.toast_layer.clone()),
8017 )
8018 }
8019}
8020
8021impl WorkspaceStore {
8022 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8023 Self {
8024 workspaces: Default::default(),
8025 _subscriptions: vec![
8026 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8027 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8028 ],
8029 client,
8030 }
8031 }
8032
8033 pub fn update_followers(
8034 &self,
8035 project_id: Option<u64>,
8036 update: proto::update_followers::Variant,
8037 cx: &App,
8038 ) -> Option<()> {
8039 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8040 let room_id = active_call.0.room_id(cx)?;
8041 self.client
8042 .send(proto::UpdateFollowers {
8043 room_id,
8044 project_id,
8045 variant: Some(update),
8046 })
8047 .log_err()
8048 }
8049
8050 pub async fn handle_follow(
8051 this: Entity<Self>,
8052 envelope: TypedEnvelope<proto::Follow>,
8053 mut cx: AsyncApp,
8054 ) -> Result<proto::FollowResponse> {
8055 this.update(&mut cx, |this, cx| {
8056 let follower = Follower {
8057 project_id: envelope.payload.project_id,
8058 peer_id: envelope.original_sender_id()?,
8059 };
8060
8061 let mut response = proto::FollowResponse::default();
8062
8063 this.workspaces.retain(|(window_handle, weak_workspace)| {
8064 let Some(workspace) = weak_workspace.upgrade() else {
8065 return false;
8066 };
8067 window_handle
8068 .update(cx, |_, window, cx| {
8069 workspace.update(cx, |workspace, cx| {
8070 let handler_response =
8071 workspace.handle_follow(follower.project_id, window, cx);
8072 if let Some(active_view) = handler_response.active_view
8073 && workspace.project.read(cx).remote_id() == follower.project_id
8074 {
8075 response.active_view = Some(active_view)
8076 }
8077 });
8078 })
8079 .is_ok()
8080 });
8081
8082 Ok(response)
8083 })
8084 }
8085
8086 async fn handle_update_followers(
8087 this: Entity<Self>,
8088 envelope: TypedEnvelope<proto::UpdateFollowers>,
8089 mut cx: AsyncApp,
8090 ) -> Result<()> {
8091 let leader_id = envelope.original_sender_id()?;
8092 let update = envelope.payload;
8093
8094 this.update(&mut cx, |this, cx| {
8095 this.workspaces.retain(|(window_handle, weak_workspace)| {
8096 let Some(workspace) = weak_workspace.upgrade() else {
8097 return false;
8098 };
8099 window_handle
8100 .update(cx, |_, window, cx| {
8101 workspace.update(cx, |workspace, cx| {
8102 let project_id = workspace.project.read(cx).remote_id();
8103 if update.project_id != project_id && update.project_id.is_some() {
8104 return;
8105 }
8106 workspace.handle_update_followers(
8107 leader_id,
8108 update.clone(),
8109 window,
8110 cx,
8111 );
8112 });
8113 })
8114 .is_ok()
8115 });
8116 Ok(())
8117 })
8118 }
8119
8120 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8121 self.workspaces.iter().map(|(_, weak)| weak)
8122 }
8123
8124 pub fn workspaces_with_windows(
8125 &self,
8126 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8127 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8128 }
8129}
8130
8131impl ViewId {
8132 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8133 Ok(Self {
8134 creator: message
8135 .creator
8136 .map(CollaboratorId::PeerId)
8137 .context("creator is missing")?,
8138 id: message.id,
8139 })
8140 }
8141
8142 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8143 if let CollaboratorId::PeerId(peer_id) = self.creator {
8144 Some(proto::ViewId {
8145 creator: Some(peer_id),
8146 id: self.id,
8147 })
8148 } else {
8149 None
8150 }
8151 }
8152}
8153
8154impl FollowerState {
8155 fn pane(&self) -> &Entity<Pane> {
8156 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8157 }
8158}
8159
8160pub trait WorkspaceHandle {
8161 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8162}
8163
8164impl WorkspaceHandle for Entity<Workspace> {
8165 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8166 self.read(cx)
8167 .worktrees(cx)
8168 .flat_map(|worktree| {
8169 let worktree_id = worktree.read(cx).id();
8170 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8171 worktree_id,
8172 path: f.path.clone(),
8173 })
8174 })
8175 .collect::<Vec<_>>()
8176 }
8177}
8178
8179pub async fn last_opened_workspace_location(
8180 fs: &dyn fs::Fs,
8181) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8182 DB.last_workspace(fs)
8183 .await
8184 .log_err()
8185 .flatten()
8186 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8187}
8188
8189pub async fn last_session_workspace_locations(
8190 last_session_id: &str,
8191 last_session_window_stack: Option<Vec<WindowId>>,
8192 fs: &dyn fs::Fs,
8193) -> Option<Vec<SessionWorkspace>> {
8194 DB.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8195 .await
8196 .log_err()
8197}
8198
8199pub struct MultiWorkspaceRestoreResult {
8200 pub window_handle: WindowHandle<MultiWorkspace>,
8201 pub errors: Vec<anyhow::Error>,
8202}
8203
8204pub async fn restore_multiworkspace(
8205 multi_workspace: SerializedMultiWorkspace,
8206 app_state: Arc<AppState>,
8207 cx: &mut AsyncApp,
8208) -> anyhow::Result<MultiWorkspaceRestoreResult> {
8209 let SerializedMultiWorkspace {
8210 workspaces,
8211 state,
8212 id: window_id,
8213 } = multi_workspace;
8214 let mut group_iter = workspaces.into_iter();
8215 let first = group_iter
8216 .next()
8217 .context("window group must not be empty")?;
8218
8219 let window_handle = if first.paths.is_empty() {
8220 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
8221 .await?
8222 } else {
8223 let OpenResult { window, .. } = cx
8224 .update(|cx| {
8225 Workspace::new_local(
8226 first.paths.paths().to_vec(),
8227 app_state.clone(),
8228 None,
8229 None,
8230 None,
8231 true,
8232 cx,
8233 )
8234 })
8235 .await?;
8236 window
8237 };
8238
8239 let mut errors = Vec::new();
8240
8241 for session_workspace in group_iter {
8242 let error = if session_workspace.paths.is_empty() {
8243 cx.update(|cx| {
8244 open_workspace_by_id(
8245 session_workspace.workspace_id,
8246 app_state.clone(),
8247 Some(window_handle),
8248 cx,
8249 )
8250 })
8251 .await
8252 .err()
8253 } else {
8254 cx.update(|cx| {
8255 Workspace::new_local(
8256 session_workspace.paths.paths().to_vec(),
8257 app_state.clone(),
8258 Some(window_handle),
8259 None,
8260 None,
8261 true,
8262 cx,
8263 )
8264 })
8265 .await
8266 .err()
8267 };
8268
8269 if let Some(error) = error {
8270 errors.push(error);
8271 }
8272 }
8273
8274 if let Some(target_id) = state.active_workspace_id {
8275 window_handle
8276 .update(cx, |multi_workspace, window, cx| {
8277 multi_workspace.set_database_id(window_id);
8278 let target_index = multi_workspace
8279 .workspaces()
8280 .iter()
8281 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8282 if let Some(index) = target_index {
8283 multi_workspace.activate_index(index, window, cx);
8284 } else if !multi_workspace.workspaces().is_empty() {
8285 multi_workspace.activate_index(0, window, cx);
8286 }
8287 })
8288 .ok();
8289 } else {
8290 window_handle
8291 .update(cx, |multi_workspace, window, cx| {
8292 if !multi_workspace.workspaces().is_empty() {
8293 multi_workspace.activate_index(0, window, cx);
8294 }
8295 })
8296 .ok();
8297 }
8298
8299 window_handle
8300 .update(cx, |_, window, _cx| {
8301 window.activate_window();
8302 })
8303 .ok();
8304
8305 Ok(MultiWorkspaceRestoreResult {
8306 window_handle,
8307 errors,
8308 })
8309}
8310
8311actions!(
8312 collab,
8313 [
8314 /// Opens the channel notes for the current call.
8315 ///
8316 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8317 /// channel in the collab panel.
8318 ///
8319 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8320 /// can be copied via "Copy link to section" in the context menu of the channel notes
8321 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8322 OpenChannelNotes,
8323 /// Mutes your microphone.
8324 Mute,
8325 /// Deafens yourself (mute both microphone and speakers).
8326 Deafen,
8327 /// Leaves the current call.
8328 LeaveCall,
8329 /// Shares the current project with collaborators.
8330 ShareProject,
8331 /// Shares your screen with collaborators.
8332 ScreenShare,
8333 /// Copies the current room name and session id for debugging purposes.
8334 CopyRoomId,
8335 ]
8336);
8337
8338/// Opens the channel notes for a specific channel by its ID.
8339#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8340#[action(namespace = collab)]
8341#[serde(deny_unknown_fields)]
8342pub struct OpenChannelNotesById {
8343 pub channel_id: u64,
8344}
8345
8346actions!(
8347 zed,
8348 [
8349 /// Opens the Zed log file.
8350 OpenLog,
8351 /// Reveals the Zed log file in the system file manager.
8352 RevealLogInFileManager
8353 ]
8354);
8355
8356async fn join_channel_internal(
8357 channel_id: ChannelId,
8358 app_state: &Arc<AppState>,
8359 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8360 requesting_workspace: Option<WeakEntity<Workspace>>,
8361 active_call: &dyn AnyActiveCall,
8362 cx: &mut AsyncApp,
8363) -> Result<bool> {
8364 let (should_prompt, already_in_channel) = cx.update(|cx| {
8365 if !active_call.is_in_room(cx) {
8366 return (false, false);
8367 }
8368
8369 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8370 let should_prompt = active_call.is_sharing_project(cx)
8371 && active_call.has_remote_participants(cx)
8372 && !already_in_channel;
8373 (should_prompt, already_in_channel)
8374 });
8375
8376 if already_in_channel {
8377 let task = cx.update(|cx| {
8378 if let Some((project, host)) = active_call.most_active_project(cx) {
8379 Some(join_in_room_project(project, host, app_state.clone(), cx))
8380 } else {
8381 None
8382 }
8383 });
8384 if let Some(task) = task {
8385 task.await?;
8386 }
8387 return anyhow::Ok(true);
8388 }
8389
8390 if should_prompt {
8391 if let Some(multi_workspace) = requesting_window {
8392 let answer = multi_workspace
8393 .update(cx, |_, window, cx| {
8394 window.prompt(
8395 PromptLevel::Warning,
8396 "Do you want to switch channels?",
8397 Some("Leaving this call will unshare your current project."),
8398 &["Yes, Join Channel", "Cancel"],
8399 cx,
8400 )
8401 })?
8402 .await;
8403
8404 if answer == Ok(1) {
8405 return Ok(false);
8406 }
8407 } else {
8408 return Ok(false);
8409 }
8410 }
8411
8412 let client = cx.update(|cx| active_call.client(cx));
8413
8414 let mut client_status = client.status();
8415
8416 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8417 'outer: loop {
8418 let Some(status) = client_status.recv().await else {
8419 anyhow::bail!("error connecting");
8420 };
8421
8422 match status {
8423 Status::Connecting
8424 | Status::Authenticating
8425 | Status::Authenticated
8426 | Status::Reconnecting
8427 | Status::Reauthenticating
8428 | Status::Reauthenticated => continue,
8429 Status::Connected { .. } => break 'outer,
8430 Status::SignedOut | Status::AuthenticationError => {
8431 return Err(ErrorCode::SignedOut.into());
8432 }
8433 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8434 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8435 return Err(ErrorCode::Disconnected.into());
8436 }
8437 }
8438 }
8439
8440 let joined = cx
8441 .update(|cx| active_call.join_channel(channel_id, cx))
8442 .await?;
8443
8444 if !joined {
8445 return anyhow::Ok(true);
8446 }
8447
8448 cx.update(|cx| active_call.room_update_completed(cx)).await;
8449
8450 let task = cx.update(|cx| {
8451 if let Some((project, host)) = active_call.most_active_project(cx) {
8452 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8453 }
8454
8455 // If you are the first to join a channel, see if you should share your project.
8456 if !active_call.has_remote_participants(cx)
8457 && !active_call.local_participant_is_guest(cx)
8458 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8459 {
8460 let project = workspace.update(cx, |workspace, cx| {
8461 let project = workspace.project.read(cx);
8462
8463 if !active_call.share_on_join(cx) {
8464 return None;
8465 }
8466
8467 if (project.is_local() || project.is_via_remote_server())
8468 && project.visible_worktrees(cx).any(|tree| {
8469 tree.read(cx)
8470 .root_entry()
8471 .is_some_and(|entry| entry.is_dir())
8472 })
8473 {
8474 Some(workspace.project.clone())
8475 } else {
8476 None
8477 }
8478 });
8479 if let Some(project) = project {
8480 let share_task = active_call.share_project(project, cx);
8481 return Some(cx.spawn(async move |_cx| -> Result<()> {
8482 share_task.await?;
8483 Ok(())
8484 }));
8485 }
8486 }
8487
8488 None
8489 });
8490 if let Some(task) = task {
8491 task.await?;
8492 return anyhow::Ok(true);
8493 }
8494 anyhow::Ok(false)
8495}
8496
8497pub fn join_channel(
8498 channel_id: ChannelId,
8499 app_state: Arc<AppState>,
8500 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8501 requesting_workspace: Option<WeakEntity<Workspace>>,
8502 cx: &mut App,
8503) -> Task<Result<()>> {
8504 let active_call = GlobalAnyActiveCall::global(cx).clone();
8505 cx.spawn(async move |cx| {
8506 let result = join_channel_internal(
8507 channel_id,
8508 &app_state,
8509 requesting_window,
8510 requesting_workspace,
8511 &*active_call.0,
8512 cx,
8513 )
8514 .await;
8515
8516 // join channel succeeded, and opened a window
8517 if matches!(result, Ok(true)) {
8518 return anyhow::Ok(());
8519 }
8520
8521 // find an existing workspace to focus and show call controls
8522 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8523 if active_window.is_none() {
8524 // no open workspaces, make one to show the error in (blergh)
8525 let OpenResult {
8526 window: window_handle,
8527 ..
8528 } = cx
8529 .update(|cx| {
8530 Workspace::new_local(
8531 vec![],
8532 app_state.clone(),
8533 requesting_window,
8534 None,
8535 None,
8536 true,
8537 cx,
8538 )
8539 })
8540 .await?;
8541
8542 window_handle
8543 .update(cx, |_, window, _cx| {
8544 window.activate_window();
8545 })
8546 .ok();
8547
8548 if result.is_ok() {
8549 cx.update(|cx| {
8550 cx.dispatch_action(&OpenChannelNotes);
8551 });
8552 }
8553
8554 active_window = Some(window_handle);
8555 }
8556
8557 if let Err(err) = result {
8558 log::error!("failed to join channel: {}", err);
8559 if let Some(active_window) = active_window {
8560 active_window
8561 .update(cx, |_, window, cx| {
8562 let detail: SharedString = match err.error_code() {
8563 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8564 ErrorCode::UpgradeRequired => concat!(
8565 "Your are running an unsupported version of Zed. ",
8566 "Please update to continue."
8567 )
8568 .into(),
8569 ErrorCode::NoSuchChannel => concat!(
8570 "No matching channel was found. ",
8571 "Please check the link and try again."
8572 )
8573 .into(),
8574 ErrorCode::Forbidden => concat!(
8575 "This channel is private, and you do not have access. ",
8576 "Please ask someone to add you and try again."
8577 )
8578 .into(),
8579 ErrorCode::Disconnected => {
8580 "Please check your internet connection and try again.".into()
8581 }
8582 _ => format!("{}\n\nPlease try again.", err).into(),
8583 };
8584 window.prompt(
8585 PromptLevel::Critical,
8586 "Failed to join channel",
8587 Some(&detail),
8588 &["Ok"],
8589 cx,
8590 )
8591 })?
8592 .await
8593 .ok();
8594 }
8595 }
8596
8597 // return ok, we showed the error to the user.
8598 anyhow::Ok(())
8599 })
8600}
8601
8602pub async fn get_any_active_multi_workspace(
8603 app_state: Arc<AppState>,
8604 mut cx: AsyncApp,
8605) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8606 // find an existing workspace to focus and show call controls
8607 let active_window = activate_any_workspace_window(&mut cx);
8608 if active_window.is_none() {
8609 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
8610 .await?;
8611 }
8612 activate_any_workspace_window(&mut cx).context("could not open zed")
8613}
8614
8615fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
8616 cx.update(|cx| {
8617 if let Some(workspace_window) = cx
8618 .active_window()
8619 .and_then(|window| window.downcast::<MultiWorkspace>())
8620 {
8621 return Some(workspace_window);
8622 }
8623
8624 for window in cx.windows() {
8625 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
8626 workspace_window
8627 .update(cx, |_, window, _| window.activate_window())
8628 .ok();
8629 return Some(workspace_window);
8630 }
8631 }
8632 None
8633 })
8634}
8635
8636pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
8637 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
8638}
8639
8640pub fn workspace_windows_for_location(
8641 serialized_location: &SerializedWorkspaceLocation,
8642 cx: &App,
8643) -> Vec<WindowHandle<MultiWorkspace>> {
8644 cx.windows()
8645 .into_iter()
8646 .filter_map(|window| window.downcast::<MultiWorkspace>())
8647 .filter(|multi_workspace| {
8648 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
8649 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
8650 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
8651 }
8652 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
8653 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
8654 a.distro_name == b.distro_name
8655 }
8656 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
8657 a.container_id == b.container_id
8658 }
8659 #[cfg(any(test, feature = "test-support"))]
8660 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
8661 a.id == b.id
8662 }
8663 _ => false,
8664 };
8665
8666 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
8667 multi_workspace.workspaces().iter().any(|workspace| {
8668 match workspace.read(cx).workspace_location(cx) {
8669 WorkspaceLocation::Location(location, _) => {
8670 match (&location, serialized_location) {
8671 (
8672 SerializedWorkspaceLocation::Local,
8673 SerializedWorkspaceLocation::Local,
8674 ) => true,
8675 (
8676 SerializedWorkspaceLocation::Remote(a),
8677 SerializedWorkspaceLocation::Remote(b),
8678 ) => same_host(a, b),
8679 _ => false,
8680 }
8681 }
8682 _ => false,
8683 }
8684 })
8685 })
8686 })
8687 .collect()
8688}
8689
8690pub async fn find_existing_workspace(
8691 abs_paths: &[PathBuf],
8692 open_options: &OpenOptions,
8693 location: &SerializedWorkspaceLocation,
8694 cx: &mut AsyncApp,
8695) -> (
8696 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
8697 OpenVisible,
8698) {
8699 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
8700 let mut open_visible = OpenVisible::All;
8701 let mut best_match = None;
8702
8703 if open_options.open_new_workspace != Some(true) {
8704 cx.update(|cx| {
8705 for window in workspace_windows_for_location(location, cx) {
8706 if let Ok(multi_workspace) = window.read(cx) {
8707 for workspace in multi_workspace.workspaces() {
8708 let project = workspace.read(cx).project.read(cx);
8709 let m = project.visibility_for_paths(
8710 abs_paths,
8711 open_options.open_new_workspace == None,
8712 cx,
8713 );
8714 if m > best_match {
8715 existing = Some((window, workspace.clone()));
8716 best_match = m;
8717 } else if best_match.is_none()
8718 && open_options.open_new_workspace == Some(false)
8719 {
8720 existing = Some((window, workspace.clone()))
8721 }
8722 }
8723 }
8724 }
8725 });
8726
8727 let all_paths_are_files = existing
8728 .as_ref()
8729 .and_then(|(_, target_workspace)| {
8730 cx.update(|cx| {
8731 let workspace = target_workspace.read(cx);
8732 let project = workspace.project.read(cx);
8733 let path_style = workspace.path_style(cx);
8734 Some(!abs_paths.iter().any(|path| {
8735 let path = util::paths::SanitizedPath::new(path);
8736 project.worktrees(cx).any(|worktree| {
8737 let worktree = worktree.read(cx);
8738 let abs_path = worktree.abs_path();
8739 path_style
8740 .strip_prefix(path.as_ref(), abs_path.as_ref())
8741 .and_then(|rel| worktree.entry_for_path(&rel))
8742 .is_some_and(|e| e.is_dir())
8743 })
8744 }))
8745 })
8746 })
8747 .unwrap_or(false);
8748
8749 if open_options.open_new_workspace.is_none()
8750 && existing.is_some()
8751 && open_options.wait
8752 && all_paths_are_files
8753 {
8754 cx.update(|cx| {
8755 let windows = workspace_windows_for_location(location, cx);
8756 let window = cx
8757 .active_window()
8758 .and_then(|window| window.downcast::<MultiWorkspace>())
8759 .filter(|window| windows.contains(window))
8760 .or_else(|| windows.into_iter().next());
8761 if let Some(window) = window {
8762 if let Ok(multi_workspace) = window.read(cx) {
8763 let active_workspace = multi_workspace.workspace().clone();
8764 existing = Some((window, active_workspace));
8765 open_visible = OpenVisible::None;
8766 }
8767 }
8768 });
8769 }
8770 }
8771 (existing, open_visible)
8772}
8773
8774#[derive(Default, Clone)]
8775pub struct OpenOptions {
8776 pub visible: Option<OpenVisible>,
8777 pub focus: Option<bool>,
8778 pub open_new_workspace: Option<bool>,
8779 pub wait: bool,
8780 pub replace_window: Option<WindowHandle<MultiWorkspace>>,
8781 pub env: Option<HashMap<String, String>>,
8782}
8783
8784/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
8785/// or [`Workspace::open_workspace_for_paths`].
8786pub struct OpenResult {
8787 pub window: WindowHandle<MultiWorkspace>,
8788 pub workspace: Entity<Workspace>,
8789 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
8790}
8791
8792/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
8793pub fn open_workspace_by_id(
8794 workspace_id: WorkspaceId,
8795 app_state: Arc<AppState>,
8796 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8797 cx: &mut App,
8798) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
8799 let project_handle = Project::local(
8800 app_state.client.clone(),
8801 app_state.node_runtime.clone(),
8802 app_state.user_store.clone(),
8803 app_state.languages.clone(),
8804 app_state.fs.clone(),
8805 None,
8806 project::LocalProjectFlags {
8807 init_worktree_trust: true,
8808 ..project::LocalProjectFlags::default()
8809 },
8810 cx,
8811 );
8812
8813 cx.spawn(async move |cx| {
8814 let serialized_workspace = persistence::DB
8815 .workspace_for_id(workspace_id)
8816 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
8817
8818 let centered_layout = serialized_workspace.centered_layout;
8819
8820 let (window, workspace) = if let Some(window) = requesting_window {
8821 let workspace = window.update(cx, |multi_workspace, window, cx| {
8822 let workspace = cx.new(|cx| {
8823 let mut workspace = Workspace::new(
8824 Some(workspace_id),
8825 project_handle.clone(),
8826 app_state.clone(),
8827 window,
8828 cx,
8829 );
8830 workspace.centered_layout = centered_layout;
8831 workspace
8832 });
8833 multi_workspace.add_workspace(workspace.clone(), cx);
8834 workspace
8835 })?;
8836 (window, workspace)
8837 } else {
8838 let window_bounds_override = window_bounds_env_override();
8839
8840 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
8841 (Some(WindowBounds::Windowed(bounds)), None)
8842 } else if let Some(display) = serialized_workspace.display
8843 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
8844 {
8845 (Some(bounds.0), Some(display))
8846 } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
8847 (Some(bounds), Some(display))
8848 } else {
8849 (None, None)
8850 };
8851
8852 let options = cx.update(|cx| {
8853 let mut options = (app_state.build_window_options)(display, cx);
8854 options.window_bounds = window_bounds;
8855 options
8856 });
8857
8858 let window = cx.open_window(options, {
8859 let app_state = app_state.clone();
8860 let project_handle = project_handle.clone();
8861 move |window, cx| {
8862 let workspace = cx.new(|cx| {
8863 let mut workspace = Workspace::new(
8864 Some(workspace_id),
8865 project_handle,
8866 app_state,
8867 window,
8868 cx,
8869 );
8870 workspace.centered_layout = centered_layout;
8871 workspace
8872 });
8873 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
8874 }
8875 })?;
8876
8877 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
8878 multi_workspace.workspace().clone()
8879 })?;
8880
8881 (window, workspace)
8882 };
8883
8884 notify_if_database_failed(window, cx);
8885
8886 // Restore items from the serialized workspace
8887 window
8888 .update(cx, |_, window, cx| {
8889 workspace.update(cx, |_workspace, cx| {
8890 open_items(Some(serialized_workspace), vec![], window, cx)
8891 })
8892 })?
8893 .await?;
8894
8895 window.update(cx, |_, window, cx| {
8896 workspace.update(cx, |workspace, cx| {
8897 workspace.serialize_workspace(window, cx);
8898 });
8899 })?;
8900
8901 Ok(window)
8902 })
8903}
8904
8905#[allow(clippy::type_complexity)]
8906pub fn open_paths(
8907 abs_paths: &[PathBuf],
8908 app_state: Arc<AppState>,
8909 open_options: OpenOptions,
8910 cx: &mut App,
8911) -> Task<anyhow::Result<OpenResult>> {
8912 let abs_paths = abs_paths.to_vec();
8913 #[cfg(target_os = "windows")]
8914 let wsl_path = abs_paths
8915 .iter()
8916 .find_map(|p| util::paths::WslPath::from_path(p));
8917
8918 cx.spawn(async move |cx| {
8919 let (mut existing, mut open_visible) = find_existing_workspace(
8920 &abs_paths,
8921 &open_options,
8922 &SerializedWorkspaceLocation::Local,
8923 cx,
8924 )
8925 .await;
8926
8927 // Fallback: if no workspace contains the paths and all paths are files,
8928 // prefer an existing local workspace window (active window first).
8929 if open_options.open_new_workspace.is_none() && existing.is_none() {
8930 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
8931 let all_metadatas = futures::future::join_all(all_paths)
8932 .await
8933 .into_iter()
8934 .filter_map(|result| result.ok().flatten())
8935 .collect::<Vec<_>>();
8936
8937 if all_metadatas.iter().all(|file| !file.is_dir) {
8938 cx.update(|cx| {
8939 let windows = workspace_windows_for_location(
8940 &SerializedWorkspaceLocation::Local,
8941 cx,
8942 );
8943 let window = cx
8944 .active_window()
8945 .and_then(|window| window.downcast::<MultiWorkspace>())
8946 .filter(|window| windows.contains(window))
8947 .or_else(|| windows.into_iter().next());
8948 if let Some(window) = window {
8949 if let Ok(multi_workspace) = window.read(cx) {
8950 let active_workspace = multi_workspace.workspace().clone();
8951 existing = Some((window, active_workspace));
8952 open_visible = OpenVisible::None;
8953 }
8954 }
8955 });
8956 }
8957 }
8958
8959 let result = if let Some((existing, target_workspace)) = existing {
8960 let open_task = existing
8961 .update(cx, |multi_workspace, window, cx| {
8962 window.activate_window();
8963 multi_workspace.activate(target_workspace.clone(), cx);
8964 target_workspace.update(cx, |workspace, cx| {
8965 workspace.open_paths(
8966 abs_paths,
8967 OpenOptions {
8968 visible: Some(open_visible),
8969 ..Default::default()
8970 },
8971 None,
8972 window,
8973 cx,
8974 )
8975 })
8976 })?
8977 .await;
8978
8979 _ = existing.update(cx, |multi_workspace, _, cx| {
8980 let workspace = multi_workspace.workspace().clone();
8981 workspace.update(cx, |workspace, cx| {
8982 for item in open_task.iter().flatten() {
8983 if let Err(e) = item {
8984 workspace.show_error(&e, cx);
8985 }
8986 }
8987 });
8988 });
8989
8990 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
8991 } else {
8992 let result = cx
8993 .update(move |cx| {
8994 Workspace::new_local(
8995 abs_paths,
8996 app_state.clone(),
8997 open_options.replace_window,
8998 open_options.env,
8999 None,
9000 true,
9001 cx,
9002 )
9003 })
9004 .await;
9005
9006 if let Ok(ref result) = result {
9007 result.window
9008 .update(cx, |_, window, _cx| {
9009 window.activate_window();
9010 })
9011 .log_err();
9012 }
9013
9014 result
9015 };
9016
9017 #[cfg(target_os = "windows")]
9018 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9019 && let Ok(ref result) = result
9020 {
9021 result.window
9022 .update(cx, move |multi_workspace, _window, cx| {
9023 struct OpenInWsl;
9024 let workspace = multi_workspace.workspace().clone();
9025 workspace.update(cx, |workspace, cx| {
9026 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9027 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9028 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9029 cx.new(move |cx| {
9030 MessageNotification::new(msg, cx)
9031 .primary_message("Open in WSL")
9032 .primary_icon(IconName::FolderOpen)
9033 .primary_on_click(move |window, cx| {
9034 window.dispatch_action(Box::new(remote::OpenWslPath {
9035 distro: remote::WslConnectionOptions {
9036 distro_name: distro.clone(),
9037 user: None,
9038 },
9039 paths: vec![path.clone().into()],
9040 }), cx)
9041 })
9042 })
9043 });
9044 });
9045 })
9046 .unwrap();
9047 };
9048 result
9049 })
9050}
9051
9052pub fn open_new(
9053 open_options: OpenOptions,
9054 app_state: Arc<AppState>,
9055 cx: &mut App,
9056 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9057) -> Task<anyhow::Result<()>> {
9058 let task = Workspace::new_local(
9059 Vec::new(),
9060 app_state,
9061 open_options.replace_window,
9062 open_options.env,
9063 Some(Box::new(init)),
9064 true,
9065 cx,
9066 );
9067 cx.spawn(async move |cx| {
9068 let OpenResult { window, .. } = task.await?;
9069 window
9070 .update(cx, |_, window, _cx| {
9071 window.activate_window();
9072 })
9073 .ok();
9074 Ok(())
9075 })
9076}
9077
9078pub fn create_and_open_local_file(
9079 path: &'static Path,
9080 window: &mut Window,
9081 cx: &mut Context<Workspace>,
9082 default_content: impl 'static + Send + FnOnce() -> Rope,
9083) -> Task<Result<Box<dyn ItemHandle>>> {
9084 cx.spawn_in(window, async move |workspace, cx| {
9085 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9086 if !fs.is_file(path).await {
9087 fs.create_file(path, Default::default()).await?;
9088 fs.save(path, &default_content(), Default::default())
9089 .await?;
9090 }
9091
9092 workspace
9093 .update_in(cx, |workspace, window, cx| {
9094 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9095 let path = workspace
9096 .project
9097 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9098 cx.spawn_in(window, async move |workspace, cx| {
9099 let path = path.await?;
9100 let mut items = workspace
9101 .update_in(cx, |workspace, window, cx| {
9102 workspace.open_paths(
9103 vec![path.to_path_buf()],
9104 OpenOptions {
9105 visible: Some(OpenVisible::None),
9106 ..Default::default()
9107 },
9108 None,
9109 window,
9110 cx,
9111 )
9112 })?
9113 .await;
9114 let item = items.pop().flatten();
9115 item.with_context(|| format!("path {path:?} is not a file"))?
9116 })
9117 })
9118 })?
9119 .await?
9120 .await
9121 })
9122}
9123
9124pub fn open_remote_project_with_new_connection(
9125 window: WindowHandle<MultiWorkspace>,
9126 remote_connection: Arc<dyn RemoteConnection>,
9127 cancel_rx: oneshot::Receiver<()>,
9128 delegate: Arc<dyn RemoteClientDelegate>,
9129 app_state: Arc<AppState>,
9130 paths: Vec<PathBuf>,
9131 cx: &mut App,
9132) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9133 cx.spawn(async move |cx| {
9134 let (workspace_id, serialized_workspace) =
9135 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9136 .await?;
9137
9138 let session = match cx
9139 .update(|cx| {
9140 remote::RemoteClient::new(
9141 ConnectionIdentifier::Workspace(workspace_id.0),
9142 remote_connection,
9143 cancel_rx,
9144 delegate,
9145 cx,
9146 )
9147 })
9148 .await?
9149 {
9150 Some(result) => result,
9151 None => return Ok(Vec::new()),
9152 };
9153
9154 let project = cx.update(|cx| {
9155 project::Project::remote(
9156 session,
9157 app_state.client.clone(),
9158 app_state.node_runtime.clone(),
9159 app_state.user_store.clone(),
9160 app_state.languages.clone(),
9161 app_state.fs.clone(),
9162 true,
9163 cx,
9164 )
9165 });
9166
9167 open_remote_project_inner(
9168 project,
9169 paths,
9170 workspace_id,
9171 serialized_workspace,
9172 app_state,
9173 window,
9174 cx,
9175 )
9176 .await
9177 })
9178}
9179
9180pub fn open_remote_project_with_existing_connection(
9181 connection_options: RemoteConnectionOptions,
9182 project: Entity<Project>,
9183 paths: Vec<PathBuf>,
9184 app_state: Arc<AppState>,
9185 window: WindowHandle<MultiWorkspace>,
9186 cx: &mut AsyncApp,
9187) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9188 cx.spawn(async move |cx| {
9189 let (workspace_id, serialized_workspace) =
9190 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9191
9192 open_remote_project_inner(
9193 project,
9194 paths,
9195 workspace_id,
9196 serialized_workspace,
9197 app_state,
9198 window,
9199 cx,
9200 )
9201 .await
9202 })
9203}
9204
9205async fn open_remote_project_inner(
9206 project: Entity<Project>,
9207 paths: Vec<PathBuf>,
9208 workspace_id: WorkspaceId,
9209 serialized_workspace: Option<SerializedWorkspace>,
9210 app_state: Arc<AppState>,
9211 window: WindowHandle<MultiWorkspace>,
9212 cx: &mut AsyncApp,
9213) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9214 let toolchains = DB.toolchains(workspace_id).await?;
9215 for (toolchain, worktree_path, path) in toolchains {
9216 project
9217 .update(cx, |this, cx| {
9218 let Some(worktree_id) =
9219 this.find_worktree(&worktree_path, cx)
9220 .and_then(|(worktree, rel_path)| {
9221 if rel_path.is_empty() {
9222 Some(worktree.read(cx).id())
9223 } else {
9224 None
9225 }
9226 })
9227 else {
9228 return Task::ready(None);
9229 };
9230
9231 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9232 })
9233 .await;
9234 }
9235 let mut project_paths_to_open = vec![];
9236 let mut project_path_errors = vec![];
9237
9238 for path in paths {
9239 let result = cx
9240 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9241 .await;
9242 match result {
9243 Ok((_, project_path)) => {
9244 project_paths_to_open.push((path.clone(), Some(project_path)));
9245 }
9246 Err(error) => {
9247 project_path_errors.push(error);
9248 }
9249 };
9250 }
9251
9252 if project_paths_to_open.is_empty() {
9253 return Err(project_path_errors.pop().context("no paths given")?);
9254 }
9255
9256 let workspace = window.update(cx, |multi_workspace, window, cx| {
9257 telemetry::event!("SSH Project Opened");
9258
9259 let new_workspace = cx.new(|cx| {
9260 let mut workspace =
9261 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9262 workspace.update_history(cx);
9263
9264 if let Some(ref serialized) = serialized_workspace {
9265 workspace.centered_layout = serialized.centered_layout;
9266 }
9267
9268 workspace
9269 });
9270
9271 multi_workspace.activate(new_workspace.clone(), cx);
9272 new_workspace
9273 })?;
9274
9275 let items = window
9276 .update(cx, |_, window, cx| {
9277 window.activate_window();
9278 workspace.update(cx, |_workspace, cx| {
9279 open_items(serialized_workspace, project_paths_to_open, window, cx)
9280 })
9281 })?
9282 .await?;
9283
9284 workspace.update(cx, |workspace, cx| {
9285 for error in project_path_errors {
9286 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9287 if let Some(path) = error.error_tag("path") {
9288 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9289 }
9290 } else {
9291 workspace.show_error(&error, cx)
9292 }
9293 }
9294 });
9295
9296 Ok(items.into_iter().map(|item| item?.ok()).collect())
9297}
9298
9299fn deserialize_remote_project(
9300 connection_options: RemoteConnectionOptions,
9301 paths: Vec<PathBuf>,
9302 cx: &AsyncApp,
9303) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9304 cx.background_spawn(async move {
9305 let remote_connection_id = persistence::DB
9306 .get_or_create_remote_connection(connection_options)
9307 .await?;
9308
9309 let serialized_workspace =
9310 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
9311
9312 let workspace_id = if let Some(workspace_id) =
9313 serialized_workspace.as_ref().map(|workspace| workspace.id)
9314 {
9315 workspace_id
9316 } else {
9317 persistence::DB.next_id().await?
9318 };
9319
9320 Ok((workspace_id, serialized_workspace))
9321 })
9322}
9323
9324pub fn join_in_room_project(
9325 project_id: u64,
9326 follow_user_id: u64,
9327 app_state: Arc<AppState>,
9328 cx: &mut App,
9329) -> Task<Result<()>> {
9330 let windows = cx.windows();
9331 cx.spawn(async move |cx| {
9332 let existing_window_and_workspace: Option<(
9333 WindowHandle<MultiWorkspace>,
9334 Entity<Workspace>,
9335 )> = windows.into_iter().find_map(|window_handle| {
9336 window_handle
9337 .downcast::<MultiWorkspace>()
9338 .and_then(|window_handle| {
9339 window_handle
9340 .update(cx, |multi_workspace, _window, cx| {
9341 for workspace in multi_workspace.workspaces() {
9342 if workspace.read(cx).project().read(cx).remote_id()
9343 == Some(project_id)
9344 {
9345 return Some((window_handle, workspace.clone()));
9346 }
9347 }
9348 None
9349 })
9350 .unwrap_or(None)
9351 })
9352 });
9353
9354 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9355 existing_window_and_workspace
9356 {
9357 existing_window
9358 .update(cx, |multi_workspace, _, cx| {
9359 multi_workspace.activate(target_workspace, cx);
9360 })
9361 .ok();
9362 existing_window
9363 } else {
9364 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9365 let project = cx
9366 .update(|cx| {
9367 active_call.0.join_project(
9368 project_id,
9369 app_state.languages.clone(),
9370 app_state.fs.clone(),
9371 cx,
9372 )
9373 })
9374 .await?;
9375
9376 let window_bounds_override = window_bounds_env_override();
9377 cx.update(|cx| {
9378 let mut options = (app_state.build_window_options)(None, cx);
9379 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9380 cx.open_window(options, |window, cx| {
9381 let workspace = cx.new(|cx| {
9382 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9383 });
9384 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9385 })
9386 })?
9387 };
9388
9389 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9390 cx.activate(true);
9391 window.activate_window();
9392
9393 // We set the active workspace above, so this is the correct workspace.
9394 let workspace = multi_workspace.workspace().clone();
9395 workspace.update(cx, |workspace, cx| {
9396 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9397 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9398 .or_else(|| {
9399 // If we couldn't follow the given user, follow the host instead.
9400 let collaborator = workspace
9401 .project()
9402 .read(cx)
9403 .collaborators()
9404 .values()
9405 .find(|collaborator| collaborator.is_host)?;
9406 Some(collaborator.peer_id)
9407 });
9408
9409 if let Some(follow_peer_id) = follow_peer_id {
9410 workspace.follow(follow_peer_id, window, cx);
9411 }
9412 });
9413 })?;
9414
9415 anyhow::Ok(())
9416 })
9417}
9418
9419pub fn reload(cx: &mut App) {
9420 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9421 let mut workspace_windows = cx
9422 .windows()
9423 .into_iter()
9424 .filter_map(|window| window.downcast::<MultiWorkspace>())
9425 .collect::<Vec<_>>();
9426
9427 // If multiple windows have unsaved changes, and need a save prompt,
9428 // prompt in the active window before switching to a different window.
9429 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9430
9431 let mut prompt = None;
9432 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9433 prompt = window
9434 .update(cx, |_, window, cx| {
9435 window.prompt(
9436 PromptLevel::Info,
9437 "Are you sure you want to restart?",
9438 None,
9439 &["Restart", "Cancel"],
9440 cx,
9441 )
9442 })
9443 .ok();
9444 }
9445
9446 cx.spawn(async move |cx| {
9447 if let Some(prompt) = prompt {
9448 let answer = prompt.await?;
9449 if answer != 0 {
9450 return anyhow::Ok(());
9451 }
9452 }
9453
9454 // If the user cancels any save prompt, then keep the app open.
9455 for window in workspace_windows {
9456 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9457 let workspace = multi_workspace.workspace().clone();
9458 workspace.update(cx, |workspace, cx| {
9459 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9460 })
9461 }) && !should_close.await?
9462 {
9463 return anyhow::Ok(());
9464 }
9465 }
9466 cx.update(|cx| cx.restart());
9467 anyhow::Ok(())
9468 })
9469 .detach_and_log_err(cx);
9470}
9471
9472fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9473 let mut parts = value.split(',');
9474 let x: usize = parts.next()?.parse().ok()?;
9475 let y: usize = parts.next()?.parse().ok()?;
9476 Some(point(px(x as f32), px(y as f32)))
9477}
9478
9479fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9480 let mut parts = value.split(',');
9481 let width: usize = parts.next()?.parse().ok()?;
9482 let height: usize = parts.next()?.parse().ok()?;
9483 Some(size(px(width as f32), px(height as f32)))
9484}
9485
9486/// Add client-side decorations (rounded corners, shadows, resize handling) when
9487/// appropriate.
9488///
9489/// The `border_radius_tiling` parameter allows overriding which corners get
9490/// rounded, independently of the actual window tiling state. This is used
9491/// specifically for the workspace switcher sidebar: when the sidebar is open,
9492/// we want square corners on the left (so the sidebar appears flush with the
9493/// window edge) but we still need the shadow padding for proper visual
9494/// appearance. Unlike actual window tiling, this only affects border radius -
9495/// not padding or shadows.
9496pub fn client_side_decorations(
9497 element: impl IntoElement,
9498 window: &mut Window,
9499 cx: &mut App,
9500 border_radius_tiling: Tiling,
9501) -> Stateful<Div> {
9502 const BORDER_SIZE: Pixels = px(1.0);
9503 let decorations = window.window_decorations();
9504 let tiling = match decorations {
9505 Decorations::Server => Tiling::default(),
9506 Decorations::Client { tiling } => tiling,
9507 };
9508
9509 match decorations {
9510 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9511 Decorations::Server => window.set_client_inset(px(0.0)),
9512 }
9513
9514 struct GlobalResizeEdge(ResizeEdge);
9515 impl Global for GlobalResizeEdge {}
9516
9517 div()
9518 .id("window-backdrop")
9519 .bg(transparent_black())
9520 .map(|div| match decorations {
9521 Decorations::Server => div,
9522 Decorations::Client { .. } => div
9523 .when(
9524 !(tiling.top
9525 || tiling.right
9526 || border_radius_tiling.top
9527 || border_radius_tiling.right),
9528 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9529 )
9530 .when(
9531 !(tiling.top
9532 || tiling.left
9533 || border_radius_tiling.top
9534 || border_radius_tiling.left),
9535 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9536 )
9537 .when(
9538 !(tiling.bottom
9539 || tiling.right
9540 || border_radius_tiling.bottom
9541 || border_radius_tiling.right),
9542 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9543 )
9544 .when(
9545 !(tiling.bottom
9546 || tiling.left
9547 || border_radius_tiling.bottom
9548 || border_radius_tiling.left),
9549 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9550 )
9551 .when(!tiling.top, |div| {
9552 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9553 })
9554 .when(!tiling.bottom, |div| {
9555 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9556 })
9557 .when(!tiling.left, |div| {
9558 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9559 })
9560 .when(!tiling.right, |div| {
9561 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9562 })
9563 .on_mouse_move(move |e, window, cx| {
9564 let size = window.window_bounds().get_bounds().size;
9565 let pos = e.position;
9566
9567 let new_edge =
9568 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9569
9570 let edge = cx.try_global::<GlobalResizeEdge>();
9571 if new_edge != edge.map(|edge| edge.0) {
9572 window
9573 .window_handle()
9574 .update(cx, |workspace, _, cx| {
9575 cx.notify(workspace.entity_id());
9576 })
9577 .ok();
9578 }
9579 })
9580 .on_mouse_down(MouseButton::Left, move |e, window, _| {
9581 let size = window.window_bounds().get_bounds().size;
9582 let pos = e.position;
9583
9584 let edge = match resize_edge(
9585 pos,
9586 theme::CLIENT_SIDE_DECORATION_SHADOW,
9587 size,
9588 tiling,
9589 ) {
9590 Some(value) => value,
9591 None => return,
9592 };
9593
9594 window.start_window_resize(edge);
9595 }),
9596 })
9597 .size_full()
9598 .child(
9599 div()
9600 .cursor(CursorStyle::Arrow)
9601 .map(|div| match decorations {
9602 Decorations::Server => div,
9603 Decorations::Client { .. } => div
9604 .border_color(cx.theme().colors().border)
9605 .when(
9606 !(tiling.top
9607 || tiling.right
9608 || border_radius_tiling.top
9609 || border_radius_tiling.right),
9610 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9611 )
9612 .when(
9613 !(tiling.top
9614 || tiling.left
9615 || border_radius_tiling.top
9616 || border_radius_tiling.left),
9617 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9618 )
9619 .when(
9620 !(tiling.bottom
9621 || tiling.right
9622 || border_radius_tiling.bottom
9623 || border_radius_tiling.right),
9624 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9625 )
9626 .when(
9627 !(tiling.bottom
9628 || tiling.left
9629 || border_radius_tiling.bottom
9630 || border_radius_tiling.left),
9631 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9632 )
9633 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
9634 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
9635 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
9636 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
9637 .when(!tiling.is_tiled(), |div| {
9638 div.shadow(vec![gpui::BoxShadow {
9639 color: Hsla {
9640 h: 0.,
9641 s: 0.,
9642 l: 0.,
9643 a: 0.4,
9644 },
9645 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
9646 spread_radius: px(0.),
9647 offset: point(px(0.0), px(0.0)),
9648 }])
9649 }),
9650 })
9651 .on_mouse_move(|_e, _, cx| {
9652 cx.stop_propagation();
9653 })
9654 .size_full()
9655 .child(element),
9656 )
9657 .map(|div| match decorations {
9658 Decorations::Server => div,
9659 Decorations::Client { tiling, .. } => div.child(
9660 canvas(
9661 |_bounds, window, _| {
9662 window.insert_hitbox(
9663 Bounds::new(
9664 point(px(0.0), px(0.0)),
9665 window.window_bounds().get_bounds().size,
9666 ),
9667 HitboxBehavior::Normal,
9668 )
9669 },
9670 move |_bounds, hitbox, window, cx| {
9671 let mouse = window.mouse_position();
9672 let size = window.window_bounds().get_bounds().size;
9673 let Some(edge) =
9674 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
9675 else {
9676 return;
9677 };
9678 cx.set_global(GlobalResizeEdge(edge));
9679 window.set_cursor_style(
9680 match edge {
9681 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
9682 ResizeEdge::Left | ResizeEdge::Right => {
9683 CursorStyle::ResizeLeftRight
9684 }
9685 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
9686 CursorStyle::ResizeUpLeftDownRight
9687 }
9688 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
9689 CursorStyle::ResizeUpRightDownLeft
9690 }
9691 },
9692 &hitbox,
9693 );
9694 },
9695 )
9696 .size_full()
9697 .absolute(),
9698 ),
9699 })
9700}
9701
9702fn resize_edge(
9703 pos: Point<Pixels>,
9704 shadow_size: Pixels,
9705 window_size: Size<Pixels>,
9706 tiling: Tiling,
9707) -> Option<ResizeEdge> {
9708 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
9709 if bounds.contains(&pos) {
9710 return None;
9711 }
9712
9713 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
9714 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
9715 if !tiling.top && top_left_bounds.contains(&pos) {
9716 return Some(ResizeEdge::TopLeft);
9717 }
9718
9719 let top_right_bounds = Bounds::new(
9720 Point::new(window_size.width - corner_size.width, px(0.)),
9721 corner_size,
9722 );
9723 if !tiling.top && top_right_bounds.contains(&pos) {
9724 return Some(ResizeEdge::TopRight);
9725 }
9726
9727 let bottom_left_bounds = Bounds::new(
9728 Point::new(px(0.), window_size.height - corner_size.height),
9729 corner_size,
9730 );
9731 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
9732 return Some(ResizeEdge::BottomLeft);
9733 }
9734
9735 let bottom_right_bounds = Bounds::new(
9736 Point::new(
9737 window_size.width - corner_size.width,
9738 window_size.height - corner_size.height,
9739 ),
9740 corner_size,
9741 );
9742 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
9743 return Some(ResizeEdge::BottomRight);
9744 }
9745
9746 if !tiling.top && pos.y < shadow_size {
9747 Some(ResizeEdge::Top)
9748 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
9749 Some(ResizeEdge::Bottom)
9750 } else if !tiling.left && pos.x < shadow_size {
9751 Some(ResizeEdge::Left)
9752 } else if !tiling.right && pos.x > window_size.width - shadow_size {
9753 Some(ResizeEdge::Right)
9754 } else {
9755 None
9756 }
9757}
9758
9759fn join_pane_into_active(
9760 active_pane: &Entity<Pane>,
9761 pane: &Entity<Pane>,
9762 window: &mut Window,
9763 cx: &mut App,
9764) {
9765 if pane == active_pane {
9766 } else if pane.read(cx).items_len() == 0 {
9767 pane.update(cx, |_, cx| {
9768 cx.emit(pane::Event::Remove {
9769 focus_on_pane: None,
9770 });
9771 })
9772 } else {
9773 move_all_items(pane, active_pane, window, cx);
9774 }
9775}
9776
9777fn move_all_items(
9778 from_pane: &Entity<Pane>,
9779 to_pane: &Entity<Pane>,
9780 window: &mut Window,
9781 cx: &mut App,
9782) {
9783 let destination_is_different = from_pane != to_pane;
9784 let mut moved_items = 0;
9785 for (item_ix, item_handle) in from_pane
9786 .read(cx)
9787 .items()
9788 .enumerate()
9789 .map(|(ix, item)| (ix, item.clone()))
9790 .collect::<Vec<_>>()
9791 {
9792 let ix = item_ix - moved_items;
9793 if destination_is_different {
9794 // Close item from previous pane
9795 from_pane.update(cx, |source, cx| {
9796 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
9797 });
9798 moved_items += 1;
9799 }
9800
9801 // This automatically removes duplicate items in the pane
9802 to_pane.update(cx, |destination, cx| {
9803 destination.add_item(item_handle, true, true, None, window, cx);
9804 window.focus(&destination.focus_handle(cx), cx)
9805 });
9806 }
9807}
9808
9809pub fn move_item(
9810 source: &Entity<Pane>,
9811 destination: &Entity<Pane>,
9812 item_id_to_move: EntityId,
9813 destination_index: usize,
9814 activate: bool,
9815 window: &mut Window,
9816 cx: &mut App,
9817) {
9818 let Some((item_ix, item_handle)) = source
9819 .read(cx)
9820 .items()
9821 .enumerate()
9822 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
9823 .map(|(ix, item)| (ix, item.clone()))
9824 else {
9825 // Tab was closed during drag
9826 return;
9827 };
9828
9829 if source != destination {
9830 // Close item from previous pane
9831 source.update(cx, |source, cx| {
9832 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
9833 });
9834 }
9835
9836 // This automatically removes duplicate items in the pane
9837 destination.update(cx, |destination, cx| {
9838 destination.add_item_inner(
9839 item_handle,
9840 activate,
9841 activate,
9842 activate,
9843 Some(destination_index),
9844 window,
9845 cx,
9846 );
9847 if activate {
9848 window.focus(&destination.focus_handle(cx), cx)
9849 }
9850 });
9851}
9852
9853pub fn move_active_item(
9854 source: &Entity<Pane>,
9855 destination: &Entity<Pane>,
9856 focus_destination: bool,
9857 close_if_empty: bool,
9858 window: &mut Window,
9859 cx: &mut App,
9860) {
9861 if source == destination {
9862 return;
9863 }
9864 let Some(active_item) = source.read(cx).active_item() else {
9865 return;
9866 };
9867 source.update(cx, |source_pane, cx| {
9868 let item_id = active_item.item_id();
9869 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
9870 destination.update(cx, |target_pane, cx| {
9871 target_pane.add_item(
9872 active_item,
9873 focus_destination,
9874 focus_destination,
9875 Some(target_pane.items_len()),
9876 window,
9877 cx,
9878 );
9879 });
9880 });
9881}
9882
9883pub fn clone_active_item(
9884 workspace_id: Option<WorkspaceId>,
9885 source: &Entity<Pane>,
9886 destination: &Entity<Pane>,
9887 focus_destination: bool,
9888 window: &mut Window,
9889 cx: &mut App,
9890) {
9891 if source == destination {
9892 return;
9893 }
9894 let Some(active_item) = source.read(cx).active_item() else {
9895 return;
9896 };
9897 if !active_item.can_split(cx) {
9898 return;
9899 }
9900 let destination = destination.downgrade();
9901 let task = active_item.clone_on_split(workspace_id, window, cx);
9902 window
9903 .spawn(cx, async move |cx| {
9904 let Some(clone) = task.await else {
9905 return;
9906 };
9907 destination
9908 .update_in(cx, |target_pane, window, cx| {
9909 target_pane.add_item(
9910 clone,
9911 focus_destination,
9912 focus_destination,
9913 Some(target_pane.items_len()),
9914 window,
9915 cx,
9916 );
9917 })
9918 .log_err();
9919 })
9920 .detach();
9921}
9922
9923#[derive(Debug)]
9924pub struct WorkspacePosition {
9925 pub window_bounds: Option<WindowBounds>,
9926 pub display: Option<Uuid>,
9927 pub centered_layout: bool,
9928}
9929
9930pub fn remote_workspace_position_from_db(
9931 connection_options: RemoteConnectionOptions,
9932 paths_to_open: &[PathBuf],
9933 cx: &App,
9934) -> Task<Result<WorkspacePosition>> {
9935 let paths = paths_to_open.to_vec();
9936
9937 cx.background_spawn(async move {
9938 let remote_connection_id = persistence::DB
9939 .get_or_create_remote_connection(connection_options)
9940 .await
9941 .context("fetching serialized ssh project")?;
9942 let serialized_workspace =
9943 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
9944
9945 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
9946 (Some(WindowBounds::Windowed(bounds)), None)
9947 } else {
9948 let restorable_bounds = serialized_workspace
9949 .as_ref()
9950 .and_then(|workspace| {
9951 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
9952 })
9953 .or_else(|| persistence::read_default_window_bounds());
9954
9955 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
9956 (Some(serialized_bounds), Some(serialized_display))
9957 } else {
9958 (None, None)
9959 }
9960 };
9961
9962 let centered_layout = serialized_workspace
9963 .as_ref()
9964 .map(|w| w.centered_layout)
9965 .unwrap_or(false);
9966
9967 Ok(WorkspacePosition {
9968 window_bounds,
9969 display,
9970 centered_layout,
9971 })
9972 })
9973}
9974
9975pub fn with_active_or_new_workspace(
9976 cx: &mut App,
9977 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
9978) {
9979 match cx
9980 .active_window()
9981 .and_then(|w| w.downcast::<MultiWorkspace>())
9982 {
9983 Some(multi_workspace) => {
9984 cx.defer(move |cx| {
9985 multi_workspace
9986 .update(cx, |multi_workspace, window, cx| {
9987 let workspace = multi_workspace.workspace().clone();
9988 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
9989 })
9990 .log_err();
9991 });
9992 }
9993 None => {
9994 let app_state = AppState::global(cx);
9995 if let Some(app_state) = app_state.upgrade() {
9996 open_new(
9997 OpenOptions::default(),
9998 app_state,
9999 cx,
10000 move |workspace, window, cx| f(workspace, window, cx),
10001 )
10002 .detach_and_log_err(cx);
10003 }
10004 }
10005 }
10006}
10007
10008#[cfg(test)]
10009mod tests {
10010 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10011
10012 use super::*;
10013 use crate::{
10014 dock::{PanelEvent, test::TestPanel},
10015 item::{
10016 ItemBufferKind, ItemEvent,
10017 test::{TestItem, TestProjectItem},
10018 },
10019 };
10020 use fs::FakeFs;
10021 use gpui::{
10022 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10023 UpdateGlobal, VisualTestContext, px,
10024 };
10025 use project::{Project, ProjectEntryId};
10026 use serde_json::json;
10027 use settings::SettingsStore;
10028 use util::path;
10029 use util::rel_path::rel_path;
10030
10031 #[gpui::test]
10032 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10033 init_test(cx);
10034
10035 let fs = FakeFs::new(cx.executor());
10036 let project = Project::test(fs, [], cx).await;
10037 let (workspace, cx) =
10038 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10039
10040 // Adding an item with no ambiguity renders the tab without detail.
10041 let item1 = cx.new(|cx| {
10042 let mut item = TestItem::new(cx);
10043 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10044 item
10045 });
10046 workspace.update_in(cx, |workspace, window, cx| {
10047 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10048 });
10049 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10050
10051 // Adding an item that creates ambiguity increases the level of detail on
10052 // both tabs.
10053 let item2 = cx.new_window_entity(|_window, cx| {
10054 let mut item = TestItem::new(cx);
10055 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10056 item
10057 });
10058 workspace.update_in(cx, |workspace, window, cx| {
10059 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10060 });
10061 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10062 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10063
10064 // Adding an item that creates ambiguity increases the level of detail only
10065 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10066 // we stop at the highest detail available.
10067 let item3 = cx.new(|cx| {
10068 let mut item = TestItem::new(cx);
10069 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10070 item
10071 });
10072 workspace.update_in(cx, |workspace, window, cx| {
10073 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10074 });
10075 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10076 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10077 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10078 }
10079
10080 #[gpui::test]
10081 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10082 init_test(cx);
10083
10084 let fs = FakeFs::new(cx.executor());
10085 fs.insert_tree(
10086 "/root1",
10087 json!({
10088 "one.txt": "",
10089 "two.txt": "",
10090 }),
10091 )
10092 .await;
10093 fs.insert_tree(
10094 "/root2",
10095 json!({
10096 "three.txt": "",
10097 }),
10098 )
10099 .await;
10100
10101 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10102 let (workspace, cx) =
10103 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10104 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10105 let worktree_id = project.update(cx, |project, cx| {
10106 project.worktrees(cx).next().unwrap().read(cx).id()
10107 });
10108
10109 let item1 = cx.new(|cx| {
10110 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10111 });
10112 let item2 = cx.new(|cx| {
10113 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10114 });
10115
10116 // Add an item to an empty pane
10117 workspace.update_in(cx, |workspace, window, cx| {
10118 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10119 });
10120 project.update(cx, |project, cx| {
10121 assert_eq!(
10122 project.active_entry(),
10123 project
10124 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10125 .map(|e| e.id)
10126 );
10127 });
10128 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10129
10130 // Add a second item to a non-empty pane
10131 workspace.update_in(cx, |workspace, window, cx| {
10132 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10133 });
10134 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10135 project.update(cx, |project, cx| {
10136 assert_eq!(
10137 project.active_entry(),
10138 project
10139 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10140 .map(|e| e.id)
10141 );
10142 });
10143
10144 // Close the active item
10145 pane.update_in(cx, |pane, window, cx| {
10146 pane.close_active_item(&Default::default(), window, cx)
10147 })
10148 .await
10149 .unwrap();
10150 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10151 project.update(cx, |project, cx| {
10152 assert_eq!(
10153 project.active_entry(),
10154 project
10155 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10156 .map(|e| e.id)
10157 );
10158 });
10159
10160 // Add a project folder
10161 project
10162 .update(cx, |project, cx| {
10163 project.find_or_create_worktree("root2", true, cx)
10164 })
10165 .await
10166 .unwrap();
10167 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10168
10169 // Remove a project folder
10170 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10171 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10172 }
10173
10174 #[gpui::test]
10175 async fn test_close_window(cx: &mut TestAppContext) {
10176 init_test(cx);
10177
10178 let fs = FakeFs::new(cx.executor());
10179 fs.insert_tree("/root", json!({ "one": "" })).await;
10180
10181 let project = Project::test(fs, ["root".as_ref()], cx).await;
10182 let (workspace, cx) =
10183 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10184
10185 // When there are no dirty items, there's nothing to do.
10186 let item1 = cx.new(TestItem::new);
10187 workspace.update_in(cx, |w, window, cx| {
10188 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10189 });
10190 let task = workspace.update_in(cx, |w, window, cx| {
10191 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10192 });
10193 assert!(task.await.unwrap());
10194
10195 // When there are dirty untitled items, prompt to save each one. If the user
10196 // cancels any prompt, then abort.
10197 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10198 let item3 = cx.new(|cx| {
10199 TestItem::new(cx)
10200 .with_dirty(true)
10201 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10202 });
10203 workspace.update_in(cx, |w, window, cx| {
10204 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10205 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10206 });
10207 let task = workspace.update_in(cx, |w, window, cx| {
10208 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10209 });
10210 cx.executor().run_until_parked();
10211 cx.simulate_prompt_answer("Cancel"); // cancel save all
10212 cx.executor().run_until_parked();
10213 assert!(!cx.has_pending_prompt());
10214 assert!(!task.await.unwrap());
10215 }
10216
10217 #[gpui::test]
10218 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10219 init_test(cx);
10220
10221 let fs = FakeFs::new(cx.executor());
10222 fs.insert_tree("/root", json!({ "one": "" })).await;
10223
10224 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10225 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10226 let multi_workspace_handle =
10227 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10228 cx.run_until_parked();
10229
10230 let workspace_a = multi_workspace_handle
10231 .read_with(cx, |mw, _| mw.workspace().clone())
10232 .unwrap();
10233
10234 let workspace_b = multi_workspace_handle
10235 .update(cx, |mw, window, cx| {
10236 mw.test_add_workspace(project_b, window, cx)
10237 })
10238 .unwrap();
10239
10240 // Activate workspace A
10241 multi_workspace_handle
10242 .update(cx, |mw, window, cx| {
10243 mw.activate_index(0, window, cx);
10244 })
10245 .unwrap();
10246
10247 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10248
10249 // Workspace A has a clean item
10250 let item_a = cx.new(TestItem::new);
10251 workspace_a.update_in(cx, |w, window, cx| {
10252 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10253 });
10254
10255 // Workspace B has a dirty item
10256 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10257 workspace_b.update_in(cx, |w, window, cx| {
10258 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10259 });
10260
10261 // Verify workspace A is active
10262 multi_workspace_handle
10263 .read_with(cx, |mw, _| {
10264 assert_eq!(mw.active_workspace_index(), 0);
10265 })
10266 .unwrap();
10267
10268 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10269 multi_workspace_handle
10270 .update(cx, |mw, window, cx| {
10271 mw.close_window(&CloseWindow, window, cx);
10272 })
10273 .unwrap();
10274 cx.run_until_parked();
10275
10276 // Workspace B should now be active since it has dirty items that need attention
10277 multi_workspace_handle
10278 .read_with(cx, |mw, _| {
10279 assert_eq!(
10280 mw.active_workspace_index(),
10281 1,
10282 "workspace B should be activated when it prompts"
10283 );
10284 })
10285 .unwrap();
10286
10287 // User cancels the save prompt from workspace B
10288 cx.simulate_prompt_answer("Cancel");
10289 cx.run_until_parked();
10290
10291 // Window should still exist because workspace B's close was cancelled
10292 assert!(
10293 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10294 "window should still exist after cancelling one workspace's close"
10295 );
10296 }
10297
10298 #[gpui::test]
10299 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10300 init_test(cx);
10301
10302 // Register TestItem as a serializable item
10303 cx.update(|cx| {
10304 register_serializable_item::<TestItem>(cx);
10305 });
10306
10307 let fs = FakeFs::new(cx.executor());
10308 fs.insert_tree("/root", json!({ "one": "" })).await;
10309
10310 let project = Project::test(fs, ["root".as_ref()], cx).await;
10311 let (workspace, cx) =
10312 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10313
10314 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10315 let item1 = cx.new(|cx| {
10316 TestItem::new(cx)
10317 .with_dirty(true)
10318 .with_serialize(|| Some(Task::ready(Ok(()))))
10319 });
10320 let item2 = cx.new(|cx| {
10321 TestItem::new(cx)
10322 .with_dirty(true)
10323 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10324 .with_serialize(|| Some(Task::ready(Ok(()))))
10325 });
10326 workspace.update_in(cx, |w, window, cx| {
10327 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10328 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10329 });
10330 let task = workspace.update_in(cx, |w, window, cx| {
10331 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10332 });
10333 assert!(task.await.unwrap());
10334 }
10335
10336 #[gpui::test]
10337 async fn test_close_pane_items(cx: &mut TestAppContext) {
10338 init_test(cx);
10339
10340 let fs = FakeFs::new(cx.executor());
10341
10342 let project = Project::test(fs, None, cx).await;
10343 let (workspace, cx) =
10344 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10345
10346 let item1 = cx.new(|cx| {
10347 TestItem::new(cx)
10348 .with_dirty(true)
10349 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10350 });
10351 let item2 = cx.new(|cx| {
10352 TestItem::new(cx)
10353 .with_dirty(true)
10354 .with_conflict(true)
10355 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10356 });
10357 let item3 = cx.new(|cx| {
10358 TestItem::new(cx)
10359 .with_dirty(true)
10360 .with_conflict(true)
10361 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10362 });
10363 let item4 = cx.new(|cx| {
10364 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10365 let project_item = TestProjectItem::new_untitled(cx);
10366 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10367 project_item
10368 }])
10369 });
10370 let pane = workspace.update_in(cx, |workspace, window, cx| {
10371 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10372 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10373 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10374 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10375 workspace.active_pane().clone()
10376 });
10377
10378 let close_items = pane.update_in(cx, |pane, window, cx| {
10379 pane.activate_item(1, true, true, window, cx);
10380 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10381 let item1_id = item1.item_id();
10382 let item3_id = item3.item_id();
10383 let item4_id = item4.item_id();
10384 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10385 [item1_id, item3_id, item4_id].contains(&id)
10386 })
10387 });
10388 cx.executor().run_until_parked();
10389
10390 assert!(cx.has_pending_prompt());
10391 cx.simulate_prompt_answer("Save all");
10392
10393 cx.executor().run_until_parked();
10394
10395 // Item 1 is saved. There's a prompt to save item 3.
10396 pane.update(cx, |pane, cx| {
10397 assert_eq!(item1.read(cx).save_count, 1);
10398 assert_eq!(item1.read(cx).save_as_count, 0);
10399 assert_eq!(item1.read(cx).reload_count, 0);
10400 assert_eq!(pane.items_len(), 3);
10401 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10402 });
10403 assert!(cx.has_pending_prompt());
10404
10405 // Cancel saving item 3.
10406 cx.simulate_prompt_answer("Discard");
10407 cx.executor().run_until_parked();
10408
10409 // Item 3 is reloaded. There's a prompt to save item 4.
10410 pane.update(cx, |pane, cx| {
10411 assert_eq!(item3.read(cx).save_count, 0);
10412 assert_eq!(item3.read(cx).save_as_count, 0);
10413 assert_eq!(item3.read(cx).reload_count, 1);
10414 assert_eq!(pane.items_len(), 2);
10415 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10416 });
10417
10418 // There's a prompt for a path for item 4.
10419 cx.simulate_new_path_selection(|_| Some(Default::default()));
10420 close_items.await.unwrap();
10421
10422 // The requested items are closed.
10423 pane.update(cx, |pane, cx| {
10424 assert_eq!(item4.read(cx).save_count, 0);
10425 assert_eq!(item4.read(cx).save_as_count, 1);
10426 assert_eq!(item4.read(cx).reload_count, 0);
10427 assert_eq!(pane.items_len(), 1);
10428 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10429 });
10430 }
10431
10432 #[gpui::test]
10433 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10434 init_test(cx);
10435
10436 let fs = FakeFs::new(cx.executor());
10437 let project = Project::test(fs, [], cx).await;
10438 let (workspace, cx) =
10439 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10440
10441 // Create several workspace items with single project entries, and two
10442 // workspace items with multiple project entries.
10443 let single_entry_items = (0..=4)
10444 .map(|project_entry_id| {
10445 cx.new(|cx| {
10446 TestItem::new(cx)
10447 .with_dirty(true)
10448 .with_project_items(&[dirty_project_item(
10449 project_entry_id,
10450 &format!("{project_entry_id}.txt"),
10451 cx,
10452 )])
10453 })
10454 })
10455 .collect::<Vec<_>>();
10456 let item_2_3 = cx.new(|cx| {
10457 TestItem::new(cx)
10458 .with_dirty(true)
10459 .with_buffer_kind(ItemBufferKind::Multibuffer)
10460 .with_project_items(&[
10461 single_entry_items[2].read(cx).project_items[0].clone(),
10462 single_entry_items[3].read(cx).project_items[0].clone(),
10463 ])
10464 });
10465 let item_3_4 = cx.new(|cx| {
10466 TestItem::new(cx)
10467 .with_dirty(true)
10468 .with_buffer_kind(ItemBufferKind::Multibuffer)
10469 .with_project_items(&[
10470 single_entry_items[3].read(cx).project_items[0].clone(),
10471 single_entry_items[4].read(cx).project_items[0].clone(),
10472 ])
10473 });
10474
10475 // Create two panes that contain the following project entries:
10476 // left pane:
10477 // multi-entry items: (2, 3)
10478 // single-entry items: 0, 2, 3, 4
10479 // right pane:
10480 // single-entry items: 4, 1
10481 // multi-entry items: (3, 4)
10482 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10483 let left_pane = workspace.active_pane().clone();
10484 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10485 workspace.add_item_to_active_pane(
10486 single_entry_items[0].boxed_clone(),
10487 None,
10488 true,
10489 window,
10490 cx,
10491 );
10492 workspace.add_item_to_active_pane(
10493 single_entry_items[2].boxed_clone(),
10494 None,
10495 true,
10496 window,
10497 cx,
10498 );
10499 workspace.add_item_to_active_pane(
10500 single_entry_items[3].boxed_clone(),
10501 None,
10502 true,
10503 window,
10504 cx,
10505 );
10506 workspace.add_item_to_active_pane(
10507 single_entry_items[4].boxed_clone(),
10508 None,
10509 true,
10510 window,
10511 cx,
10512 );
10513
10514 let right_pane =
10515 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10516
10517 let boxed_clone = single_entry_items[1].boxed_clone();
10518 let right_pane = window.spawn(cx, async move |cx| {
10519 right_pane.await.inspect(|right_pane| {
10520 right_pane
10521 .update_in(cx, |pane, window, cx| {
10522 pane.add_item(boxed_clone, true, true, None, window, cx);
10523 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10524 })
10525 .unwrap();
10526 })
10527 });
10528
10529 (left_pane, right_pane)
10530 });
10531 let right_pane = right_pane.await.unwrap();
10532 cx.focus(&right_pane);
10533
10534 let close = right_pane.update_in(cx, |pane, window, cx| {
10535 pane.close_all_items(&CloseAllItems::default(), window, cx)
10536 .unwrap()
10537 });
10538 cx.executor().run_until_parked();
10539
10540 let msg = cx.pending_prompt().unwrap().0;
10541 assert!(msg.contains("1.txt"));
10542 assert!(!msg.contains("2.txt"));
10543 assert!(!msg.contains("3.txt"));
10544 assert!(!msg.contains("4.txt"));
10545
10546 // With best-effort close, cancelling item 1 keeps it open but items 4
10547 // and (3,4) still close since their entries exist in left pane.
10548 cx.simulate_prompt_answer("Cancel");
10549 close.await;
10550
10551 right_pane.read_with(cx, |pane, _| {
10552 assert_eq!(pane.items_len(), 1);
10553 });
10554
10555 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10556 left_pane
10557 .update_in(cx, |left_pane, window, cx| {
10558 left_pane.close_item_by_id(
10559 single_entry_items[3].entity_id(),
10560 SaveIntent::Skip,
10561 window,
10562 cx,
10563 )
10564 })
10565 .await
10566 .unwrap();
10567
10568 let close = left_pane.update_in(cx, |pane, window, cx| {
10569 pane.close_all_items(&CloseAllItems::default(), window, cx)
10570 .unwrap()
10571 });
10572 cx.executor().run_until_parked();
10573
10574 let details = cx.pending_prompt().unwrap().1;
10575 assert!(details.contains("0.txt"));
10576 assert!(details.contains("3.txt"));
10577 assert!(details.contains("4.txt"));
10578 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10579 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10580 // assert!(!details.contains("2.txt"));
10581
10582 cx.simulate_prompt_answer("Save all");
10583 cx.executor().run_until_parked();
10584 close.await;
10585
10586 left_pane.read_with(cx, |pane, _| {
10587 assert_eq!(pane.items_len(), 0);
10588 });
10589 }
10590
10591 #[gpui::test]
10592 async fn test_autosave(cx: &mut gpui::TestAppContext) {
10593 init_test(cx);
10594
10595 let fs = FakeFs::new(cx.executor());
10596 let project = Project::test(fs, [], cx).await;
10597 let (workspace, cx) =
10598 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10599 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10600
10601 let item = cx.new(|cx| {
10602 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10603 });
10604 let item_id = item.entity_id();
10605 workspace.update_in(cx, |workspace, window, cx| {
10606 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10607 });
10608
10609 // Autosave on window change.
10610 item.update(cx, |item, cx| {
10611 SettingsStore::update_global(cx, |settings, cx| {
10612 settings.update_user_settings(cx, |settings| {
10613 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10614 })
10615 });
10616 item.is_dirty = true;
10617 });
10618
10619 // Deactivating the window saves the file.
10620 cx.deactivate_window();
10621 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10622
10623 // Re-activating the window doesn't save the file.
10624 cx.update(|window, _| window.activate_window());
10625 cx.executor().run_until_parked();
10626 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10627
10628 // Autosave on focus change.
10629 item.update_in(cx, |item, window, cx| {
10630 cx.focus_self(window);
10631 SettingsStore::update_global(cx, |settings, cx| {
10632 settings.update_user_settings(cx, |settings| {
10633 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10634 })
10635 });
10636 item.is_dirty = true;
10637 });
10638 // Blurring the item saves the file.
10639 item.update_in(cx, |_, window, _| window.blur());
10640 cx.executor().run_until_parked();
10641 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10642
10643 // Deactivating the window still saves the file.
10644 item.update_in(cx, |item, window, cx| {
10645 cx.focus_self(window);
10646 item.is_dirty = true;
10647 });
10648 cx.deactivate_window();
10649 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10650
10651 // Autosave after delay.
10652 item.update(cx, |item, cx| {
10653 SettingsStore::update_global(cx, |settings, cx| {
10654 settings.update_user_settings(cx, |settings| {
10655 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10656 milliseconds: 500.into(),
10657 });
10658 })
10659 });
10660 item.is_dirty = true;
10661 cx.emit(ItemEvent::Edit);
10662 });
10663
10664 // Delay hasn't fully expired, so the file is still dirty and unsaved.
10665 cx.executor().advance_clock(Duration::from_millis(250));
10666 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10667
10668 // After delay expires, the file is saved.
10669 cx.executor().advance_clock(Duration::from_millis(250));
10670 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10671
10672 // Autosave after delay, should save earlier than delay if tab is closed
10673 item.update(cx, |item, cx| {
10674 item.is_dirty = true;
10675 cx.emit(ItemEvent::Edit);
10676 });
10677 cx.executor().advance_clock(Duration::from_millis(250));
10678 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10679
10680 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10681 pane.update_in(cx, |pane, window, cx| {
10682 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10683 })
10684 .await
10685 .unwrap();
10686 assert!(!cx.has_pending_prompt());
10687 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10688
10689 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10690 workspace.update_in(cx, |workspace, window, cx| {
10691 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10692 });
10693 item.update_in(cx, |item, _window, cx| {
10694 item.is_dirty = true;
10695 for project_item in &mut item.project_items {
10696 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10697 }
10698 });
10699 cx.run_until_parked();
10700 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10701
10702 // Autosave on focus change, ensuring closing the tab counts as such.
10703 item.update(cx, |item, cx| {
10704 SettingsStore::update_global(cx, |settings, cx| {
10705 settings.update_user_settings(cx, |settings| {
10706 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10707 })
10708 });
10709 item.is_dirty = true;
10710 for project_item in &mut item.project_items {
10711 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10712 }
10713 });
10714
10715 pane.update_in(cx, |pane, window, cx| {
10716 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10717 })
10718 .await
10719 .unwrap();
10720 assert!(!cx.has_pending_prompt());
10721 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10722
10723 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10724 workspace.update_in(cx, |workspace, window, cx| {
10725 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10726 });
10727 item.update_in(cx, |item, window, cx| {
10728 item.project_items[0].update(cx, |item, _| {
10729 item.entry_id = None;
10730 });
10731 item.is_dirty = true;
10732 window.blur();
10733 });
10734 cx.run_until_parked();
10735 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10736
10737 // Ensure autosave is prevented for deleted files also when closing the buffer.
10738 let _close_items = pane.update_in(cx, |pane, window, cx| {
10739 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10740 });
10741 cx.run_until_parked();
10742 assert!(cx.has_pending_prompt());
10743 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10744 }
10745
10746 #[gpui::test]
10747 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
10748 init_test(cx);
10749
10750 let fs = FakeFs::new(cx.executor());
10751 let project = Project::test(fs, [], cx).await;
10752 let (workspace, cx) =
10753 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10754
10755 // Create a multibuffer-like item with two child focus handles,
10756 // simulating individual buffer editors within a multibuffer.
10757 let item = cx.new(|cx| {
10758 TestItem::new(cx)
10759 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10760 .with_child_focus_handles(2, cx)
10761 });
10762 workspace.update_in(cx, |workspace, window, cx| {
10763 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10764 });
10765
10766 // Set autosave to OnFocusChange and focus the first child handle,
10767 // simulating the user's cursor being inside one of the multibuffer's excerpts.
10768 item.update_in(cx, |item, window, cx| {
10769 SettingsStore::update_global(cx, |settings, cx| {
10770 settings.update_user_settings(cx, |settings| {
10771 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10772 })
10773 });
10774 item.is_dirty = true;
10775 window.focus(&item.child_focus_handles[0], cx);
10776 });
10777 cx.executor().run_until_parked();
10778 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
10779
10780 // Moving focus from one child to another within the same item should
10781 // NOT trigger autosave — focus is still within the item's focus hierarchy.
10782 item.update_in(cx, |item, window, cx| {
10783 window.focus(&item.child_focus_handles[1], cx);
10784 });
10785 cx.executor().run_until_parked();
10786 item.read_with(cx, |item, _| {
10787 assert_eq!(
10788 item.save_count, 0,
10789 "Switching focus between children within the same item should not autosave"
10790 );
10791 });
10792
10793 // Blurring the item saves the file. This is the core regression scenario:
10794 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
10795 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
10796 // the leaf is always a child focus handle, so `on_blur` never detected
10797 // focus leaving the item.
10798 item.update_in(cx, |_, window, _| window.blur());
10799 cx.executor().run_until_parked();
10800 item.read_with(cx, |item, _| {
10801 assert_eq!(
10802 item.save_count, 1,
10803 "Blurring should trigger autosave when focus was on a child of the item"
10804 );
10805 });
10806
10807 // Deactivating the window should also trigger autosave when a child of
10808 // the multibuffer item currently owns focus.
10809 item.update_in(cx, |item, window, cx| {
10810 item.is_dirty = true;
10811 window.focus(&item.child_focus_handles[0], cx);
10812 });
10813 cx.executor().run_until_parked();
10814 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10815
10816 cx.deactivate_window();
10817 item.read_with(cx, |item, _| {
10818 assert_eq!(
10819 item.save_count, 2,
10820 "Deactivating window should trigger autosave when focus was on a child"
10821 );
10822 });
10823 }
10824
10825 #[gpui::test]
10826 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10827 init_test(cx);
10828
10829 let fs = FakeFs::new(cx.executor());
10830
10831 let project = Project::test(fs, [], cx).await;
10832 let (workspace, cx) =
10833 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10834
10835 let item = cx.new(|cx| {
10836 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10837 });
10838 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10839 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10840 let toolbar_notify_count = Rc::new(RefCell::new(0));
10841
10842 workspace.update_in(cx, |workspace, window, cx| {
10843 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10844 let toolbar_notification_count = toolbar_notify_count.clone();
10845 cx.observe_in(&toolbar, window, move |_, _, _, _| {
10846 *toolbar_notification_count.borrow_mut() += 1
10847 })
10848 .detach();
10849 });
10850
10851 pane.read_with(cx, |pane, _| {
10852 assert!(!pane.can_navigate_backward());
10853 assert!(!pane.can_navigate_forward());
10854 });
10855
10856 item.update_in(cx, |item, _, cx| {
10857 item.set_state("one".to_string(), cx);
10858 });
10859
10860 // Toolbar must be notified to re-render the navigation buttons
10861 assert_eq!(*toolbar_notify_count.borrow(), 1);
10862
10863 pane.read_with(cx, |pane, _| {
10864 assert!(pane.can_navigate_backward());
10865 assert!(!pane.can_navigate_forward());
10866 });
10867
10868 workspace
10869 .update_in(cx, |workspace, window, cx| {
10870 workspace.go_back(pane.downgrade(), window, cx)
10871 })
10872 .await
10873 .unwrap();
10874
10875 assert_eq!(*toolbar_notify_count.borrow(), 2);
10876 pane.read_with(cx, |pane, _| {
10877 assert!(!pane.can_navigate_backward());
10878 assert!(pane.can_navigate_forward());
10879 });
10880 }
10881
10882 #[gpui::test]
10883 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
10884 init_test(cx);
10885 let fs = FakeFs::new(cx.executor());
10886 let project = Project::test(fs, [], cx).await;
10887 let (multi_workspace, cx) =
10888 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
10889 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
10890
10891 workspace.update_in(cx, |workspace, window, cx| {
10892 let first_item = cx.new(|cx| {
10893 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10894 });
10895 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
10896 workspace.split_pane(
10897 workspace.active_pane().clone(),
10898 SplitDirection::Right,
10899 window,
10900 cx,
10901 );
10902 workspace.split_pane(
10903 workspace.active_pane().clone(),
10904 SplitDirection::Right,
10905 window,
10906 cx,
10907 );
10908 });
10909
10910 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
10911 let panes = workspace.center.panes();
10912 assert!(panes.len() >= 2);
10913 (
10914 panes.first().expect("at least one pane").entity_id(),
10915 panes.last().expect("at least one pane").entity_id(),
10916 )
10917 });
10918
10919 workspace.update_in(cx, |workspace, window, cx| {
10920 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
10921 });
10922 workspace.update(cx, |workspace, _| {
10923 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
10924 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
10925 });
10926
10927 cx.dispatch_action(ActivateLastPane);
10928
10929 workspace.update(cx, |workspace, _| {
10930 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
10931 });
10932 }
10933
10934 #[gpui::test]
10935 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
10936 init_test(cx);
10937 let fs = FakeFs::new(cx.executor());
10938
10939 let project = Project::test(fs, [], cx).await;
10940 let (workspace, cx) =
10941 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10942
10943 let panel = workspace.update_in(cx, |workspace, window, cx| {
10944 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10945 workspace.add_panel(panel.clone(), window, cx);
10946
10947 workspace
10948 .right_dock()
10949 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10950
10951 panel
10952 });
10953
10954 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10955 pane.update_in(cx, |pane, window, cx| {
10956 let item = cx.new(TestItem::new);
10957 pane.add_item(Box::new(item), true, true, None, window, cx);
10958 });
10959
10960 // Transfer focus from center to panel
10961 workspace.update_in(cx, |workspace, window, cx| {
10962 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10963 });
10964
10965 workspace.update_in(cx, |workspace, window, cx| {
10966 assert!(workspace.right_dock().read(cx).is_open());
10967 assert!(!panel.is_zoomed(window, cx));
10968 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10969 });
10970
10971 // Transfer focus from panel to center
10972 workspace.update_in(cx, |workspace, window, cx| {
10973 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10974 });
10975
10976 workspace.update_in(cx, |workspace, window, cx| {
10977 assert!(workspace.right_dock().read(cx).is_open());
10978 assert!(!panel.is_zoomed(window, cx));
10979 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10980 });
10981
10982 // Close the dock
10983 workspace.update_in(cx, |workspace, window, cx| {
10984 workspace.toggle_dock(DockPosition::Right, window, cx);
10985 });
10986
10987 workspace.update_in(cx, |workspace, window, cx| {
10988 assert!(!workspace.right_dock().read(cx).is_open());
10989 assert!(!panel.is_zoomed(window, cx));
10990 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10991 });
10992
10993 // Open the dock
10994 workspace.update_in(cx, |workspace, window, cx| {
10995 workspace.toggle_dock(DockPosition::Right, window, cx);
10996 });
10997
10998 workspace.update_in(cx, |workspace, window, cx| {
10999 assert!(workspace.right_dock().read(cx).is_open());
11000 assert!(!panel.is_zoomed(window, cx));
11001 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11002 });
11003
11004 // Focus and zoom panel
11005 panel.update_in(cx, |panel, window, cx| {
11006 cx.focus_self(window);
11007 panel.set_zoomed(true, window, cx)
11008 });
11009
11010 workspace.update_in(cx, |workspace, window, cx| {
11011 assert!(workspace.right_dock().read(cx).is_open());
11012 assert!(panel.is_zoomed(window, cx));
11013 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11014 });
11015
11016 // Transfer focus to the center closes the dock
11017 workspace.update_in(cx, |workspace, window, cx| {
11018 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11019 });
11020
11021 workspace.update_in(cx, |workspace, window, cx| {
11022 assert!(!workspace.right_dock().read(cx).is_open());
11023 assert!(panel.is_zoomed(window, cx));
11024 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11025 });
11026
11027 // Transferring focus back to the panel keeps it zoomed
11028 workspace.update_in(cx, |workspace, window, cx| {
11029 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11030 });
11031
11032 workspace.update_in(cx, |workspace, window, cx| {
11033 assert!(workspace.right_dock().read(cx).is_open());
11034 assert!(panel.is_zoomed(window, cx));
11035 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11036 });
11037
11038 // Close the dock while it is zoomed
11039 workspace.update_in(cx, |workspace, window, cx| {
11040 workspace.toggle_dock(DockPosition::Right, window, cx)
11041 });
11042
11043 workspace.update_in(cx, |workspace, window, cx| {
11044 assert!(!workspace.right_dock().read(cx).is_open());
11045 assert!(panel.is_zoomed(window, cx));
11046 assert!(workspace.zoomed.is_none());
11047 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11048 });
11049
11050 // Opening the dock, when it's zoomed, retains focus
11051 workspace.update_in(cx, |workspace, window, cx| {
11052 workspace.toggle_dock(DockPosition::Right, window, cx)
11053 });
11054
11055 workspace.update_in(cx, |workspace, window, cx| {
11056 assert!(workspace.right_dock().read(cx).is_open());
11057 assert!(panel.is_zoomed(window, cx));
11058 assert!(workspace.zoomed.is_some());
11059 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11060 });
11061
11062 // Unzoom and close the panel, zoom the active pane.
11063 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11064 workspace.update_in(cx, |workspace, window, cx| {
11065 workspace.toggle_dock(DockPosition::Right, window, cx)
11066 });
11067 pane.update_in(cx, |pane, window, cx| {
11068 pane.toggle_zoom(&Default::default(), window, cx)
11069 });
11070
11071 // Opening a dock unzooms the pane.
11072 workspace.update_in(cx, |workspace, window, cx| {
11073 workspace.toggle_dock(DockPosition::Right, window, cx)
11074 });
11075 workspace.update_in(cx, |workspace, window, cx| {
11076 let pane = pane.read(cx);
11077 assert!(!pane.is_zoomed());
11078 assert!(!pane.focus_handle(cx).is_focused(window));
11079 assert!(workspace.right_dock().read(cx).is_open());
11080 assert!(workspace.zoomed.is_none());
11081 });
11082 }
11083
11084 #[gpui::test]
11085 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11086 init_test(cx);
11087 let fs = FakeFs::new(cx.executor());
11088
11089 let project = Project::test(fs, [], cx).await;
11090 let (workspace, cx) =
11091 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11092
11093 let panel = workspace.update_in(cx, |workspace, window, cx| {
11094 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11095 workspace.add_panel(panel.clone(), window, cx);
11096 panel
11097 });
11098
11099 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11100 pane.update_in(cx, |pane, window, cx| {
11101 let item = cx.new(TestItem::new);
11102 pane.add_item(Box::new(item), true, true, None, window, cx);
11103 });
11104
11105 // Enable close_panel_on_toggle
11106 cx.update_global(|store: &mut SettingsStore, cx| {
11107 store.update_user_settings(cx, |settings| {
11108 settings.workspace.close_panel_on_toggle = Some(true);
11109 });
11110 });
11111
11112 // Panel starts closed. Toggling should open and focus it.
11113 workspace.update_in(cx, |workspace, window, cx| {
11114 assert!(!workspace.right_dock().read(cx).is_open());
11115 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11116 });
11117
11118 workspace.update_in(cx, |workspace, window, cx| {
11119 assert!(
11120 workspace.right_dock().read(cx).is_open(),
11121 "Dock should be open after toggling from center"
11122 );
11123 assert!(
11124 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11125 "Panel should be focused after toggling from center"
11126 );
11127 });
11128
11129 // Panel is open and focused. Toggling should close the panel and
11130 // return focus to the center.
11131 workspace.update_in(cx, |workspace, window, cx| {
11132 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11133 });
11134
11135 workspace.update_in(cx, |workspace, window, cx| {
11136 assert!(
11137 !workspace.right_dock().read(cx).is_open(),
11138 "Dock should be closed after toggling from focused panel"
11139 );
11140 assert!(
11141 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11142 "Panel should not be focused after toggling from focused panel"
11143 );
11144 });
11145
11146 // Open the dock and focus something else so the panel is open but not
11147 // focused. Toggling should focus the panel (not close it).
11148 workspace.update_in(cx, |workspace, window, cx| {
11149 workspace
11150 .right_dock()
11151 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11152 window.focus(&pane.read(cx).focus_handle(cx), cx);
11153 });
11154
11155 workspace.update_in(cx, |workspace, window, cx| {
11156 assert!(workspace.right_dock().read(cx).is_open());
11157 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11158 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11159 });
11160
11161 workspace.update_in(cx, |workspace, window, cx| {
11162 assert!(
11163 workspace.right_dock().read(cx).is_open(),
11164 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11165 );
11166 assert!(
11167 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11168 "Panel should be focused after toggling an open-but-unfocused panel"
11169 );
11170 });
11171
11172 // Now disable the setting and verify the original behavior: toggling
11173 // from a focused panel moves focus to center but leaves the dock open.
11174 cx.update_global(|store: &mut SettingsStore, cx| {
11175 store.update_user_settings(cx, |settings| {
11176 settings.workspace.close_panel_on_toggle = Some(false);
11177 });
11178 });
11179
11180 workspace.update_in(cx, |workspace, window, cx| {
11181 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11182 });
11183
11184 workspace.update_in(cx, |workspace, window, cx| {
11185 assert!(
11186 workspace.right_dock().read(cx).is_open(),
11187 "Dock should remain open when setting is disabled"
11188 );
11189 assert!(
11190 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11191 "Panel should not be focused after toggling with setting disabled"
11192 );
11193 });
11194 }
11195
11196 #[gpui::test]
11197 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11198 init_test(cx);
11199 let fs = FakeFs::new(cx.executor());
11200
11201 let project = Project::test(fs, [], cx).await;
11202 let (workspace, cx) =
11203 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11204
11205 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11206 workspace.active_pane().clone()
11207 });
11208
11209 // Add an item to the pane so it can be zoomed
11210 workspace.update_in(cx, |workspace, window, cx| {
11211 let item = cx.new(TestItem::new);
11212 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11213 });
11214
11215 // Initially not zoomed
11216 workspace.update_in(cx, |workspace, _window, cx| {
11217 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11218 assert!(
11219 workspace.zoomed.is_none(),
11220 "Workspace should track no zoomed pane"
11221 );
11222 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11223 });
11224
11225 // Zoom In
11226 pane.update_in(cx, |pane, window, cx| {
11227 pane.zoom_in(&crate::ZoomIn, window, cx);
11228 });
11229
11230 workspace.update_in(cx, |workspace, window, cx| {
11231 assert!(
11232 pane.read(cx).is_zoomed(),
11233 "Pane should be zoomed after ZoomIn"
11234 );
11235 assert!(
11236 workspace.zoomed.is_some(),
11237 "Workspace should track the zoomed pane"
11238 );
11239 assert!(
11240 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11241 "ZoomIn should focus the pane"
11242 );
11243 });
11244
11245 // Zoom In again is a no-op
11246 pane.update_in(cx, |pane, window, cx| {
11247 pane.zoom_in(&crate::ZoomIn, window, cx);
11248 });
11249
11250 workspace.update_in(cx, |workspace, window, cx| {
11251 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11252 assert!(
11253 workspace.zoomed.is_some(),
11254 "Workspace still tracks zoomed pane"
11255 );
11256 assert!(
11257 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11258 "Pane remains focused after repeated ZoomIn"
11259 );
11260 });
11261
11262 // Zoom Out
11263 pane.update_in(cx, |pane, window, cx| {
11264 pane.zoom_out(&crate::ZoomOut, window, cx);
11265 });
11266
11267 workspace.update_in(cx, |workspace, _window, cx| {
11268 assert!(
11269 !pane.read(cx).is_zoomed(),
11270 "Pane should unzoom after ZoomOut"
11271 );
11272 assert!(
11273 workspace.zoomed.is_none(),
11274 "Workspace clears zoom tracking after ZoomOut"
11275 );
11276 });
11277
11278 // Zoom Out again is a no-op
11279 pane.update_in(cx, |pane, window, cx| {
11280 pane.zoom_out(&crate::ZoomOut, window, cx);
11281 });
11282
11283 workspace.update_in(cx, |workspace, _window, cx| {
11284 assert!(
11285 !pane.read(cx).is_zoomed(),
11286 "Second ZoomOut keeps pane unzoomed"
11287 );
11288 assert!(
11289 workspace.zoomed.is_none(),
11290 "Workspace remains without zoomed pane"
11291 );
11292 });
11293 }
11294
11295 #[gpui::test]
11296 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11297 init_test(cx);
11298 let fs = FakeFs::new(cx.executor());
11299
11300 let project = Project::test(fs, [], cx).await;
11301 let (workspace, cx) =
11302 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11303 workspace.update_in(cx, |workspace, window, cx| {
11304 // Open two docks
11305 let left_dock = workspace.dock_at_position(DockPosition::Left);
11306 let right_dock = workspace.dock_at_position(DockPosition::Right);
11307
11308 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11309 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11310
11311 assert!(left_dock.read(cx).is_open());
11312 assert!(right_dock.read(cx).is_open());
11313 });
11314
11315 workspace.update_in(cx, |workspace, window, cx| {
11316 // Toggle all docks - should close both
11317 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11318
11319 let left_dock = workspace.dock_at_position(DockPosition::Left);
11320 let right_dock = workspace.dock_at_position(DockPosition::Right);
11321 assert!(!left_dock.read(cx).is_open());
11322 assert!(!right_dock.read(cx).is_open());
11323 });
11324
11325 workspace.update_in(cx, |workspace, window, cx| {
11326 // Toggle again - should reopen both
11327 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11328
11329 let left_dock = workspace.dock_at_position(DockPosition::Left);
11330 let right_dock = workspace.dock_at_position(DockPosition::Right);
11331 assert!(left_dock.read(cx).is_open());
11332 assert!(right_dock.read(cx).is_open());
11333 });
11334 }
11335
11336 #[gpui::test]
11337 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11338 init_test(cx);
11339 let fs = FakeFs::new(cx.executor());
11340
11341 let project = Project::test(fs, [], cx).await;
11342 let (workspace, cx) =
11343 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11344 workspace.update_in(cx, |workspace, window, cx| {
11345 // Open two docks
11346 let left_dock = workspace.dock_at_position(DockPosition::Left);
11347 let right_dock = workspace.dock_at_position(DockPosition::Right);
11348
11349 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11350 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11351
11352 assert!(left_dock.read(cx).is_open());
11353 assert!(right_dock.read(cx).is_open());
11354 });
11355
11356 workspace.update_in(cx, |workspace, window, cx| {
11357 // Close them manually
11358 workspace.toggle_dock(DockPosition::Left, window, cx);
11359 workspace.toggle_dock(DockPosition::Right, window, cx);
11360
11361 let left_dock = workspace.dock_at_position(DockPosition::Left);
11362 let right_dock = workspace.dock_at_position(DockPosition::Right);
11363 assert!(!left_dock.read(cx).is_open());
11364 assert!(!right_dock.read(cx).is_open());
11365 });
11366
11367 workspace.update_in(cx, |workspace, window, cx| {
11368 // Toggle all docks - only last closed (right dock) should reopen
11369 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11370
11371 let left_dock = workspace.dock_at_position(DockPosition::Left);
11372 let right_dock = workspace.dock_at_position(DockPosition::Right);
11373 assert!(!left_dock.read(cx).is_open());
11374 assert!(right_dock.read(cx).is_open());
11375 });
11376 }
11377
11378 #[gpui::test]
11379 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11380 init_test(cx);
11381 let fs = FakeFs::new(cx.executor());
11382 let project = Project::test(fs, [], cx).await;
11383 let (multi_workspace, cx) =
11384 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11385 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11386
11387 // Open two docks (left and right) with one panel each
11388 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11389 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11390 workspace.add_panel(left_panel.clone(), window, cx);
11391
11392 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11393 workspace.add_panel(right_panel.clone(), window, cx);
11394
11395 workspace.toggle_dock(DockPosition::Left, window, cx);
11396 workspace.toggle_dock(DockPosition::Right, window, cx);
11397
11398 // Verify initial state
11399 assert!(
11400 workspace.left_dock().read(cx).is_open(),
11401 "Left dock should be open"
11402 );
11403 assert_eq!(
11404 workspace
11405 .left_dock()
11406 .read(cx)
11407 .visible_panel()
11408 .unwrap()
11409 .panel_id(),
11410 left_panel.panel_id(),
11411 "Left panel should be visible in left dock"
11412 );
11413 assert!(
11414 workspace.right_dock().read(cx).is_open(),
11415 "Right dock should be open"
11416 );
11417 assert_eq!(
11418 workspace
11419 .right_dock()
11420 .read(cx)
11421 .visible_panel()
11422 .unwrap()
11423 .panel_id(),
11424 right_panel.panel_id(),
11425 "Right panel should be visible in right dock"
11426 );
11427 assert!(
11428 !workspace.bottom_dock().read(cx).is_open(),
11429 "Bottom dock should be closed"
11430 );
11431
11432 (left_panel, right_panel)
11433 });
11434
11435 // Focus the left panel and move it to the next position (bottom dock)
11436 workspace.update_in(cx, |workspace, window, cx| {
11437 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11438 assert!(
11439 left_panel.read(cx).focus_handle(cx).is_focused(window),
11440 "Left panel should be focused"
11441 );
11442 });
11443
11444 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11445
11446 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11447 workspace.update(cx, |workspace, cx| {
11448 assert!(
11449 !workspace.left_dock().read(cx).is_open(),
11450 "Left dock should be closed"
11451 );
11452 assert!(
11453 workspace.bottom_dock().read(cx).is_open(),
11454 "Bottom dock should now be open"
11455 );
11456 assert_eq!(
11457 left_panel.read(cx).position,
11458 DockPosition::Bottom,
11459 "Left panel should now be in the bottom dock"
11460 );
11461 assert_eq!(
11462 workspace
11463 .bottom_dock()
11464 .read(cx)
11465 .visible_panel()
11466 .unwrap()
11467 .panel_id(),
11468 left_panel.panel_id(),
11469 "Left panel should be the visible panel in the bottom dock"
11470 );
11471 });
11472
11473 // Toggle all docks off
11474 workspace.update_in(cx, |workspace, window, cx| {
11475 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11476 assert!(
11477 !workspace.left_dock().read(cx).is_open(),
11478 "Left dock should be closed"
11479 );
11480 assert!(
11481 !workspace.right_dock().read(cx).is_open(),
11482 "Right dock should be closed"
11483 );
11484 assert!(
11485 !workspace.bottom_dock().read(cx).is_open(),
11486 "Bottom dock should be closed"
11487 );
11488 });
11489
11490 // Toggle all docks back on and verify positions are restored
11491 workspace.update_in(cx, |workspace, window, cx| {
11492 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11493 assert!(
11494 !workspace.left_dock().read(cx).is_open(),
11495 "Left dock should remain closed"
11496 );
11497 assert!(
11498 workspace.right_dock().read(cx).is_open(),
11499 "Right dock should remain open"
11500 );
11501 assert!(
11502 workspace.bottom_dock().read(cx).is_open(),
11503 "Bottom dock should remain open"
11504 );
11505 assert_eq!(
11506 left_panel.read(cx).position,
11507 DockPosition::Bottom,
11508 "Left panel should remain in the bottom dock"
11509 );
11510 assert_eq!(
11511 right_panel.read(cx).position,
11512 DockPosition::Right,
11513 "Right panel should remain in the right dock"
11514 );
11515 assert_eq!(
11516 workspace
11517 .bottom_dock()
11518 .read(cx)
11519 .visible_panel()
11520 .unwrap()
11521 .panel_id(),
11522 left_panel.panel_id(),
11523 "Left panel should be the visible panel in the right dock"
11524 );
11525 });
11526 }
11527
11528 #[gpui::test]
11529 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11530 init_test(cx);
11531
11532 let fs = FakeFs::new(cx.executor());
11533
11534 let project = Project::test(fs, None, cx).await;
11535 let (workspace, cx) =
11536 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11537
11538 // Let's arrange the panes like this:
11539 //
11540 // +-----------------------+
11541 // | top |
11542 // +------+--------+-------+
11543 // | left | center | right |
11544 // +------+--------+-------+
11545 // | bottom |
11546 // +-----------------------+
11547
11548 let top_item = cx.new(|cx| {
11549 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11550 });
11551 let bottom_item = cx.new(|cx| {
11552 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11553 });
11554 let left_item = cx.new(|cx| {
11555 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11556 });
11557 let right_item = cx.new(|cx| {
11558 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11559 });
11560 let center_item = cx.new(|cx| {
11561 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11562 });
11563
11564 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11565 let top_pane_id = workspace.active_pane().entity_id();
11566 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11567 workspace.split_pane(
11568 workspace.active_pane().clone(),
11569 SplitDirection::Down,
11570 window,
11571 cx,
11572 );
11573 top_pane_id
11574 });
11575 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11576 let bottom_pane_id = workspace.active_pane().entity_id();
11577 workspace.add_item_to_active_pane(
11578 Box::new(bottom_item.clone()),
11579 None,
11580 false,
11581 window,
11582 cx,
11583 );
11584 workspace.split_pane(
11585 workspace.active_pane().clone(),
11586 SplitDirection::Up,
11587 window,
11588 cx,
11589 );
11590 bottom_pane_id
11591 });
11592 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11593 let left_pane_id = workspace.active_pane().entity_id();
11594 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11595 workspace.split_pane(
11596 workspace.active_pane().clone(),
11597 SplitDirection::Right,
11598 window,
11599 cx,
11600 );
11601 left_pane_id
11602 });
11603 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11604 let right_pane_id = workspace.active_pane().entity_id();
11605 workspace.add_item_to_active_pane(
11606 Box::new(right_item.clone()),
11607 None,
11608 false,
11609 window,
11610 cx,
11611 );
11612 workspace.split_pane(
11613 workspace.active_pane().clone(),
11614 SplitDirection::Left,
11615 window,
11616 cx,
11617 );
11618 right_pane_id
11619 });
11620 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11621 let center_pane_id = workspace.active_pane().entity_id();
11622 workspace.add_item_to_active_pane(
11623 Box::new(center_item.clone()),
11624 None,
11625 false,
11626 window,
11627 cx,
11628 );
11629 center_pane_id
11630 });
11631 cx.executor().run_until_parked();
11632
11633 workspace.update_in(cx, |workspace, window, cx| {
11634 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11635
11636 // Join into next from center pane into right
11637 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11638 });
11639
11640 workspace.update_in(cx, |workspace, window, cx| {
11641 let active_pane = workspace.active_pane();
11642 assert_eq!(right_pane_id, active_pane.entity_id());
11643 assert_eq!(2, active_pane.read(cx).items_len());
11644 let item_ids_in_pane =
11645 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11646 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11647 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11648
11649 // Join into next from right pane into bottom
11650 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11651 });
11652
11653 workspace.update_in(cx, |workspace, window, cx| {
11654 let active_pane = workspace.active_pane();
11655 assert_eq!(bottom_pane_id, active_pane.entity_id());
11656 assert_eq!(3, active_pane.read(cx).items_len());
11657 let item_ids_in_pane =
11658 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11659 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11660 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11661 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11662
11663 // Join into next from bottom pane into left
11664 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11665 });
11666
11667 workspace.update_in(cx, |workspace, window, cx| {
11668 let active_pane = workspace.active_pane();
11669 assert_eq!(left_pane_id, active_pane.entity_id());
11670 assert_eq!(4, active_pane.read(cx).items_len());
11671 let item_ids_in_pane =
11672 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11673 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11674 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11675 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11676 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11677
11678 // Join into next from left pane into top
11679 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11680 });
11681
11682 workspace.update_in(cx, |workspace, window, cx| {
11683 let active_pane = workspace.active_pane();
11684 assert_eq!(top_pane_id, active_pane.entity_id());
11685 assert_eq!(5, active_pane.read(cx).items_len());
11686 let item_ids_in_pane =
11687 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11688 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11689 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11690 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11691 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11692 assert!(item_ids_in_pane.contains(&top_item.item_id()));
11693
11694 // Single pane left: no-op
11695 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11696 });
11697
11698 workspace.update(cx, |workspace, _cx| {
11699 let active_pane = workspace.active_pane();
11700 assert_eq!(top_pane_id, active_pane.entity_id());
11701 });
11702 }
11703
11704 fn add_an_item_to_active_pane(
11705 cx: &mut VisualTestContext,
11706 workspace: &Entity<Workspace>,
11707 item_id: u64,
11708 ) -> Entity<TestItem> {
11709 let item = cx.new(|cx| {
11710 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11711 item_id,
11712 "item{item_id}.txt",
11713 cx,
11714 )])
11715 });
11716 workspace.update_in(cx, |workspace, window, cx| {
11717 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11718 });
11719 item
11720 }
11721
11722 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11723 workspace.update_in(cx, |workspace, window, cx| {
11724 workspace.split_pane(
11725 workspace.active_pane().clone(),
11726 SplitDirection::Right,
11727 window,
11728 cx,
11729 )
11730 })
11731 }
11732
11733 #[gpui::test]
11734 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11735 init_test(cx);
11736 let fs = FakeFs::new(cx.executor());
11737 let project = Project::test(fs, None, cx).await;
11738 let (workspace, cx) =
11739 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11740
11741 add_an_item_to_active_pane(cx, &workspace, 1);
11742 split_pane(cx, &workspace);
11743 add_an_item_to_active_pane(cx, &workspace, 2);
11744 split_pane(cx, &workspace); // empty pane
11745 split_pane(cx, &workspace);
11746 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11747
11748 cx.executor().run_until_parked();
11749
11750 workspace.update(cx, |workspace, cx| {
11751 let num_panes = workspace.panes().len();
11752 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11753 let active_item = workspace
11754 .active_pane()
11755 .read(cx)
11756 .active_item()
11757 .expect("item is in focus");
11758
11759 assert_eq!(num_panes, 4);
11760 assert_eq!(num_items_in_current_pane, 1);
11761 assert_eq!(active_item.item_id(), last_item.item_id());
11762 });
11763
11764 workspace.update_in(cx, |workspace, window, cx| {
11765 workspace.join_all_panes(window, cx);
11766 });
11767
11768 workspace.update(cx, |workspace, cx| {
11769 let num_panes = workspace.panes().len();
11770 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11771 let active_item = workspace
11772 .active_pane()
11773 .read(cx)
11774 .active_item()
11775 .expect("item is in focus");
11776
11777 assert_eq!(num_panes, 1);
11778 assert_eq!(num_items_in_current_pane, 3);
11779 assert_eq!(active_item.item_id(), last_item.item_id());
11780 });
11781 }
11782 struct TestModal(FocusHandle);
11783
11784 impl TestModal {
11785 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11786 Self(cx.focus_handle())
11787 }
11788 }
11789
11790 impl EventEmitter<DismissEvent> for TestModal {}
11791
11792 impl Focusable for TestModal {
11793 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11794 self.0.clone()
11795 }
11796 }
11797
11798 impl ModalView for TestModal {}
11799
11800 impl Render for TestModal {
11801 fn render(
11802 &mut self,
11803 _window: &mut Window,
11804 _cx: &mut Context<TestModal>,
11805 ) -> impl IntoElement {
11806 div().track_focus(&self.0)
11807 }
11808 }
11809
11810 #[gpui::test]
11811 async fn test_panels(cx: &mut gpui::TestAppContext) {
11812 init_test(cx);
11813 let fs = FakeFs::new(cx.executor());
11814
11815 let project = Project::test(fs, [], cx).await;
11816 let (multi_workspace, cx) =
11817 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11818 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11819
11820 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11821 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11822 workspace.add_panel(panel_1.clone(), window, cx);
11823 workspace.toggle_dock(DockPosition::Left, window, cx);
11824 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11825 workspace.add_panel(panel_2.clone(), window, cx);
11826 workspace.toggle_dock(DockPosition::Right, window, cx);
11827
11828 let left_dock = workspace.left_dock();
11829 assert_eq!(
11830 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11831 panel_1.panel_id()
11832 );
11833 assert_eq!(
11834 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11835 panel_1.size(window, cx)
11836 );
11837
11838 left_dock.update(cx, |left_dock, cx| {
11839 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11840 });
11841 assert_eq!(
11842 workspace
11843 .right_dock()
11844 .read(cx)
11845 .visible_panel()
11846 .unwrap()
11847 .panel_id(),
11848 panel_2.panel_id(),
11849 );
11850
11851 (panel_1, panel_2)
11852 });
11853
11854 // Move panel_1 to the right
11855 panel_1.update_in(cx, |panel_1, window, cx| {
11856 panel_1.set_position(DockPosition::Right, window, cx)
11857 });
11858
11859 workspace.update_in(cx, |workspace, window, cx| {
11860 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11861 // Since it was the only panel on the left, the left dock should now be closed.
11862 assert!(!workspace.left_dock().read(cx).is_open());
11863 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11864 let right_dock = workspace.right_dock();
11865 assert_eq!(
11866 right_dock.read(cx).visible_panel().unwrap().panel_id(),
11867 panel_1.panel_id()
11868 );
11869 assert_eq!(
11870 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11871 px(1337.)
11872 );
11873
11874 // Now we move panel_2 to the left
11875 panel_2.set_position(DockPosition::Left, window, cx);
11876 });
11877
11878 workspace.update(cx, |workspace, cx| {
11879 // Since panel_2 was not visible on the right, we don't open the left dock.
11880 assert!(!workspace.left_dock().read(cx).is_open());
11881 // And the right dock is unaffected in its displaying of panel_1
11882 assert!(workspace.right_dock().read(cx).is_open());
11883 assert_eq!(
11884 workspace
11885 .right_dock()
11886 .read(cx)
11887 .visible_panel()
11888 .unwrap()
11889 .panel_id(),
11890 panel_1.panel_id(),
11891 );
11892 });
11893
11894 // Move panel_1 back to the left
11895 panel_1.update_in(cx, |panel_1, window, cx| {
11896 panel_1.set_position(DockPosition::Left, window, cx)
11897 });
11898
11899 workspace.update_in(cx, |workspace, window, cx| {
11900 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11901 let left_dock = workspace.left_dock();
11902 assert!(left_dock.read(cx).is_open());
11903 assert_eq!(
11904 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11905 panel_1.panel_id()
11906 );
11907 assert_eq!(
11908 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11909 px(1337.)
11910 );
11911 // And the right dock should be closed as it no longer has any panels.
11912 assert!(!workspace.right_dock().read(cx).is_open());
11913
11914 // Now we move panel_1 to the bottom
11915 panel_1.set_position(DockPosition::Bottom, window, cx);
11916 });
11917
11918 workspace.update_in(cx, |workspace, window, cx| {
11919 // Since panel_1 was visible on the left, we close the left dock.
11920 assert!(!workspace.left_dock().read(cx).is_open());
11921 // The bottom dock is sized based on the panel's default size,
11922 // since the panel orientation changed from vertical to horizontal.
11923 let bottom_dock = workspace.bottom_dock();
11924 assert_eq!(
11925 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
11926 panel_1.size(window, cx),
11927 );
11928 // Close bottom dock and move panel_1 back to the left.
11929 bottom_dock.update(cx, |bottom_dock, cx| {
11930 bottom_dock.set_open(false, window, cx)
11931 });
11932 panel_1.set_position(DockPosition::Left, window, cx);
11933 });
11934
11935 // Emit activated event on panel 1
11936 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
11937
11938 // Now the left dock is open and panel_1 is active and focused.
11939 workspace.update_in(cx, |workspace, window, cx| {
11940 let left_dock = workspace.left_dock();
11941 assert!(left_dock.read(cx).is_open());
11942 assert_eq!(
11943 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11944 panel_1.panel_id(),
11945 );
11946 assert!(panel_1.focus_handle(cx).is_focused(window));
11947 });
11948
11949 // Emit closed event on panel 2, which is not active
11950 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11951
11952 // Wo don't close the left dock, because panel_2 wasn't the active panel
11953 workspace.update(cx, |workspace, cx| {
11954 let left_dock = workspace.left_dock();
11955 assert!(left_dock.read(cx).is_open());
11956 assert_eq!(
11957 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11958 panel_1.panel_id(),
11959 );
11960 });
11961
11962 // Emitting a ZoomIn event shows the panel as zoomed.
11963 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
11964 workspace.read_with(cx, |workspace, _| {
11965 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11966 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
11967 });
11968
11969 // Move panel to another dock while it is zoomed
11970 panel_1.update_in(cx, |panel, window, cx| {
11971 panel.set_position(DockPosition::Right, window, cx)
11972 });
11973 workspace.read_with(cx, |workspace, _| {
11974 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11975
11976 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11977 });
11978
11979 // This is a helper for getting a:
11980 // - valid focus on an element,
11981 // - that isn't a part of the panes and panels system of the Workspace,
11982 // - and doesn't trigger the 'on_focus_lost' API.
11983 let focus_other_view = {
11984 let workspace = workspace.clone();
11985 move |cx: &mut VisualTestContext| {
11986 workspace.update_in(cx, |workspace, window, cx| {
11987 if workspace.active_modal::<TestModal>(cx).is_some() {
11988 workspace.toggle_modal(window, cx, TestModal::new);
11989 workspace.toggle_modal(window, cx, TestModal::new);
11990 } else {
11991 workspace.toggle_modal(window, cx, TestModal::new);
11992 }
11993 })
11994 }
11995 };
11996
11997 // If focus is transferred to another view that's not a panel or another pane, we still show
11998 // the panel as zoomed.
11999 focus_other_view(cx);
12000 workspace.read_with(cx, |workspace, _| {
12001 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12002 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12003 });
12004
12005 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12006 workspace.update_in(cx, |_workspace, window, cx| {
12007 cx.focus_self(window);
12008 });
12009 workspace.read_with(cx, |workspace, _| {
12010 assert_eq!(workspace.zoomed, None);
12011 assert_eq!(workspace.zoomed_position, None);
12012 });
12013
12014 // If focus is transferred again to another view that's not a panel or a pane, we won't
12015 // show the panel as zoomed because it wasn't zoomed before.
12016 focus_other_view(cx);
12017 workspace.read_with(cx, |workspace, _| {
12018 assert_eq!(workspace.zoomed, None);
12019 assert_eq!(workspace.zoomed_position, None);
12020 });
12021
12022 // When the panel is activated, it is zoomed again.
12023 cx.dispatch_action(ToggleRightDock);
12024 workspace.read_with(cx, |workspace, _| {
12025 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12026 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12027 });
12028
12029 // Emitting a ZoomOut event unzooms the panel.
12030 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12031 workspace.read_with(cx, |workspace, _| {
12032 assert_eq!(workspace.zoomed, None);
12033 assert_eq!(workspace.zoomed_position, None);
12034 });
12035
12036 // Emit closed event on panel 1, which is active
12037 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12038
12039 // Now the left dock is closed, because panel_1 was the active panel
12040 workspace.update(cx, |workspace, cx| {
12041 let right_dock = workspace.right_dock();
12042 assert!(!right_dock.read(cx).is_open());
12043 });
12044 }
12045
12046 #[gpui::test]
12047 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12048 init_test(cx);
12049
12050 let fs = FakeFs::new(cx.background_executor.clone());
12051 let project = Project::test(fs, [], cx).await;
12052 let (workspace, cx) =
12053 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12054 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12055
12056 let dirty_regular_buffer = cx.new(|cx| {
12057 TestItem::new(cx)
12058 .with_dirty(true)
12059 .with_label("1.txt")
12060 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12061 });
12062 let dirty_regular_buffer_2 = cx.new(|cx| {
12063 TestItem::new(cx)
12064 .with_dirty(true)
12065 .with_label("2.txt")
12066 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12067 });
12068 let dirty_multi_buffer_with_both = cx.new(|cx| {
12069 TestItem::new(cx)
12070 .with_dirty(true)
12071 .with_buffer_kind(ItemBufferKind::Multibuffer)
12072 .with_label("Fake Project Search")
12073 .with_project_items(&[
12074 dirty_regular_buffer.read(cx).project_items[0].clone(),
12075 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12076 ])
12077 });
12078 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12079 workspace.update_in(cx, |workspace, window, cx| {
12080 workspace.add_item(
12081 pane.clone(),
12082 Box::new(dirty_regular_buffer.clone()),
12083 None,
12084 false,
12085 false,
12086 window,
12087 cx,
12088 );
12089 workspace.add_item(
12090 pane.clone(),
12091 Box::new(dirty_regular_buffer_2.clone()),
12092 None,
12093 false,
12094 false,
12095 window,
12096 cx,
12097 );
12098 workspace.add_item(
12099 pane.clone(),
12100 Box::new(dirty_multi_buffer_with_both.clone()),
12101 None,
12102 false,
12103 false,
12104 window,
12105 cx,
12106 );
12107 });
12108
12109 pane.update_in(cx, |pane, window, cx| {
12110 pane.activate_item(2, true, true, window, cx);
12111 assert_eq!(
12112 pane.active_item().unwrap().item_id(),
12113 multi_buffer_with_both_files_id,
12114 "Should select the multi buffer in the pane"
12115 );
12116 });
12117 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12118 pane.close_other_items(
12119 &CloseOtherItems {
12120 save_intent: Some(SaveIntent::Save),
12121 close_pinned: true,
12122 },
12123 None,
12124 window,
12125 cx,
12126 )
12127 });
12128 cx.background_executor.run_until_parked();
12129 assert!(!cx.has_pending_prompt());
12130 close_all_but_multi_buffer_task
12131 .await
12132 .expect("Closing all buffers but the multi buffer failed");
12133 pane.update(cx, |pane, cx| {
12134 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12135 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12136 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12137 assert_eq!(pane.items_len(), 1);
12138 assert_eq!(
12139 pane.active_item().unwrap().item_id(),
12140 multi_buffer_with_both_files_id,
12141 "Should have only the multi buffer left in the pane"
12142 );
12143 assert!(
12144 dirty_multi_buffer_with_both.read(cx).is_dirty,
12145 "The multi buffer containing the unsaved buffer should still be dirty"
12146 );
12147 });
12148
12149 dirty_regular_buffer.update(cx, |buffer, cx| {
12150 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12151 });
12152
12153 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12154 pane.close_active_item(
12155 &CloseActiveItem {
12156 save_intent: Some(SaveIntent::Close),
12157 close_pinned: false,
12158 },
12159 window,
12160 cx,
12161 )
12162 });
12163 cx.background_executor.run_until_parked();
12164 assert!(
12165 cx.has_pending_prompt(),
12166 "Dirty multi buffer should prompt a save dialog"
12167 );
12168 cx.simulate_prompt_answer("Save");
12169 cx.background_executor.run_until_parked();
12170 close_multi_buffer_task
12171 .await
12172 .expect("Closing the multi buffer failed");
12173 pane.update(cx, |pane, cx| {
12174 assert_eq!(
12175 dirty_multi_buffer_with_both.read(cx).save_count,
12176 1,
12177 "Multi buffer item should get be saved"
12178 );
12179 // Test impl does not save inner items, so we do not assert them
12180 assert_eq!(
12181 pane.items_len(),
12182 0,
12183 "No more items should be left in the pane"
12184 );
12185 assert!(pane.active_item().is_none());
12186 });
12187 }
12188
12189 #[gpui::test]
12190 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
12191 cx: &mut TestAppContext,
12192 ) {
12193 init_test(cx);
12194
12195 let fs = FakeFs::new(cx.background_executor.clone());
12196 let project = Project::test(fs, [], cx).await;
12197 let (workspace, cx) =
12198 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12199 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12200
12201 let dirty_regular_buffer = cx.new(|cx| {
12202 TestItem::new(cx)
12203 .with_dirty(true)
12204 .with_label("1.txt")
12205 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12206 });
12207 let dirty_regular_buffer_2 = cx.new(|cx| {
12208 TestItem::new(cx)
12209 .with_dirty(true)
12210 .with_label("2.txt")
12211 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12212 });
12213 let clear_regular_buffer = cx.new(|cx| {
12214 TestItem::new(cx)
12215 .with_label("3.txt")
12216 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12217 });
12218
12219 let dirty_multi_buffer_with_both = cx.new(|cx| {
12220 TestItem::new(cx)
12221 .with_dirty(true)
12222 .with_buffer_kind(ItemBufferKind::Multibuffer)
12223 .with_label("Fake Project Search")
12224 .with_project_items(&[
12225 dirty_regular_buffer.read(cx).project_items[0].clone(),
12226 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12227 clear_regular_buffer.read(cx).project_items[0].clone(),
12228 ])
12229 });
12230 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12231 workspace.update_in(cx, |workspace, window, cx| {
12232 workspace.add_item(
12233 pane.clone(),
12234 Box::new(dirty_regular_buffer.clone()),
12235 None,
12236 false,
12237 false,
12238 window,
12239 cx,
12240 );
12241 workspace.add_item(
12242 pane.clone(),
12243 Box::new(dirty_multi_buffer_with_both.clone()),
12244 None,
12245 false,
12246 false,
12247 window,
12248 cx,
12249 );
12250 });
12251
12252 pane.update_in(cx, |pane, window, cx| {
12253 pane.activate_item(1, true, true, window, cx);
12254 assert_eq!(
12255 pane.active_item().unwrap().item_id(),
12256 multi_buffer_with_both_files_id,
12257 "Should select the multi buffer in the pane"
12258 );
12259 });
12260 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12261 pane.close_active_item(
12262 &CloseActiveItem {
12263 save_intent: None,
12264 close_pinned: false,
12265 },
12266 window,
12267 cx,
12268 )
12269 });
12270 cx.background_executor.run_until_parked();
12271 assert!(
12272 cx.has_pending_prompt(),
12273 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
12274 );
12275 }
12276
12277 /// Tests that when `close_on_file_delete` is enabled, files are automatically
12278 /// closed when they are deleted from disk.
12279 #[gpui::test]
12280 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
12281 init_test(cx);
12282
12283 // Enable the close_on_disk_deletion setting
12284 cx.update_global(|store: &mut SettingsStore, cx| {
12285 store.update_user_settings(cx, |settings| {
12286 settings.workspace.close_on_file_delete = Some(true);
12287 });
12288 });
12289
12290 let fs = FakeFs::new(cx.background_executor.clone());
12291 let project = Project::test(fs, [], cx).await;
12292 let (workspace, cx) =
12293 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12294 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12295
12296 // Create a test item that simulates a file
12297 let item = cx.new(|cx| {
12298 TestItem::new(cx)
12299 .with_label("test.txt")
12300 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12301 });
12302
12303 // Add item to workspace
12304 workspace.update_in(cx, |workspace, window, cx| {
12305 workspace.add_item(
12306 pane.clone(),
12307 Box::new(item.clone()),
12308 None,
12309 false,
12310 false,
12311 window,
12312 cx,
12313 );
12314 });
12315
12316 // Verify the item is in the pane
12317 pane.read_with(cx, |pane, _| {
12318 assert_eq!(pane.items().count(), 1);
12319 });
12320
12321 // Simulate file deletion by setting the item's deleted state
12322 item.update(cx, |item, _| {
12323 item.set_has_deleted_file(true);
12324 });
12325
12326 // Emit UpdateTab event to trigger the close behavior
12327 cx.run_until_parked();
12328 item.update(cx, |_, cx| {
12329 cx.emit(ItemEvent::UpdateTab);
12330 });
12331
12332 // Allow the close operation to complete
12333 cx.run_until_parked();
12334
12335 // Verify the item was automatically closed
12336 pane.read_with(cx, |pane, _| {
12337 assert_eq!(
12338 pane.items().count(),
12339 0,
12340 "Item should be automatically closed when file is deleted"
12341 );
12342 });
12343 }
12344
12345 /// Tests that when `close_on_file_delete` is disabled (default), files remain
12346 /// open with a strikethrough when they are deleted from disk.
12347 #[gpui::test]
12348 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12349 init_test(cx);
12350
12351 // Ensure close_on_disk_deletion is disabled (default)
12352 cx.update_global(|store: &mut SettingsStore, cx| {
12353 store.update_user_settings(cx, |settings| {
12354 settings.workspace.close_on_file_delete = Some(false);
12355 });
12356 });
12357
12358 let fs = FakeFs::new(cx.background_executor.clone());
12359 let project = Project::test(fs, [], cx).await;
12360 let (workspace, cx) =
12361 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12362 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12363
12364 // Create a test item that simulates a file
12365 let item = cx.new(|cx| {
12366 TestItem::new(cx)
12367 .with_label("test.txt")
12368 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12369 });
12370
12371 // Add item to workspace
12372 workspace.update_in(cx, |workspace, window, cx| {
12373 workspace.add_item(
12374 pane.clone(),
12375 Box::new(item.clone()),
12376 None,
12377 false,
12378 false,
12379 window,
12380 cx,
12381 );
12382 });
12383
12384 // Verify the item is in the pane
12385 pane.read_with(cx, |pane, _| {
12386 assert_eq!(pane.items().count(), 1);
12387 });
12388
12389 // Simulate file deletion
12390 item.update(cx, |item, _| {
12391 item.set_has_deleted_file(true);
12392 });
12393
12394 // Emit UpdateTab event
12395 cx.run_until_parked();
12396 item.update(cx, |_, cx| {
12397 cx.emit(ItemEvent::UpdateTab);
12398 });
12399
12400 // Allow any potential close operation to complete
12401 cx.run_until_parked();
12402
12403 // Verify the item remains open (with strikethrough)
12404 pane.read_with(cx, |pane, _| {
12405 assert_eq!(
12406 pane.items().count(),
12407 1,
12408 "Item should remain open when close_on_disk_deletion is disabled"
12409 );
12410 });
12411
12412 // Verify the item shows as deleted
12413 item.read_with(cx, |item, _| {
12414 assert!(
12415 item.has_deleted_file,
12416 "Item should be marked as having deleted file"
12417 );
12418 });
12419 }
12420
12421 /// Tests that dirty files are not automatically closed when deleted from disk,
12422 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12423 /// unsaved changes without being prompted.
12424 #[gpui::test]
12425 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12426 init_test(cx);
12427
12428 // Enable the close_on_file_delete setting
12429 cx.update_global(|store: &mut SettingsStore, cx| {
12430 store.update_user_settings(cx, |settings| {
12431 settings.workspace.close_on_file_delete = Some(true);
12432 });
12433 });
12434
12435 let fs = FakeFs::new(cx.background_executor.clone());
12436 let project = Project::test(fs, [], cx).await;
12437 let (workspace, cx) =
12438 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12439 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12440
12441 // Create a dirty test item
12442 let item = cx.new(|cx| {
12443 TestItem::new(cx)
12444 .with_dirty(true)
12445 .with_label("test.txt")
12446 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12447 });
12448
12449 // Add item to workspace
12450 workspace.update_in(cx, |workspace, window, cx| {
12451 workspace.add_item(
12452 pane.clone(),
12453 Box::new(item.clone()),
12454 None,
12455 false,
12456 false,
12457 window,
12458 cx,
12459 );
12460 });
12461
12462 // Simulate file deletion
12463 item.update(cx, |item, _| {
12464 item.set_has_deleted_file(true);
12465 });
12466
12467 // Emit UpdateTab event to trigger the close behavior
12468 cx.run_until_parked();
12469 item.update(cx, |_, cx| {
12470 cx.emit(ItemEvent::UpdateTab);
12471 });
12472
12473 // Allow any potential close operation to complete
12474 cx.run_until_parked();
12475
12476 // Verify the item remains open (dirty files are not auto-closed)
12477 pane.read_with(cx, |pane, _| {
12478 assert_eq!(
12479 pane.items().count(),
12480 1,
12481 "Dirty items should not be automatically closed even when file is deleted"
12482 );
12483 });
12484
12485 // Verify the item is marked as deleted and still dirty
12486 item.read_with(cx, |item, _| {
12487 assert!(
12488 item.has_deleted_file,
12489 "Item should be marked as having deleted file"
12490 );
12491 assert!(item.is_dirty, "Item should still be dirty");
12492 });
12493 }
12494
12495 /// Tests that navigation history is cleaned up when files are auto-closed
12496 /// due to deletion from disk.
12497 #[gpui::test]
12498 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12499 init_test(cx);
12500
12501 // Enable the close_on_file_delete setting
12502 cx.update_global(|store: &mut SettingsStore, cx| {
12503 store.update_user_settings(cx, |settings| {
12504 settings.workspace.close_on_file_delete = Some(true);
12505 });
12506 });
12507
12508 let fs = FakeFs::new(cx.background_executor.clone());
12509 let project = Project::test(fs, [], cx).await;
12510 let (workspace, cx) =
12511 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12512 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12513
12514 // Create test items
12515 let item1 = cx.new(|cx| {
12516 TestItem::new(cx)
12517 .with_label("test1.txt")
12518 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12519 });
12520 let item1_id = item1.item_id();
12521
12522 let item2 = cx.new(|cx| {
12523 TestItem::new(cx)
12524 .with_label("test2.txt")
12525 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12526 });
12527
12528 // Add items to workspace
12529 workspace.update_in(cx, |workspace, window, cx| {
12530 workspace.add_item(
12531 pane.clone(),
12532 Box::new(item1.clone()),
12533 None,
12534 false,
12535 false,
12536 window,
12537 cx,
12538 );
12539 workspace.add_item(
12540 pane.clone(),
12541 Box::new(item2.clone()),
12542 None,
12543 false,
12544 false,
12545 window,
12546 cx,
12547 );
12548 });
12549
12550 // Activate item1 to ensure it gets navigation entries
12551 pane.update_in(cx, |pane, window, cx| {
12552 pane.activate_item(0, true, true, window, cx);
12553 });
12554
12555 // Switch to item2 and back to create navigation history
12556 pane.update_in(cx, |pane, window, cx| {
12557 pane.activate_item(1, true, true, window, cx);
12558 });
12559 cx.run_until_parked();
12560
12561 pane.update_in(cx, |pane, window, cx| {
12562 pane.activate_item(0, true, true, window, cx);
12563 });
12564 cx.run_until_parked();
12565
12566 // Simulate file deletion for item1
12567 item1.update(cx, |item, _| {
12568 item.set_has_deleted_file(true);
12569 });
12570
12571 // Emit UpdateTab event to trigger the close behavior
12572 item1.update(cx, |_, cx| {
12573 cx.emit(ItemEvent::UpdateTab);
12574 });
12575 cx.run_until_parked();
12576
12577 // Verify item1 was closed
12578 pane.read_with(cx, |pane, _| {
12579 assert_eq!(
12580 pane.items().count(),
12581 1,
12582 "Should have 1 item remaining after auto-close"
12583 );
12584 });
12585
12586 // Check navigation history after close
12587 let has_item = pane.read_with(cx, |pane, cx| {
12588 let mut has_item = false;
12589 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12590 if entry.item.id() == item1_id {
12591 has_item = true;
12592 }
12593 });
12594 has_item
12595 });
12596
12597 assert!(
12598 !has_item,
12599 "Navigation history should not contain closed item entries"
12600 );
12601 }
12602
12603 #[gpui::test]
12604 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12605 cx: &mut TestAppContext,
12606 ) {
12607 init_test(cx);
12608
12609 let fs = FakeFs::new(cx.background_executor.clone());
12610 let project = Project::test(fs, [], cx).await;
12611 let (workspace, cx) =
12612 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12613 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12614
12615 let dirty_regular_buffer = cx.new(|cx| {
12616 TestItem::new(cx)
12617 .with_dirty(true)
12618 .with_label("1.txt")
12619 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12620 });
12621 let dirty_regular_buffer_2 = cx.new(|cx| {
12622 TestItem::new(cx)
12623 .with_dirty(true)
12624 .with_label("2.txt")
12625 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12626 });
12627 let clear_regular_buffer = cx.new(|cx| {
12628 TestItem::new(cx)
12629 .with_label("3.txt")
12630 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12631 });
12632
12633 let dirty_multi_buffer = cx.new(|cx| {
12634 TestItem::new(cx)
12635 .with_dirty(true)
12636 .with_buffer_kind(ItemBufferKind::Multibuffer)
12637 .with_label("Fake Project Search")
12638 .with_project_items(&[
12639 dirty_regular_buffer.read(cx).project_items[0].clone(),
12640 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12641 clear_regular_buffer.read(cx).project_items[0].clone(),
12642 ])
12643 });
12644 workspace.update_in(cx, |workspace, window, cx| {
12645 workspace.add_item(
12646 pane.clone(),
12647 Box::new(dirty_regular_buffer.clone()),
12648 None,
12649 false,
12650 false,
12651 window,
12652 cx,
12653 );
12654 workspace.add_item(
12655 pane.clone(),
12656 Box::new(dirty_regular_buffer_2.clone()),
12657 None,
12658 false,
12659 false,
12660 window,
12661 cx,
12662 );
12663 workspace.add_item(
12664 pane.clone(),
12665 Box::new(dirty_multi_buffer.clone()),
12666 None,
12667 false,
12668 false,
12669 window,
12670 cx,
12671 );
12672 });
12673
12674 pane.update_in(cx, |pane, window, cx| {
12675 pane.activate_item(2, true, true, window, cx);
12676 assert_eq!(
12677 pane.active_item().unwrap().item_id(),
12678 dirty_multi_buffer.item_id(),
12679 "Should select the multi buffer in the pane"
12680 );
12681 });
12682 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12683 pane.close_active_item(
12684 &CloseActiveItem {
12685 save_intent: None,
12686 close_pinned: false,
12687 },
12688 window,
12689 cx,
12690 )
12691 });
12692 cx.background_executor.run_until_parked();
12693 assert!(
12694 !cx.has_pending_prompt(),
12695 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12696 );
12697 close_multi_buffer_task
12698 .await
12699 .expect("Closing multi buffer failed");
12700 pane.update(cx, |pane, cx| {
12701 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12702 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12703 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12704 assert_eq!(
12705 pane.items()
12706 .map(|item| item.item_id())
12707 .sorted()
12708 .collect::<Vec<_>>(),
12709 vec![
12710 dirty_regular_buffer.item_id(),
12711 dirty_regular_buffer_2.item_id(),
12712 ],
12713 "Should have no multi buffer left in the pane"
12714 );
12715 assert!(dirty_regular_buffer.read(cx).is_dirty);
12716 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12717 });
12718 }
12719
12720 #[gpui::test]
12721 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12722 init_test(cx);
12723 let fs = FakeFs::new(cx.executor());
12724 let project = Project::test(fs, [], cx).await;
12725 let (multi_workspace, cx) =
12726 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12727 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12728
12729 // Add a new panel to the right dock, opening the dock and setting the
12730 // focus to the new panel.
12731 let panel = workspace.update_in(cx, |workspace, window, cx| {
12732 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12733 workspace.add_panel(panel.clone(), window, cx);
12734
12735 workspace
12736 .right_dock()
12737 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12738
12739 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12740
12741 panel
12742 });
12743
12744 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12745 // panel to the next valid position which, in this case, is the left
12746 // dock.
12747 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12748 workspace.update(cx, |workspace, cx| {
12749 assert!(workspace.left_dock().read(cx).is_open());
12750 assert_eq!(panel.read(cx).position, DockPosition::Left);
12751 });
12752
12753 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12754 // panel to the next valid position which, in this case, is the bottom
12755 // dock.
12756 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12757 workspace.update(cx, |workspace, cx| {
12758 assert!(workspace.bottom_dock().read(cx).is_open());
12759 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12760 });
12761
12762 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12763 // around moving the panel to its initial position, the right dock.
12764 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12765 workspace.update(cx, |workspace, cx| {
12766 assert!(workspace.right_dock().read(cx).is_open());
12767 assert_eq!(panel.read(cx).position, DockPosition::Right);
12768 });
12769
12770 // Remove focus from the panel, ensuring that, if the panel is not
12771 // focused, the `MoveFocusedPanelToNextPosition` action does not update
12772 // the panel's position, so the panel is still in the right dock.
12773 workspace.update_in(cx, |workspace, window, cx| {
12774 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12775 });
12776
12777 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12778 workspace.update(cx, |workspace, cx| {
12779 assert!(workspace.right_dock().read(cx).is_open());
12780 assert_eq!(panel.read(cx).position, DockPosition::Right);
12781 });
12782 }
12783
12784 #[gpui::test]
12785 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12786 init_test(cx);
12787
12788 let fs = FakeFs::new(cx.executor());
12789 let project = Project::test(fs, [], cx).await;
12790 let (workspace, cx) =
12791 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12792
12793 let item_1 = cx.new(|cx| {
12794 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12795 });
12796 workspace.update_in(cx, |workspace, window, cx| {
12797 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12798 workspace.move_item_to_pane_in_direction(
12799 &MoveItemToPaneInDirection {
12800 direction: SplitDirection::Right,
12801 focus: true,
12802 clone: false,
12803 },
12804 window,
12805 cx,
12806 );
12807 workspace.move_item_to_pane_at_index(
12808 &MoveItemToPane {
12809 destination: 3,
12810 focus: true,
12811 clone: false,
12812 },
12813 window,
12814 cx,
12815 );
12816
12817 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12818 assert_eq!(
12819 pane_items_paths(&workspace.active_pane, cx),
12820 vec!["first.txt".to_string()],
12821 "Single item was not moved anywhere"
12822 );
12823 });
12824
12825 let item_2 = cx.new(|cx| {
12826 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12827 });
12828 workspace.update_in(cx, |workspace, window, cx| {
12829 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12830 assert_eq!(
12831 pane_items_paths(&workspace.panes[0], cx),
12832 vec!["first.txt".to_string(), "second.txt".to_string()],
12833 );
12834 workspace.move_item_to_pane_in_direction(
12835 &MoveItemToPaneInDirection {
12836 direction: SplitDirection::Right,
12837 focus: true,
12838 clone: false,
12839 },
12840 window,
12841 cx,
12842 );
12843
12844 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12845 assert_eq!(
12846 pane_items_paths(&workspace.panes[0], cx),
12847 vec!["first.txt".to_string()],
12848 "After moving, one item should be left in the original pane"
12849 );
12850 assert_eq!(
12851 pane_items_paths(&workspace.panes[1], cx),
12852 vec!["second.txt".to_string()],
12853 "New item should have been moved to the new pane"
12854 );
12855 });
12856
12857 let item_3 = cx.new(|cx| {
12858 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12859 });
12860 workspace.update_in(cx, |workspace, window, cx| {
12861 let original_pane = workspace.panes[0].clone();
12862 workspace.set_active_pane(&original_pane, window, cx);
12863 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12864 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12865 assert_eq!(
12866 pane_items_paths(&workspace.active_pane, cx),
12867 vec!["first.txt".to_string(), "third.txt".to_string()],
12868 "New pane should be ready to move one item out"
12869 );
12870
12871 workspace.move_item_to_pane_at_index(
12872 &MoveItemToPane {
12873 destination: 3,
12874 focus: true,
12875 clone: false,
12876 },
12877 window,
12878 cx,
12879 );
12880 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12881 assert_eq!(
12882 pane_items_paths(&workspace.active_pane, cx),
12883 vec!["first.txt".to_string()],
12884 "After moving, one item should be left in the original pane"
12885 );
12886 assert_eq!(
12887 pane_items_paths(&workspace.panes[1], cx),
12888 vec!["second.txt".to_string()],
12889 "Previously created pane should be unchanged"
12890 );
12891 assert_eq!(
12892 pane_items_paths(&workspace.panes[2], cx),
12893 vec!["third.txt".to_string()],
12894 "New item should have been moved to the new pane"
12895 );
12896 });
12897 }
12898
12899 #[gpui::test]
12900 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12901 init_test(cx);
12902
12903 let fs = FakeFs::new(cx.executor());
12904 let project = Project::test(fs, [], cx).await;
12905 let (workspace, cx) =
12906 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12907
12908 let item_1 = cx.new(|cx| {
12909 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12910 });
12911 workspace.update_in(cx, |workspace, window, cx| {
12912 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12913 workspace.move_item_to_pane_in_direction(
12914 &MoveItemToPaneInDirection {
12915 direction: SplitDirection::Right,
12916 focus: true,
12917 clone: true,
12918 },
12919 window,
12920 cx,
12921 );
12922 });
12923 cx.run_until_parked();
12924 workspace.update_in(cx, |workspace, window, cx| {
12925 workspace.move_item_to_pane_at_index(
12926 &MoveItemToPane {
12927 destination: 3,
12928 focus: true,
12929 clone: true,
12930 },
12931 window,
12932 cx,
12933 );
12934 });
12935 cx.run_until_parked();
12936
12937 workspace.update(cx, |workspace, cx| {
12938 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
12939 for pane in workspace.panes() {
12940 assert_eq!(
12941 pane_items_paths(pane, cx),
12942 vec!["first.txt".to_string()],
12943 "Single item exists in all panes"
12944 );
12945 }
12946 });
12947
12948 // verify that the active pane has been updated after waiting for the
12949 // pane focus event to fire and resolve
12950 workspace.read_with(cx, |workspace, _app| {
12951 assert_eq!(
12952 workspace.active_pane(),
12953 &workspace.panes[2],
12954 "The third pane should be the active one: {:?}",
12955 workspace.panes
12956 );
12957 })
12958 }
12959
12960 #[gpui::test]
12961 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
12962 init_test(cx);
12963
12964 let fs = FakeFs::new(cx.executor());
12965 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
12966
12967 let project = Project::test(fs, ["root".as_ref()], cx).await;
12968 let (workspace, cx) =
12969 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12970
12971 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12972 // Add item to pane A with project path
12973 let item_a = cx.new(|cx| {
12974 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12975 });
12976 workspace.update_in(cx, |workspace, window, cx| {
12977 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
12978 });
12979
12980 // Split to create pane B
12981 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
12982 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
12983 });
12984
12985 // Add item with SAME project path to pane B, and pin it
12986 let item_b = cx.new(|cx| {
12987 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12988 });
12989 pane_b.update_in(cx, |pane, window, cx| {
12990 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
12991 pane.set_pinned_count(1);
12992 });
12993
12994 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
12995 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
12996
12997 // close_pinned: false should only close the unpinned copy
12998 workspace.update_in(cx, |workspace, window, cx| {
12999 workspace.close_item_in_all_panes(
13000 &CloseItemInAllPanes {
13001 save_intent: Some(SaveIntent::Close),
13002 close_pinned: false,
13003 },
13004 window,
13005 cx,
13006 )
13007 });
13008 cx.executor().run_until_parked();
13009
13010 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13011 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13012 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13013 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13014
13015 // Split again, seeing as closing the previous item also closed its
13016 // pane, so only pane remains, which does not allow us to properly test
13017 // that both items close when `close_pinned: true`.
13018 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13019 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13020 });
13021
13022 // Add an item with the same project path to pane C so that
13023 // close_item_in_all_panes can determine what to close across all panes
13024 // (it reads the active item from the active pane, and split_pane
13025 // creates an empty pane).
13026 let item_c = cx.new(|cx| {
13027 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13028 });
13029 pane_c.update_in(cx, |pane, window, cx| {
13030 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13031 });
13032
13033 // close_pinned: true should close the pinned copy too
13034 workspace.update_in(cx, |workspace, window, cx| {
13035 let panes_count = workspace.panes().len();
13036 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13037
13038 workspace.close_item_in_all_panes(
13039 &CloseItemInAllPanes {
13040 save_intent: Some(SaveIntent::Close),
13041 close_pinned: true,
13042 },
13043 window,
13044 cx,
13045 )
13046 });
13047 cx.executor().run_until_parked();
13048
13049 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13050 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13051 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13052 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13053 }
13054
13055 mod register_project_item_tests {
13056
13057 use super::*;
13058
13059 // View
13060 struct TestPngItemView {
13061 focus_handle: FocusHandle,
13062 }
13063 // Model
13064 struct TestPngItem {}
13065
13066 impl project::ProjectItem for TestPngItem {
13067 fn try_open(
13068 _project: &Entity<Project>,
13069 path: &ProjectPath,
13070 cx: &mut App,
13071 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13072 if path.path.extension().unwrap() == "png" {
13073 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13074 } else {
13075 None
13076 }
13077 }
13078
13079 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13080 None
13081 }
13082
13083 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13084 None
13085 }
13086
13087 fn is_dirty(&self) -> bool {
13088 false
13089 }
13090 }
13091
13092 impl Item for TestPngItemView {
13093 type Event = ();
13094 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13095 "".into()
13096 }
13097 }
13098 impl EventEmitter<()> for TestPngItemView {}
13099 impl Focusable for TestPngItemView {
13100 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13101 self.focus_handle.clone()
13102 }
13103 }
13104
13105 impl Render for TestPngItemView {
13106 fn render(
13107 &mut self,
13108 _window: &mut Window,
13109 _cx: &mut Context<Self>,
13110 ) -> impl IntoElement {
13111 Empty
13112 }
13113 }
13114
13115 impl ProjectItem for TestPngItemView {
13116 type Item = TestPngItem;
13117
13118 fn for_project_item(
13119 _project: Entity<Project>,
13120 _pane: Option<&Pane>,
13121 _item: Entity<Self::Item>,
13122 _: &mut Window,
13123 cx: &mut Context<Self>,
13124 ) -> Self
13125 where
13126 Self: Sized,
13127 {
13128 Self {
13129 focus_handle: cx.focus_handle(),
13130 }
13131 }
13132 }
13133
13134 // View
13135 struct TestIpynbItemView {
13136 focus_handle: FocusHandle,
13137 }
13138 // Model
13139 struct TestIpynbItem {}
13140
13141 impl project::ProjectItem for TestIpynbItem {
13142 fn try_open(
13143 _project: &Entity<Project>,
13144 path: &ProjectPath,
13145 cx: &mut App,
13146 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13147 if path.path.extension().unwrap() == "ipynb" {
13148 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13149 } else {
13150 None
13151 }
13152 }
13153
13154 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13155 None
13156 }
13157
13158 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13159 None
13160 }
13161
13162 fn is_dirty(&self) -> bool {
13163 false
13164 }
13165 }
13166
13167 impl Item for TestIpynbItemView {
13168 type Event = ();
13169 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13170 "".into()
13171 }
13172 }
13173 impl EventEmitter<()> for TestIpynbItemView {}
13174 impl Focusable for TestIpynbItemView {
13175 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13176 self.focus_handle.clone()
13177 }
13178 }
13179
13180 impl Render for TestIpynbItemView {
13181 fn render(
13182 &mut self,
13183 _window: &mut Window,
13184 _cx: &mut Context<Self>,
13185 ) -> impl IntoElement {
13186 Empty
13187 }
13188 }
13189
13190 impl ProjectItem for TestIpynbItemView {
13191 type Item = TestIpynbItem;
13192
13193 fn for_project_item(
13194 _project: Entity<Project>,
13195 _pane: Option<&Pane>,
13196 _item: Entity<Self::Item>,
13197 _: &mut Window,
13198 cx: &mut Context<Self>,
13199 ) -> Self
13200 where
13201 Self: Sized,
13202 {
13203 Self {
13204 focus_handle: cx.focus_handle(),
13205 }
13206 }
13207 }
13208
13209 struct TestAlternatePngItemView {
13210 focus_handle: FocusHandle,
13211 }
13212
13213 impl Item for TestAlternatePngItemView {
13214 type Event = ();
13215 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13216 "".into()
13217 }
13218 }
13219
13220 impl EventEmitter<()> for TestAlternatePngItemView {}
13221 impl Focusable for TestAlternatePngItemView {
13222 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13223 self.focus_handle.clone()
13224 }
13225 }
13226
13227 impl Render for TestAlternatePngItemView {
13228 fn render(
13229 &mut self,
13230 _window: &mut Window,
13231 _cx: &mut Context<Self>,
13232 ) -> impl IntoElement {
13233 Empty
13234 }
13235 }
13236
13237 impl ProjectItem for TestAlternatePngItemView {
13238 type Item = TestPngItem;
13239
13240 fn for_project_item(
13241 _project: Entity<Project>,
13242 _pane: Option<&Pane>,
13243 _item: Entity<Self::Item>,
13244 _: &mut Window,
13245 cx: &mut Context<Self>,
13246 ) -> Self
13247 where
13248 Self: Sized,
13249 {
13250 Self {
13251 focus_handle: cx.focus_handle(),
13252 }
13253 }
13254 }
13255
13256 #[gpui::test]
13257 async fn test_register_project_item(cx: &mut TestAppContext) {
13258 init_test(cx);
13259
13260 cx.update(|cx| {
13261 register_project_item::<TestPngItemView>(cx);
13262 register_project_item::<TestIpynbItemView>(cx);
13263 });
13264
13265 let fs = FakeFs::new(cx.executor());
13266 fs.insert_tree(
13267 "/root1",
13268 json!({
13269 "one.png": "BINARYDATAHERE",
13270 "two.ipynb": "{ totally a notebook }",
13271 "three.txt": "editing text, sure why not?"
13272 }),
13273 )
13274 .await;
13275
13276 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13277 let (workspace, cx) =
13278 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13279
13280 let worktree_id = project.update(cx, |project, cx| {
13281 project.worktrees(cx).next().unwrap().read(cx).id()
13282 });
13283
13284 let handle = workspace
13285 .update_in(cx, |workspace, window, cx| {
13286 let project_path = (worktree_id, rel_path("one.png"));
13287 workspace.open_path(project_path, None, true, window, cx)
13288 })
13289 .await
13290 .unwrap();
13291
13292 // Now we can check if the handle we got back errored or not
13293 assert_eq!(
13294 handle.to_any_view().entity_type(),
13295 TypeId::of::<TestPngItemView>()
13296 );
13297
13298 let handle = workspace
13299 .update_in(cx, |workspace, window, cx| {
13300 let project_path = (worktree_id, rel_path("two.ipynb"));
13301 workspace.open_path(project_path, None, true, window, cx)
13302 })
13303 .await
13304 .unwrap();
13305
13306 assert_eq!(
13307 handle.to_any_view().entity_type(),
13308 TypeId::of::<TestIpynbItemView>()
13309 );
13310
13311 let handle = workspace
13312 .update_in(cx, |workspace, window, cx| {
13313 let project_path = (worktree_id, rel_path("three.txt"));
13314 workspace.open_path(project_path, None, true, window, cx)
13315 })
13316 .await;
13317 assert!(handle.is_err());
13318 }
13319
13320 #[gpui::test]
13321 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
13322 init_test(cx);
13323
13324 cx.update(|cx| {
13325 register_project_item::<TestPngItemView>(cx);
13326 register_project_item::<TestAlternatePngItemView>(cx);
13327 });
13328
13329 let fs = FakeFs::new(cx.executor());
13330 fs.insert_tree(
13331 "/root1",
13332 json!({
13333 "one.png": "BINARYDATAHERE",
13334 "two.ipynb": "{ totally a notebook }",
13335 "three.txt": "editing text, sure why not?"
13336 }),
13337 )
13338 .await;
13339 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13340 let (workspace, cx) =
13341 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13342 let worktree_id = project.update(cx, |project, cx| {
13343 project.worktrees(cx).next().unwrap().read(cx).id()
13344 });
13345
13346 let handle = workspace
13347 .update_in(cx, |workspace, window, cx| {
13348 let project_path = (worktree_id, rel_path("one.png"));
13349 workspace.open_path(project_path, None, true, window, cx)
13350 })
13351 .await
13352 .unwrap();
13353
13354 // This _must_ be the second item registered
13355 assert_eq!(
13356 handle.to_any_view().entity_type(),
13357 TypeId::of::<TestAlternatePngItemView>()
13358 );
13359
13360 let handle = workspace
13361 .update_in(cx, |workspace, window, cx| {
13362 let project_path = (worktree_id, rel_path("three.txt"));
13363 workspace.open_path(project_path, None, true, window, cx)
13364 })
13365 .await;
13366 assert!(handle.is_err());
13367 }
13368 }
13369
13370 #[gpui::test]
13371 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13372 init_test(cx);
13373
13374 let fs = FakeFs::new(cx.executor());
13375 let project = Project::test(fs, [], cx).await;
13376 let (workspace, _cx) =
13377 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13378
13379 // Test with status bar shown (default)
13380 workspace.read_with(cx, |workspace, cx| {
13381 let visible = workspace.status_bar_visible(cx);
13382 assert!(visible, "Status bar should be visible by default");
13383 });
13384
13385 // Test with status bar hidden
13386 cx.update_global(|store: &mut SettingsStore, cx| {
13387 store.update_user_settings(cx, |settings| {
13388 settings.status_bar.get_or_insert_default().show = Some(false);
13389 });
13390 });
13391
13392 workspace.read_with(cx, |workspace, cx| {
13393 let visible = workspace.status_bar_visible(cx);
13394 assert!(!visible, "Status bar should be hidden when show is false");
13395 });
13396
13397 // Test with status bar shown explicitly
13398 cx.update_global(|store: &mut SettingsStore, cx| {
13399 store.update_user_settings(cx, |settings| {
13400 settings.status_bar.get_or_insert_default().show = Some(true);
13401 });
13402 });
13403
13404 workspace.read_with(cx, |workspace, cx| {
13405 let visible = workspace.status_bar_visible(cx);
13406 assert!(visible, "Status bar should be visible when show is true");
13407 });
13408 }
13409
13410 #[gpui::test]
13411 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13412 init_test(cx);
13413
13414 let fs = FakeFs::new(cx.executor());
13415 let project = Project::test(fs, [], cx).await;
13416 let (multi_workspace, cx) =
13417 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13418 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13419 let panel = workspace.update_in(cx, |workspace, window, cx| {
13420 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13421 workspace.add_panel(panel.clone(), window, cx);
13422
13423 workspace
13424 .right_dock()
13425 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13426
13427 panel
13428 });
13429
13430 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13431 let item_a = cx.new(TestItem::new);
13432 let item_b = cx.new(TestItem::new);
13433 let item_a_id = item_a.entity_id();
13434 let item_b_id = item_b.entity_id();
13435
13436 pane.update_in(cx, |pane, window, cx| {
13437 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13438 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13439 });
13440
13441 pane.read_with(cx, |pane, _| {
13442 assert_eq!(pane.items_len(), 2);
13443 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13444 });
13445
13446 workspace.update_in(cx, |workspace, window, cx| {
13447 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13448 });
13449
13450 workspace.update_in(cx, |_, window, cx| {
13451 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13452 });
13453
13454 // Assert that the `pane::CloseActiveItem` action is handled at the
13455 // workspace level when one of the dock panels is focused and, in that
13456 // case, the center pane's active item is closed but the focus is not
13457 // moved.
13458 cx.dispatch_action(pane::CloseActiveItem::default());
13459 cx.run_until_parked();
13460
13461 pane.read_with(cx, |pane, _| {
13462 assert_eq!(pane.items_len(), 1);
13463 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13464 });
13465
13466 workspace.update_in(cx, |workspace, window, cx| {
13467 assert!(workspace.right_dock().read(cx).is_open());
13468 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13469 });
13470 }
13471
13472 #[gpui::test]
13473 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13474 init_test(cx);
13475 let fs = FakeFs::new(cx.executor());
13476
13477 let project_a = Project::test(fs.clone(), [], cx).await;
13478 let project_b = Project::test(fs, [], cx).await;
13479
13480 let multi_workspace_handle =
13481 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13482 cx.run_until_parked();
13483
13484 let workspace_a = multi_workspace_handle
13485 .read_with(cx, |mw, _| mw.workspace().clone())
13486 .unwrap();
13487
13488 let _workspace_b = multi_workspace_handle
13489 .update(cx, |mw, window, cx| {
13490 mw.test_add_workspace(project_b, window, cx)
13491 })
13492 .unwrap();
13493
13494 // Switch to workspace A
13495 multi_workspace_handle
13496 .update(cx, |mw, window, cx| {
13497 mw.activate_index(0, window, cx);
13498 })
13499 .unwrap();
13500
13501 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13502
13503 // Add a panel to workspace A's right dock and open the dock
13504 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13505 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13506 workspace.add_panel(panel.clone(), window, cx);
13507 workspace
13508 .right_dock()
13509 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13510 panel
13511 });
13512
13513 // Focus the panel through the workspace (matching existing test pattern)
13514 workspace_a.update_in(cx, |workspace, window, cx| {
13515 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13516 });
13517
13518 // Zoom the panel
13519 panel.update_in(cx, |panel, window, cx| {
13520 panel.set_zoomed(true, window, cx);
13521 });
13522
13523 // Verify the panel is zoomed and the dock is open
13524 workspace_a.update_in(cx, |workspace, window, cx| {
13525 assert!(
13526 workspace.right_dock().read(cx).is_open(),
13527 "dock should be open before switch"
13528 );
13529 assert!(
13530 panel.is_zoomed(window, cx),
13531 "panel should be zoomed before switch"
13532 );
13533 assert!(
13534 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13535 "panel should be focused before switch"
13536 );
13537 });
13538
13539 // Switch to workspace B
13540 multi_workspace_handle
13541 .update(cx, |mw, window, cx| {
13542 mw.activate_index(1, window, cx);
13543 })
13544 .unwrap();
13545 cx.run_until_parked();
13546
13547 // Switch back to workspace A
13548 multi_workspace_handle
13549 .update(cx, |mw, window, cx| {
13550 mw.activate_index(0, window, cx);
13551 })
13552 .unwrap();
13553 cx.run_until_parked();
13554
13555 // Verify the panel is still zoomed and the dock is still open
13556 workspace_a.update_in(cx, |workspace, window, cx| {
13557 assert!(
13558 workspace.right_dock().read(cx).is_open(),
13559 "dock should still be open after switching back"
13560 );
13561 assert!(
13562 panel.is_zoomed(window, cx),
13563 "panel should still be zoomed after switching back"
13564 );
13565 });
13566 }
13567
13568 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13569 pane.read(cx)
13570 .items()
13571 .flat_map(|item| {
13572 item.project_paths(cx)
13573 .into_iter()
13574 .map(|path| path.path.display(PathStyle::local()).into_owned())
13575 })
13576 .collect()
13577 }
13578
13579 pub fn init_test(cx: &mut TestAppContext) {
13580 cx.update(|cx| {
13581 let settings_store = SettingsStore::test(cx);
13582 cx.set_global(settings_store);
13583 theme::init(theme::LoadThemes::JustBase, cx);
13584 });
13585 }
13586
13587 #[gpui::test]
13588 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
13589 use settings::{ThemeName, ThemeSelection};
13590 use theme::SystemAppearance;
13591 use zed_actions::theme::ToggleMode;
13592
13593 init_test(cx);
13594
13595 let fs = FakeFs::new(cx.executor());
13596 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
13597
13598 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
13599 .await;
13600
13601 // Build a test project and workspace view so the test can invoke
13602 // the workspace action handler the same way the UI would.
13603 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
13604 let (workspace, cx) =
13605 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13606
13607 // Seed the settings file with a plain static light theme so the
13608 // first toggle always starts from a known persisted state.
13609 workspace.update_in(cx, |_workspace, _window, cx| {
13610 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
13611 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
13612 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
13613 });
13614 });
13615 cx.executor().advance_clock(Duration::from_millis(200));
13616 cx.run_until_parked();
13617
13618 // Confirm the initial persisted settings contain the static theme
13619 // we just wrote before any toggling happens.
13620 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13621 assert!(settings_text.contains(r#""theme": "One Light""#));
13622
13623 // Toggle once. This should migrate the persisted theme settings
13624 // into light/dark slots and enable system mode.
13625 workspace.update_in(cx, |workspace, window, cx| {
13626 workspace.toggle_theme_mode(&ToggleMode, window, cx);
13627 });
13628 cx.executor().advance_clock(Duration::from_millis(200));
13629 cx.run_until_parked();
13630
13631 // 1. Static -> Dynamic
13632 // this assertion checks theme changed from static to dynamic.
13633 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13634 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
13635 assert_eq!(
13636 parsed["theme"],
13637 serde_json::json!({
13638 "mode": "system",
13639 "light": "One Light",
13640 "dark": "One Dark"
13641 })
13642 );
13643
13644 // 2. Toggle again, suppose it will change the mode to light
13645 workspace.update_in(cx, |workspace, window, cx| {
13646 workspace.toggle_theme_mode(&ToggleMode, window, cx);
13647 });
13648 cx.executor().advance_clock(Duration::from_millis(200));
13649 cx.run_until_parked();
13650
13651 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13652 assert!(settings_text.contains(r#""mode": "light""#));
13653 }
13654
13655 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13656 let item = TestProjectItem::new(id, path, cx);
13657 item.update(cx, |item, _| {
13658 item.is_dirty = true;
13659 });
13660 item
13661 }
13662
13663 #[gpui::test]
13664 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13665 cx: &mut gpui::TestAppContext,
13666 ) {
13667 init_test(cx);
13668 let fs = FakeFs::new(cx.executor());
13669
13670 let project = Project::test(fs, [], cx).await;
13671 let (workspace, cx) =
13672 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13673
13674 let panel = workspace.update_in(cx, |workspace, window, cx| {
13675 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13676 workspace.add_panel(panel.clone(), window, cx);
13677 workspace
13678 .right_dock()
13679 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13680 panel
13681 });
13682
13683 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13684 pane.update_in(cx, |pane, window, cx| {
13685 let item = cx.new(TestItem::new);
13686 pane.add_item(Box::new(item), true, true, None, window, cx);
13687 });
13688
13689 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13690 // mirrors the real-world flow and avoids side effects from directly
13691 // focusing the panel while the center pane is active.
13692 workspace.update_in(cx, |workspace, window, cx| {
13693 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13694 });
13695
13696 panel.update_in(cx, |panel, window, cx| {
13697 panel.set_zoomed(true, window, cx);
13698 });
13699
13700 workspace.update_in(cx, |workspace, window, cx| {
13701 assert!(workspace.right_dock().read(cx).is_open());
13702 assert!(panel.is_zoomed(window, cx));
13703 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13704 });
13705
13706 // Simulate a spurious pane::Event::Focus on the center pane while the
13707 // panel still has focus. This mirrors what happens during macOS window
13708 // activation: the center pane fires a focus event even though actual
13709 // focus remains on the dock panel.
13710 pane.update_in(cx, |_, _, cx| {
13711 cx.emit(pane::Event::Focus);
13712 });
13713
13714 // The dock must remain open because the panel had focus at the time the
13715 // event was processed. Before the fix, dock_to_preserve was None for
13716 // panels that don't implement pane(), causing the dock to close.
13717 workspace.update_in(cx, |workspace, window, cx| {
13718 assert!(
13719 workspace.right_dock().read(cx).is_open(),
13720 "Dock should stay open when its zoomed panel (without pane()) still has focus"
13721 );
13722 assert!(panel.is_zoomed(window, cx));
13723 });
13724 }
13725}