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/// Workspace-local view of a remote participant's location.
7272#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7273pub enum ParticipantLocation {
7274 SharedProject { project_id: u64 },
7275 UnsharedProject,
7276 External,
7277}
7278
7279impl ParticipantLocation {
7280 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7281 match location
7282 .and_then(|l| l.variant)
7283 .context("participant location was not provided")?
7284 {
7285 proto::participant_location::Variant::SharedProject(project) => {
7286 Ok(Self::SharedProject {
7287 project_id: project.id,
7288 })
7289 }
7290 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7291 proto::participant_location::Variant::External(_) => Ok(Self::External),
7292 }
7293 }
7294}
7295/// Workspace-local view of a remote collaborator's state.
7296/// This is the subset of `call::RemoteParticipant` that workspace needs.
7297#[derive(Clone)]
7298pub struct RemoteCollaborator {
7299 pub user: Arc<User>,
7300 pub peer_id: PeerId,
7301 pub location: ParticipantLocation,
7302 pub participant_index: ParticipantIndex,
7303}
7304
7305pub enum ActiveCallEvent {
7306 ParticipantLocationChanged { participant_id: PeerId },
7307 RemoteVideoTracksChanged { participant_id: PeerId },
7308}
7309
7310fn leader_border_for_pane(
7311 follower_states: &HashMap<CollaboratorId, FollowerState>,
7312 pane: &Entity<Pane>,
7313 _: &Window,
7314 cx: &App,
7315) -> Option<Div> {
7316 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7317 if state.pane() == pane {
7318 Some((*leader_id, state))
7319 } else {
7320 None
7321 }
7322 })?;
7323
7324 let mut leader_color = match leader_id {
7325 CollaboratorId::PeerId(leader_peer_id) => {
7326 let leader = GlobalAnyActiveCall::try_global(cx)?
7327 .0
7328 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7329
7330 cx.theme()
7331 .players()
7332 .color_for_participant(leader.participant_index.0)
7333 .cursor
7334 }
7335 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7336 };
7337 leader_color.fade_out(0.3);
7338 Some(
7339 div()
7340 .absolute()
7341 .size_full()
7342 .left_0()
7343 .top_0()
7344 .border_2()
7345 .border_color(leader_color),
7346 )
7347}
7348
7349fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7350 ZED_WINDOW_POSITION
7351 .zip(*ZED_WINDOW_SIZE)
7352 .map(|(position, size)| Bounds {
7353 origin: position,
7354 size,
7355 })
7356}
7357
7358fn open_items(
7359 serialized_workspace: Option<SerializedWorkspace>,
7360 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7361 window: &mut Window,
7362 cx: &mut Context<Workspace>,
7363) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7364 let restored_items = serialized_workspace.map(|serialized_workspace| {
7365 Workspace::load_workspace(
7366 serialized_workspace,
7367 project_paths_to_open
7368 .iter()
7369 .map(|(_, project_path)| project_path)
7370 .cloned()
7371 .collect(),
7372 window,
7373 cx,
7374 )
7375 });
7376
7377 cx.spawn_in(window, async move |workspace, cx| {
7378 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7379
7380 if let Some(restored_items) = restored_items {
7381 let restored_items = restored_items.await?;
7382
7383 let restored_project_paths = restored_items
7384 .iter()
7385 .filter_map(|item| {
7386 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7387 .ok()
7388 .flatten()
7389 })
7390 .collect::<HashSet<_>>();
7391
7392 for restored_item in restored_items {
7393 opened_items.push(restored_item.map(Ok));
7394 }
7395
7396 project_paths_to_open
7397 .iter_mut()
7398 .for_each(|(_, project_path)| {
7399 if let Some(project_path_to_open) = project_path
7400 && restored_project_paths.contains(project_path_to_open)
7401 {
7402 *project_path = None;
7403 }
7404 });
7405 } else {
7406 for _ in 0..project_paths_to_open.len() {
7407 opened_items.push(None);
7408 }
7409 }
7410 assert!(opened_items.len() == project_paths_to_open.len());
7411
7412 let tasks =
7413 project_paths_to_open
7414 .into_iter()
7415 .enumerate()
7416 .map(|(ix, (abs_path, project_path))| {
7417 let workspace = workspace.clone();
7418 cx.spawn(async move |cx| {
7419 let file_project_path = project_path?;
7420 let abs_path_task = workspace.update(cx, |workspace, cx| {
7421 workspace.project().update(cx, |project, cx| {
7422 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7423 })
7424 });
7425
7426 // We only want to open file paths here. If one of the items
7427 // here is a directory, it was already opened further above
7428 // with a `find_or_create_worktree`.
7429 if let Ok(task) = abs_path_task
7430 && task.await.is_none_or(|p| p.is_file())
7431 {
7432 return Some((
7433 ix,
7434 workspace
7435 .update_in(cx, |workspace, window, cx| {
7436 workspace.open_path(
7437 file_project_path,
7438 None,
7439 true,
7440 window,
7441 cx,
7442 )
7443 })
7444 .log_err()?
7445 .await,
7446 ));
7447 }
7448 None
7449 })
7450 });
7451
7452 let tasks = tasks.collect::<Vec<_>>();
7453
7454 let tasks = futures::future::join_all(tasks);
7455 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7456 opened_items[ix] = Some(path_open_result);
7457 }
7458
7459 Ok(opened_items)
7460 })
7461}
7462
7463enum ActivateInDirectionTarget {
7464 Pane(Entity<Pane>),
7465 Dock(Entity<Dock>),
7466}
7467
7468fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7469 window
7470 .update(cx, |multi_workspace, _, cx| {
7471 let workspace = multi_workspace.workspace().clone();
7472 workspace.update(cx, |workspace, cx| {
7473 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7474 struct DatabaseFailedNotification;
7475
7476 workspace.show_notification(
7477 NotificationId::unique::<DatabaseFailedNotification>(),
7478 cx,
7479 |cx| {
7480 cx.new(|cx| {
7481 MessageNotification::new("Failed to load the database file.", cx)
7482 .primary_message("File an Issue")
7483 .primary_icon(IconName::Plus)
7484 .primary_on_click(|window, cx| {
7485 window.dispatch_action(Box::new(FileBugReport), cx)
7486 })
7487 })
7488 },
7489 );
7490 }
7491 });
7492 })
7493 .log_err();
7494}
7495
7496fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7497 if val == 0 {
7498 ThemeSettings::get_global(cx).ui_font_size(cx)
7499 } else {
7500 px(val as f32)
7501 }
7502}
7503
7504fn adjust_active_dock_size_by_px(
7505 px: Pixels,
7506 workspace: &mut Workspace,
7507 window: &mut Window,
7508 cx: &mut Context<Workspace>,
7509) {
7510 let Some(active_dock) = workspace
7511 .all_docks()
7512 .into_iter()
7513 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7514 else {
7515 return;
7516 };
7517 let dock = active_dock.read(cx);
7518 let Some(panel_size) = dock.active_panel_size(window, cx) else {
7519 return;
7520 };
7521 let dock_pos = dock.position();
7522 workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
7523}
7524
7525fn adjust_open_docks_size_by_px(
7526 px: Pixels,
7527 workspace: &mut Workspace,
7528 window: &mut Window,
7529 cx: &mut Context<Workspace>,
7530) {
7531 let docks = workspace
7532 .all_docks()
7533 .into_iter()
7534 .filter_map(|dock| {
7535 if dock.read(cx).is_open() {
7536 let dock = dock.read(cx);
7537 let panel_size = dock.active_panel_size(window, cx)?;
7538 let dock_pos = dock.position();
7539 Some((panel_size, dock_pos, px))
7540 } else {
7541 None
7542 }
7543 })
7544 .collect::<Vec<_>>();
7545
7546 docks
7547 .into_iter()
7548 .for_each(|(panel_size, dock_pos, offset)| {
7549 workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
7550 });
7551}
7552
7553impl Focusable for Workspace {
7554 fn focus_handle(&self, cx: &App) -> FocusHandle {
7555 self.active_pane.focus_handle(cx)
7556 }
7557}
7558
7559#[derive(Clone)]
7560struct DraggedDock(DockPosition);
7561
7562impl Render for DraggedDock {
7563 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7564 gpui::Empty
7565 }
7566}
7567
7568impl Render for Workspace {
7569 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7570 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7571 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7572 log::info!("Rendered first frame");
7573 }
7574
7575 let centered_layout = self.centered_layout
7576 && self.center.panes().len() == 1
7577 && self.active_item(cx).is_some();
7578 let render_padding = |size| {
7579 (size > 0.0).then(|| {
7580 div()
7581 .h_full()
7582 .w(relative(size))
7583 .bg(cx.theme().colors().editor_background)
7584 .border_color(cx.theme().colors().pane_group_border)
7585 })
7586 };
7587 let paddings = if centered_layout {
7588 let settings = WorkspaceSettings::get_global(cx).centered_layout;
7589 (
7590 render_padding(Self::adjust_padding(
7591 settings.left_padding.map(|padding| padding.0),
7592 )),
7593 render_padding(Self::adjust_padding(
7594 settings.right_padding.map(|padding| padding.0),
7595 )),
7596 )
7597 } else {
7598 (None, None)
7599 };
7600 let ui_font = theme::setup_ui_font(window, cx);
7601
7602 let theme = cx.theme().clone();
7603 let colors = theme.colors();
7604 let notification_entities = self
7605 .notifications
7606 .iter()
7607 .map(|(_, notification)| notification.entity_id())
7608 .collect::<Vec<_>>();
7609 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
7610
7611 div()
7612 .relative()
7613 .size_full()
7614 .flex()
7615 .flex_col()
7616 .font(ui_font)
7617 .gap_0()
7618 .justify_start()
7619 .items_start()
7620 .text_color(colors.text)
7621 .overflow_hidden()
7622 .children(self.titlebar_item.clone())
7623 .on_modifiers_changed(move |_, _, cx| {
7624 for &id in ¬ification_entities {
7625 cx.notify(id);
7626 }
7627 })
7628 .child(
7629 div()
7630 .size_full()
7631 .relative()
7632 .flex_1()
7633 .flex()
7634 .flex_col()
7635 .child(
7636 div()
7637 .id("workspace")
7638 .bg(colors.background)
7639 .relative()
7640 .flex_1()
7641 .w_full()
7642 .flex()
7643 .flex_col()
7644 .overflow_hidden()
7645 .border_t_1()
7646 .border_b_1()
7647 .border_color(colors.border)
7648 .child({
7649 let this = cx.entity();
7650 canvas(
7651 move |bounds, window, cx| {
7652 this.update(cx, |this, cx| {
7653 let bounds_changed = this.bounds != bounds;
7654 this.bounds = bounds;
7655
7656 if bounds_changed {
7657 this.left_dock.update(cx, |dock, cx| {
7658 dock.clamp_panel_size(
7659 bounds.size.width,
7660 window,
7661 cx,
7662 )
7663 });
7664
7665 this.right_dock.update(cx, |dock, cx| {
7666 dock.clamp_panel_size(
7667 bounds.size.width,
7668 window,
7669 cx,
7670 )
7671 });
7672
7673 this.bottom_dock.update(cx, |dock, cx| {
7674 dock.clamp_panel_size(
7675 bounds.size.height,
7676 window,
7677 cx,
7678 )
7679 });
7680 }
7681 })
7682 },
7683 |_, _, _, _| {},
7684 )
7685 .absolute()
7686 .size_full()
7687 })
7688 .when(self.zoomed.is_none(), |this| {
7689 this.on_drag_move(cx.listener(
7690 move |workspace,
7691 e: &DragMoveEvent<DraggedDock>,
7692 window,
7693 cx| {
7694 if workspace.previous_dock_drag_coordinates
7695 != Some(e.event.position)
7696 {
7697 workspace.previous_dock_drag_coordinates =
7698 Some(e.event.position);
7699
7700 match e.drag(cx).0 {
7701 DockPosition::Left => {
7702 workspace.resize_left_dock(
7703 e.event.position.x
7704 - workspace.bounds.left(),
7705 window,
7706 cx,
7707 );
7708 }
7709 DockPosition::Right => {
7710 workspace.resize_right_dock(
7711 workspace.bounds.right()
7712 - e.event.position.x,
7713 window,
7714 cx,
7715 );
7716 }
7717 DockPosition::Bottom => {
7718 workspace.resize_bottom_dock(
7719 workspace.bounds.bottom()
7720 - e.event.position.y,
7721 window,
7722 cx,
7723 );
7724 }
7725 };
7726 workspace.serialize_workspace(window, cx);
7727 }
7728 },
7729 ))
7730
7731 })
7732 .child({
7733 match bottom_dock_layout {
7734 BottomDockLayout::Full => div()
7735 .flex()
7736 .flex_col()
7737 .h_full()
7738 .child(
7739 div()
7740 .flex()
7741 .flex_row()
7742 .flex_1()
7743 .overflow_hidden()
7744 .children(self.render_dock(
7745 DockPosition::Left,
7746 &self.left_dock,
7747 window,
7748 cx,
7749 ))
7750
7751 .child(
7752 div()
7753 .flex()
7754 .flex_col()
7755 .flex_1()
7756 .overflow_hidden()
7757 .child(
7758 h_flex()
7759 .flex_1()
7760 .when_some(
7761 paddings.0,
7762 |this, p| {
7763 this.child(
7764 p.border_r_1(),
7765 )
7766 },
7767 )
7768 .child(self.center.render(
7769 self.zoomed.as_ref(),
7770 &PaneRenderContext {
7771 follower_states:
7772 &self.follower_states,
7773 active_call: self.active_call(),
7774 active_pane: &self.active_pane,
7775 app_state: &self.app_state,
7776 project: &self.project,
7777 workspace: &self.weak_self,
7778 },
7779 window,
7780 cx,
7781 ))
7782 .when_some(
7783 paddings.1,
7784 |this, p| {
7785 this.child(
7786 p.border_l_1(),
7787 )
7788 },
7789 ),
7790 ),
7791 )
7792
7793 .children(self.render_dock(
7794 DockPosition::Right,
7795 &self.right_dock,
7796 window,
7797 cx,
7798 )),
7799 )
7800 .child(div().w_full().children(self.render_dock(
7801 DockPosition::Bottom,
7802 &self.bottom_dock,
7803 window,
7804 cx
7805 ))),
7806
7807 BottomDockLayout::LeftAligned => div()
7808 .flex()
7809 .flex_row()
7810 .h_full()
7811 .child(
7812 div()
7813 .flex()
7814 .flex_col()
7815 .flex_1()
7816 .h_full()
7817 .child(
7818 div()
7819 .flex()
7820 .flex_row()
7821 .flex_1()
7822 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
7823
7824 .child(
7825 div()
7826 .flex()
7827 .flex_col()
7828 .flex_1()
7829 .overflow_hidden()
7830 .child(
7831 h_flex()
7832 .flex_1()
7833 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7834 .child(self.center.render(
7835 self.zoomed.as_ref(),
7836 &PaneRenderContext {
7837 follower_states:
7838 &self.follower_states,
7839 active_call: self.active_call(),
7840 active_pane: &self.active_pane,
7841 app_state: &self.app_state,
7842 project: &self.project,
7843 workspace: &self.weak_self,
7844 },
7845 window,
7846 cx,
7847 ))
7848 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7849 )
7850 )
7851
7852 )
7853 .child(
7854 div()
7855 .w_full()
7856 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7857 ),
7858 )
7859 .children(self.render_dock(
7860 DockPosition::Right,
7861 &self.right_dock,
7862 window,
7863 cx,
7864 )),
7865
7866 BottomDockLayout::RightAligned => div()
7867 .flex()
7868 .flex_row()
7869 .h_full()
7870 .children(self.render_dock(
7871 DockPosition::Left,
7872 &self.left_dock,
7873 window,
7874 cx,
7875 ))
7876
7877 .child(
7878 div()
7879 .flex()
7880 .flex_col()
7881 .flex_1()
7882 .h_full()
7883 .child(
7884 div()
7885 .flex()
7886 .flex_row()
7887 .flex_1()
7888 .child(
7889 div()
7890 .flex()
7891 .flex_col()
7892 .flex_1()
7893 .overflow_hidden()
7894 .child(
7895 h_flex()
7896 .flex_1()
7897 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7898 .child(self.center.render(
7899 self.zoomed.as_ref(),
7900 &PaneRenderContext {
7901 follower_states:
7902 &self.follower_states,
7903 active_call: self.active_call(),
7904 active_pane: &self.active_pane,
7905 app_state: &self.app_state,
7906 project: &self.project,
7907 workspace: &self.weak_self,
7908 },
7909 window,
7910 cx,
7911 ))
7912 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7913 )
7914 )
7915
7916 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
7917 )
7918 .child(
7919 div()
7920 .w_full()
7921 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7922 ),
7923 ),
7924
7925 BottomDockLayout::Contained => div()
7926 .flex()
7927 .flex_row()
7928 .h_full()
7929 .children(self.render_dock(
7930 DockPosition::Left,
7931 &self.left_dock,
7932 window,
7933 cx,
7934 ))
7935
7936 .child(
7937 div()
7938 .flex()
7939 .flex_col()
7940 .flex_1()
7941 .overflow_hidden()
7942 .child(
7943 h_flex()
7944 .flex_1()
7945 .when_some(paddings.0, |this, p| {
7946 this.child(p.border_r_1())
7947 })
7948 .child(self.center.render(
7949 self.zoomed.as_ref(),
7950 &PaneRenderContext {
7951 follower_states:
7952 &self.follower_states,
7953 active_call: self.active_call(),
7954 active_pane: &self.active_pane,
7955 app_state: &self.app_state,
7956 project: &self.project,
7957 workspace: &self.weak_self,
7958 },
7959 window,
7960 cx,
7961 ))
7962 .when_some(paddings.1, |this, p| {
7963 this.child(p.border_l_1())
7964 }),
7965 )
7966 .children(self.render_dock(
7967 DockPosition::Bottom,
7968 &self.bottom_dock,
7969 window,
7970 cx,
7971 )),
7972 )
7973
7974 .children(self.render_dock(
7975 DockPosition::Right,
7976 &self.right_dock,
7977 window,
7978 cx,
7979 )),
7980 }
7981 })
7982 .children(self.zoomed.as_ref().and_then(|view| {
7983 let zoomed_view = view.upgrade()?;
7984 let div = div()
7985 .occlude()
7986 .absolute()
7987 .overflow_hidden()
7988 .border_color(colors.border)
7989 .bg(colors.background)
7990 .child(zoomed_view)
7991 .inset_0()
7992 .shadow_lg();
7993
7994 if !WorkspaceSettings::get_global(cx).zoomed_padding {
7995 return Some(div);
7996 }
7997
7998 Some(match self.zoomed_position {
7999 Some(DockPosition::Left) => div.right_2().border_r_1(),
8000 Some(DockPosition::Right) => div.left_2().border_l_1(),
8001 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8002 None => {
8003 div.top_2().bottom_2().left_2().right_2().border_1()
8004 }
8005 })
8006 }))
8007 .children(self.render_notifications(window, cx)),
8008 )
8009 .when(self.status_bar_visible(cx), |parent| {
8010 parent.child(self.status_bar.clone())
8011 })
8012 .child(self.toast_layer.clone()),
8013 )
8014 }
8015}
8016
8017impl WorkspaceStore {
8018 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8019 Self {
8020 workspaces: Default::default(),
8021 _subscriptions: vec![
8022 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8023 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8024 ],
8025 client,
8026 }
8027 }
8028
8029 pub fn update_followers(
8030 &self,
8031 project_id: Option<u64>,
8032 update: proto::update_followers::Variant,
8033 cx: &App,
8034 ) -> Option<()> {
8035 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8036 let room_id = active_call.0.room_id(cx)?;
8037 self.client
8038 .send(proto::UpdateFollowers {
8039 room_id,
8040 project_id,
8041 variant: Some(update),
8042 })
8043 .log_err()
8044 }
8045
8046 pub async fn handle_follow(
8047 this: Entity<Self>,
8048 envelope: TypedEnvelope<proto::Follow>,
8049 mut cx: AsyncApp,
8050 ) -> Result<proto::FollowResponse> {
8051 this.update(&mut cx, |this, cx| {
8052 let follower = Follower {
8053 project_id: envelope.payload.project_id,
8054 peer_id: envelope.original_sender_id()?,
8055 };
8056
8057 let mut response = proto::FollowResponse::default();
8058
8059 this.workspaces.retain(|(window_handle, weak_workspace)| {
8060 let Some(workspace) = weak_workspace.upgrade() else {
8061 return false;
8062 };
8063 window_handle
8064 .update(cx, |_, window, cx| {
8065 workspace.update(cx, |workspace, cx| {
8066 let handler_response =
8067 workspace.handle_follow(follower.project_id, window, cx);
8068 if let Some(active_view) = handler_response.active_view
8069 && workspace.project.read(cx).remote_id() == follower.project_id
8070 {
8071 response.active_view = Some(active_view)
8072 }
8073 });
8074 })
8075 .is_ok()
8076 });
8077
8078 Ok(response)
8079 })
8080 }
8081
8082 async fn handle_update_followers(
8083 this: Entity<Self>,
8084 envelope: TypedEnvelope<proto::UpdateFollowers>,
8085 mut cx: AsyncApp,
8086 ) -> Result<()> {
8087 let leader_id = envelope.original_sender_id()?;
8088 let update = envelope.payload;
8089
8090 this.update(&mut cx, |this, cx| {
8091 this.workspaces.retain(|(window_handle, weak_workspace)| {
8092 let Some(workspace) = weak_workspace.upgrade() else {
8093 return false;
8094 };
8095 window_handle
8096 .update(cx, |_, window, cx| {
8097 workspace.update(cx, |workspace, cx| {
8098 let project_id = workspace.project.read(cx).remote_id();
8099 if update.project_id != project_id && update.project_id.is_some() {
8100 return;
8101 }
8102 workspace.handle_update_followers(
8103 leader_id,
8104 update.clone(),
8105 window,
8106 cx,
8107 );
8108 });
8109 })
8110 .is_ok()
8111 });
8112 Ok(())
8113 })
8114 }
8115
8116 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8117 self.workspaces.iter().map(|(_, weak)| weak)
8118 }
8119
8120 pub fn workspaces_with_windows(
8121 &self,
8122 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8123 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8124 }
8125}
8126
8127impl ViewId {
8128 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8129 Ok(Self {
8130 creator: message
8131 .creator
8132 .map(CollaboratorId::PeerId)
8133 .context("creator is missing")?,
8134 id: message.id,
8135 })
8136 }
8137
8138 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8139 if let CollaboratorId::PeerId(peer_id) = self.creator {
8140 Some(proto::ViewId {
8141 creator: Some(peer_id),
8142 id: self.id,
8143 })
8144 } else {
8145 None
8146 }
8147 }
8148}
8149
8150impl FollowerState {
8151 fn pane(&self) -> &Entity<Pane> {
8152 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8153 }
8154}
8155
8156pub trait WorkspaceHandle {
8157 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8158}
8159
8160impl WorkspaceHandle for Entity<Workspace> {
8161 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8162 self.read(cx)
8163 .worktrees(cx)
8164 .flat_map(|worktree| {
8165 let worktree_id = worktree.read(cx).id();
8166 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8167 worktree_id,
8168 path: f.path.clone(),
8169 })
8170 })
8171 .collect::<Vec<_>>()
8172 }
8173}
8174
8175pub async fn last_opened_workspace_location(
8176 fs: &dyn fs::Fs,
8177) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8178 DB.last_workspace(fs)
8179 .await
8180 .log_err()
8181 .flatten()
8182 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8183}
8184
8185pub async fn last_session_workspace_locations(
8186 last_session_id: &str,
8187 last_session_window_stack: Option<Vec<WindowId>>,
8188 fs: &dyn fs::Fs,
8189) -> Option<Vec<SessionWorkspace>> {
8190 DB.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8191 .await
8192 .log_err()
8193}
8194
8195pub struct MultiWorkspaceRestoreResult {
8196 pub window_handle: WindowHandle<MultiWorkspace>,
8197 pub errors: Vec<anyhow::Error>,
8198}
8199
8200pub async fn restore_multiworkspace(
8201 multi_workspace: SerializedMultiWorkspace,
8202 app_state: Arc<AppState>,
8203 cx: &mut AsyncApp,
8204) -> anyhow::Result<MultiWorkspaceRestoreResult> {
8205 let SerializedMultiWorkspace {
8206 workspaces,
8207 state,
8208 id: window_id,
8209 } = multi_workspace;
8210 let mut group_iter = workspaces.into_iter();
8211 let first = group_iter
8212 .next()
8213 .context("window group must not be empty")?;
8214
8215 let window_handle = if first.paths.is_empty() {
8216 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
8217 .await?
8218 } else {
8219 let OpenResult { window, .. } = cx
8220 .update(|cx| {
8221 Workspace::new_local(
8222 first.paths.paths().to_vec(),
8223 app_state.clone(),
8224 None,
8225 None,
8226 None,
8227 true,
8228 cx,
8229 )
8230 })
8231 .await?;
8232 window
8233 };
8234
8235 let mut errors = Vec::new();
8236
8237 for session_workspace in group_iter {
8238 let error = if session_workspace.paths.is_empty() {
8239 cx.update(|cx| {
8240 open_workspace_by_id(
8241 session_workspace.workspace_id,
8242 app_state.clone(),
8243 Some(window_handle),
8244 cx,
8245 )
8246 })
8247 .await
8248 .err()
8249 } else {
8250 cx.update(|cx| {
8251 Workspace::new_local(
8252 session_workspace.paths.paths().to_vec(),
8253 app_state.clone(),
8254 Some(window_handle),
8255 None,
8256 None,
8257 true,
8258 cx,
8259 )
8260 })
8261 .await
8262 .err()
8263 };
8264
8265 if let Some(error) = error {
8266 errors.push(error);
8267 }
8268 }
8269
8270 if let Some(target_id) = state.active_workspace_id {
8271 window_handle
8272 .update(cx, |multi_workspace, window, cx| {
8273 multi_workspace.set_database_id(window_id);
8274 let target_index = multi_workspace
8275 .workspaces()
8276 .iter()
8277 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8278 if let Some(index) = target_index {
8279 multi_workspace.activate_index(index, window, cx);
8280 } else if !multi_workspace.workspaces().is_empty() {
8281 multi_workspace.activate_index(0, window, cx);
8282 }
8283 })
8284 .ok();
8285 } else {
8286 window_handle
8287 .update(cx, |multi_workspace, window, cx| {
8288 if !multi_workspace.workspaces().is_empty() {
8289 multi_workspace.activate_index(0, window, cx);
8290 }
8291 })
8292 .ok();
8293 }
8294
8295 window_handle
8296 .update(cx, |_, window, _cx| {
8297 window.activate_window();
8298 })
8299 .ok();
8300
8301 Ok(MultiWorkspaceRestoreResult {
8302 window_handle,
8303 errors,
8304 })
8305}
8306
8307actions!(
8308 collab,
8309 [
8310 /// Opens the channel notes for the current call.
8311 ///
8312 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8313 /// channel in the collab panel.
8314 ///
8315 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8316 /// can be copied via "Copy link to section" in the context menu of the channel notes
8317 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8318 OpenChannelNotes,
8319 /// Mutes your microphone.
8320 Mute,
8321 /// Deafens yourself (mute both microphone and speakers).
8322 Deafen,
8323 /// Leaves the current call.
8324 LeaveCall,
8325 /// Shares the current project with collaborators.
8326 ShareProject,
8327 /// Shares your screen with collaborators.
8328 ScreenShare,
8329 /// Copies the current room name and session id for debugging purposes.
8330 CopyRoomId,
8331 ]
8332);
8333actions!(
8334 zed,
8335 [
8336 /// Opens the Zed log file.
8337 OpenLog,
8338 /// Reveals the Zed log file in the system file manager.
8339 RevealLogInFileManager
8340 ]
8341);
8342
8343async fn join_channel_internal(
8344 channel_id: ChannelId,
8345 app_state: &Arc<AppState>,
8346 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8347 requesting_workspace: Option<WeakEntity<Workspace>>,
8348 active_call: &dyn AnyActiveCall,
8349 cx: &mut AsyncApp,
8350) -> Result<bool> {
8351 let (should_prompt, already_in_channel) = cx.update(|cx| {
8352 if !active_call.is_in_room(cx) {
8353 return (false, false);
8354 }
8355
8356 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8357 let should_prompt = active_call.is_sharing_project(cx)
8358 && active_call.has_remote_participants(cx)
8359 && !already_in_channel;
8360 (should_prompt, already_in_channel)
8361 });
8362
8363 if already_in_channel {
8364 let task = cx.update(|cx| {
8365 if let Some((project, host)) = active_call.most_active_project(cx) {
8366 Some(join_in_room_project(project, host, app_state.clone(), cx))
8367 } else {
8368 None
8369 }
8370 });
8371 if let Some(task) = task {
8372 task.await?;
8373 }
8374 return anyhow::Ok(true);
8375 }
8376
8377 if should_prompt {
8378 if let Some(multi_workspace) = requesting_window {
8379 let answer = multi_workspace
8380 .update(cx, |_, window, cx| {
8381 window.prompt(
8382 PromptLevel::Warning,
8383 "Do you want to switch channels?",
8384 Some("Leaving this call will unshare your current project."),
8385 &["Yes, Join Channel", "Cancel"],
8386 cx,
8387 )
8388 })?
8389 .await;
8390
8391 if answer == Ok(1) {
8392 return Ok(false);
8393 }
8394 } else {
8395 return Ok(false);
8396 }
8397 }
8398
8399 let client = cx.update(|cx| active_call.client(cx));
8400
8401 let mut client_status = client.status();
8402
8403 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8404 'outer: loop {
8405 let Some(status) = client_status.recv().await else {
8406 anyhow::bail!("error connecting");
8407 };
8408
8409 match status {
8410 Status::Connecting
8411 | Status::Authenticating
8412 | Status::Authenticated
8413 | Status::Reconnecting
8414 | Status::Reauthenticating
8415 | Status::Reauthenticated => continue,
8416 Status::Connected { .. } => break 'outer,
8417 Status::SignedOut | Status::AuthenticationError => {
8418 return Err(ErrorCode::SignedOut.into());
8419 }
8420 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8421 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8422 return Err(ErrorCode::Disconnected.into());
8423 }
8424 }
8425 }
8426
8427 let joined = cx
8428 .update(|cx| active_call.join_channel(channel_id, cx))
8429 .await?;
8430
8431 if !joined {
8432 return anyhow::Ok(true);
8433 }
8434
8435 cx.update(|cx| active_call.room_update_completed(cx)).await;
8436
8437 let task = cx.update(|cx| {
8438 if let Some((project, host)) = active_call.most_active_project(cx) {
8439 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8440 }
8441
8442 // If you are the first to join a channel, see if you should share your project.
8443 if !active_call.has_remote_participants(cx)
8444 && !active_call.local_participant_is_guest(cx)
8445 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8446 {
8447 let project = workspace.update(cx, |workspace, cx| {
8448 let project = workspace.project.read(cx);
8449
8450 if !active_call.share_on_join(cx) {
8451 return None;
8452 }
8453
8454 if (project.is_local() || project.is_via_remote_server())
8455 && project.visible_worktrees(cx).any(|tree| {
8456 tree.read(cx)
8457 .root_entry()
8458 .is_some_and(|entry| entry.is_dir())
8459 })
8460 {
8461 Some(workspace.project.clone())
8462 } else {
8463 None
8464 }
8465 });
8466 if let Some(project) = project {
8467 let share_task = active_call.share_project(project, cx);
8468 return Some(cx.spawn(async move |_cx| -> Result<()> {
8469 share_task.await?;
8470 Ok(())
8471 }));
8472 }
8473 }
8474
8475 None
8476 });
8477 if let Some(task) = task {
8478 task.await?;
8479 return anyhow::Ok(true);
8480 }
8481 anyhow::Ok(false)
8482}
8483
8484pub fn join_channel(
8485 channel_id: ChannelId,
8486 app_state: Arc<AppState>,
8487 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8488 requesting_workspace: Option<WeakEntity<Workspace>>,
8489 cx: &mut App,
8490) -> Task<Result<()>> {
8491 let active_call = GlobalAnyActiveCall::global(cx).clone();
8492 cx.spawn(async move |cx| {
8493 let result = join_channel_internal(
8494 channel_id,
8495 &app_state,
8496 requesting_window,
8497 requesting_workspace,
8498 &*active_call.0,
8499 cx,
8500 )
8501 .await;
8502
8503 // join channel succeeded, and opened a window
8504 if matches!(result, Ok(true)) {
8505 return anyhow::Ok(());
8506 }
8507
8508 // find an existing workspace to focus and show call controls
8509 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8510 if active_window.is_none() {
8511 // no open workspaces, make one to show the error in (blergh)
8512 let OpenResult {
8513 window: window_handle,
8514 ..
8515 } = cx
8516 .update(|cx| {
8517 Workspace::new_local(
8518 vec![],
8519 app_state.clone(),
8520 requesting_window,
8521 None,
8522 None,
8523 true,
8524 cx,
8525 )
8526 })
8527 .await?;
8528
8529 window_handle
8530 .update(cx, |_, window, _cx| {
8531 window.activate_window();
8532 })
8533 .ok();
8534
8535 if result.is_ok() {
8536 cx.update(|cx| {
8537 cx.dispatch_action(&OpenChannelNotes);
8538 });
8539 }
8540
8541 active_window = Some(window_handle);
8542 }
8543
8544 if let Err(err) = result {
8545 log::error!("failed to join channel: {}", err);
8546 if let Some(active_window) = active_window {
8547 active_window
8548 .update(cx, |_, window, cx| {
8549 let detail: SharedString = match err.error_code() {
8550 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8551 ErrorCode::UpgradeRequired => concat!(
8552 "Your are running an unsupported version of Zed. ",
8553 "Please update to continue."
8554 )
8555 .into(),
8556 ErrorCode::NoSuchChannel => concat!(
8557 "No matching channel was found. ",
8558 "Please check the link and try again."
8559 )
8560 .into(),
8561 ErrorCode::Forbidden => concat!(
8562 "This channel is private, and you do not have access. ",
8563 "Please ask someone to add you and try again."
8564 )
8565 .into(),
8566 ErrorCode::Disconnected => {
8567 "Please check your internet connection and try again.".into()
8568 }
8569 _ => format!("{}\n\nPlease try again.", err).into(),
8570 };
8571 window.prompt(
8572 PromptLevel::Critical,
8573 "Failed to join channel",
8574 Some(&detail),
8575 &["Ok"],
8576 cx,
8577 )
8578 })?
8579 .await
8580 .ok();
8581 }
8582 }
8583
8584 // return ok, we showed the error to the user.
8585 anyhow::Ok(())
8586 })
8587}
8588
8589pub async fn get_any_active_multi_workspace(
8590 app_state: Arc<AppState>,
8591 mut cx: AsyncApp,
8592) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8593 // find an existing workspace to focus and show call controls
8594 let active_window = activate_any_workspace_window(&mut cx);
8595 if active_window.is_none() {
8596 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
8597 .await?;
8598 }
8599 activate_any_workspace_window(&mut cx).context("could not open zed")
8600}
8601
8602fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
8603 cx.update(|cx| {
8604 if let Some(workspace_window) = cx
8605 .active_window()
8606 .and_then(|window| window.downcast::<MultiWorkspace>())
8607 {
8608 return Some(workspace_window);
8609 }
8610
8611 for window in cx.windows() {
8612 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
8613 workspace_window
8614 .update(cx, |_, window, _| window.activate_window())
8615 .ok();
8616 return Some(workspace_window);
8617 }
8618 }
8619 None
8620 })
8621}
8622
8623pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
8624 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
8625}
8626
8627pub fn workspace_windows_for_location(
8628 serialized_location: &SerializedWorkspaceLocation,
8629 cx: &App,
8630) -> Vec<WindowHandle<MultiWorkspace>> {
8631 cx.windows()
8632 .into_iter()
8633 .filter_map(|window| window.downcast::<MultiWorkspace>())
8634 .filter(|multi_workspace| {
8635 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
8636 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
8637 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
8638 }
8639 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
8640 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
8641 a.distro_name == b.distro_name
8642 }
8643 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
8644 a.container_id == b.container_id
8645 }
8646 #[cfg(any(test, feature = "test-support"))]
8647 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
8648 a.id == b.id
8649 }
8650 _ => false,
8651 };
8652
8653 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
8654 multi_workspace.workspaces().iter().any(|workspace| {
8655 match workspace.read(cx).workspace_location(cx) {
8656 WorkspaceLocation::Location(location, _) => {
8657 match (&location, serialized_location) {
8658 (
8659 SerializedWorkspaceLocation::Local,
8660 SerializedWorkspaceLocation::Local,
8661 ) => true,
8662 (
8663 SerializedWorkspaceLocation::Remote(a),
8664 SerializedWorkspaceLocation::Remote(b),
8665 ) => same_host(a, b),
8666 _ => false,
8667 }
8668 }
8669 _ => false,
8670 }
8671 })
8672 })
8673 })
8674 .collect()
8675}
8676
8677pub async fn find_existing_workspace(
8678 abs_paths: &[PathBuf],
8679 open_options: &OpenOptions,
8680 location: &SerializedWorkspaceLocation,
8681 cx: &mut AsyncApp,
8682) -> (
8683 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
8684 OpenVisible,
8685) {
8686 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
8687 let mut open_visible = OpenVisible::All;
8688 let mut best_match = None;
8689
8690 if open_options.open_new_workspace != Some(true) {
8691 cx.update(|cx| {
8692 for window in workspace_windows_for_location(location, cx) {
8693 if let Ok(multi_workspace) = window.read(cx) {
8694 for workspace in multi_workspace.workspaces() {
8695 let project = workspace.read(cx).project.read(cx);
8696 let m = project.visibility_for_paths(
8697 abs_paths,
8698 open_options.open_new_workspace == None,
8699 cx,
8700 );
8701 if m > best_match {
8702 existing = Some((window, workspace.clone()));
8703 best_match = m;
8704 } else if best_match.is_none()
8705 && open_options.open_new_workspace == Some(false)
8706 {
8707 existing = Some((window, workspace.clone()))
8708 }
8709 }
8710 }
8711 }
8712 });
8713
8714 let all_paths_are_files = existing
8715 .as_ref()
8716 .and_then(|(_, target_workspace)| {
8717 cx.update(|cx| {
8718 let workspace = target_workspace.read(cx);
8719 let project = workspace.project.read(cx);
8720 let path_style = workspace.path_style(cx);
8721 Some(!abs_paths.iter().any(|path| {
8722 let path = util::paths::SanitizedPath::new(path);
8723 project.worktrees(cx).any(|worktree| {
8724 let worktree = worktree.read(cx);
8725 let abs_path = worktree.abs_path();
8726 path_style
8727 .strip_prefix(path.as_ref(), abs_path.as_ref())
8728 .and_then(|rel| worktree.entry_for_path(&rel))
8729 .is_some_and(|e| e.is_dir())
8730 })
8731 }))
8732 })
8733 })
8734 .unwrap_or(false);
8735
8736 if open_options.open_new_workspace.is_none()
8737 && existing.is_some()
8738 && open_options.wait
8739 && all_paths_are_files
8740 {
8741 cx.update(|cx| {
8742 let windows = workspace_windows_for_location(location, cx);
8743 let window = cx
8744 .active_window()
8745 .and_then(|window| window.downcast::<MultiWorkspace>())
8746 .filter(|window| windows.contains(window))
8747 .or_else(|| windows.into_iter().next());
8748 if let Some(window) = window {
8749 if let Ok(multi_workspace) = window.read(cx) {
8750 let active_workspace = multi_workspace.workspace().clone();
8751 existing = Some((window, active_workspace));
8752 open_visible = OpenVisible::None;
8753 }
8754 }
8755 });
8756 }
8757 }
8758 (existing, open_visible)
8759}
8760
8761#[derive(Default, Clone)]
8762pub struct OpenOptions {
8763 pub visible: Option<OpenVisible>,
8764 pub focus: Option<bool>,
8765 pub open_new_workspace: Option<bool>,
8766 pub wait: bool,
8767 pub replace_window: Option<WindowHandle<MultiWorkspace>>,
8768 pub env: Option<HashMap<String, String>>,
8769}
8770
8771/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
8772/// or [`Workspace::open_workspace_for_paths`].
8773pub struct OpenResult {
8774 pub window: WindowHandle<MultiWorkspace>,
8775 pub workspace: Entity<Workspace>,
8776 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
8777}
8778
8779/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
8780pub fn open_workspace_by_id(
8781 workspace_id: WorkspaceId,
8782 app_state: Arc<AppState>,
8783 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8784 cx: &mut App,
8785) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
8786 let project_handle = Project::local(
8787 app_state.client.clone(),
8788 app_state.node_runtime.clone(),
8789 app_state.user_store.clone(),
8790 app_state.languages.clone(),
8791 app_state.fs.clone(),
8792 None,
8793 project::LocalProjectFlags {
8794 init_worktree_trust: true,
8795 ..project::LocalProjectFlags::default()
8796 },
8797 cx,
8798 );
8799
8800 cx.spawn(async move |cx| {
8801 let serialized_workspace = persistence::DB
8802 .workspace_for_id(workspace_id)
8803 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
8804
8805 let centered_layout = serialized_workspace.centered_layout;
8806
8807 let (window, workspace) = if let Some(window) = requesting_window {
8808 let workspace = window.update(cx, |multi_workspace, window, cx| {
8809 let workspace = cx.new(|cx| {
8810 let mut workspace = Workspace::new(
8811 Some(workspace_id),
8812 project_handle.clone(),
8813 app_state.clone(),
8814 window,
8815 cx,
8816 );
8817 workspace.centered_layout = centered_layout;
8818 workspace
8819 });
8820 multi_workspace.add_workspace(workspace.clone(), cx);
8821 workspace
8822 })?;
8823 (window, workspace)
8824 } else {
8825 let window_bounds_override = window_bounds_env_override();
8826
8827 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
8828 (Some(WindowBounds::Windowed(bounds)), None)
8829 } else if let Some(display) = serialized_workspace.display
8830 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
8831 {
8832 (Some(bounds.0), Some(display))
8833 } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
8834 (Some(bounds), Some(display))
8835 } else {
8836 (None, None)
8837 };
8838
8839 let options = cx.update(|cx| {
8840 let mut options = (app_state.build_window_options)(display, cx);
8841 options.window_bounds = window_bounds;
8842 options
8843 });
8844
8845 let window = cx.open_window(options, {
8846 let app_state = app_state.clone();
8847 let project_handle = project_handle.clone();
8848 move |window, cx| {
8849 let workspace = cx.new(|cx| {
8850 let mut workspace = Workspace::new(
8851 Some(workspace_id),
8852 project_handle,
8853 app_state,
8854 window,
8855 cx,
8856 );
8857 workspace.centered_layout = centered_layout;
8858 workspace
8859 });
8860 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
8861 }
8862 })?;
8863
8864 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
8865 multi_workspace.workspace().clone()
8866 })?;
8867
8868 (window, workspace)
8869 };
8870
8871 notify_if_database_failed(window, cx);
8872
8873 // Restore items from the serialized workspace
8874 window
8875 .update(cx, |_, window, cx| {
8876 workspace.update(cx, |_workspace, cx| {
8877 open_items(Some(serialized_workspace), vec![], window, cx)
8878 })
8879 })?
8880 .await?;
8881
8882 window.update(cx, |_, window, cx| {
8883 workspace.update(cx, |workspace, cx| {
8884 workspace.serialize_workspace(window, cx);
8885 });
8886 })?;
8887
8888 Ok(window)
8889 })
8890}
8891
8892#[allow(clippy::type_complexity)]
8893pub fn open_paths(
8894 abs_paths: &[PathBuf],
8895 app_state: Arc<AppState>,
8896 open_options: OpenOptions,
8897 cx: &mut App,
8898) -> Task<anyhow::Result<OpenResult>> {
8899 let abs_paths = abs_paths.to_vec();
8900 #[cfg(target_os = "windows")]
8901 let wsl_path = abs_paths
8902 .iter()
8903 .find_map(|p| util::paths::WslPath::from_path(p));
8904
8905 cx.spawn(async move |cx| {
8906 let (mut existing, mut open_visible) = find_existing_workspace(
8907 &abs_paths,
8908 &open_options,
8909 &SerializedWorkspaceLocation::Local,
8910 cx,
8911 )
8912 .await;
8913
8914 // Fallback: if no workspace contains the paths and all paths are files,
8915 // prefer an existing local workspace window (active window first).
8916 if open_options.open_new_workspace.is_none() && existing.is_none() {
8917 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
8918 let all_metadatas = futures::future::join_all(all_paths)
8919 .await
8920 .into_iter()
8921 .filter_map(|result| result.ok().flatten())
8922 .collect::<Vec<_>>();
8923
8924 if all_metadatas.iter().all(|file| !file.is_dir) {
8925 cx.update(|cx| {
8926 let windows = workspace_windows_for_location(
8927 &SerializedWorkspaceLocation::Local,
8928 cx,
8929 );
8930 let window = cx
8931 .active_window()
8932 .and_then(|window| window.downcast::<MultiWorkspace>())
8933 .filter(|window| windows.contains(window))
8934 .or_else(|| windows.into_iter().next());
8935 if let Some(window) = window {
8936 if let Ok(multi_workspace) = window.read(cx) {
8937 let active_workspace = multi_workspace.workspace().clone();
8938 existing = Some((window, active_workspace));
8939 open_visible = OpenVisible::None;
8940 }
8941 }
8942 });
8943 }
8944 }
8945
8946 let result = if let Some((existing, target_workspace)) = existing {
8947 let open_task = existing
8948 .update(cx, |multi_workspace, window, cx| {
8949 window.activate_window();
8950 multi_workspace.activate(target_workspace.clone(), cx);
8951 target_workspace.update(cx, |workspace, cx| {
8952 workspace.open_paths(
8953 abs_paths,
8954 OpenOptions {
8955 visible: Some(open_visible),
8956 ..Default::default()
8957 },
8958 None,
8959 window,
8960 cx,
8961 )
8962 })
8963 })?
8964 .await;
8965
8966 _ = existing.update(cx, |multi_workspace, _, cx| {
8967 let workspace = multi_workspace.workspace().clone();
8968 workspace.update(cx, |workspace, cx| {
8969 for item in open_task.iter().flatten() {
8970 if let Err(e) = item {
8971 workspace.show_error(&e, cx);
8972 }
8973 }
8974 });
8975 });
8976
8977 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
8978 } else {
8979 let result = cx
8980 .update(move |cx| {
8981 Workspace::new_local(
8982 abs_paths,
8983 app_state.clone(),
8984 open_options.replace_window,
8985 open_options.env,
8986 None,
8987 true,
8988 cx,
8989 )
8990 })
8991 .await;
8992
8993 if let Ok(ref result) = result {
8994 result.window
8995 .update(cx, |_, window, _cx| {
8996 window.activate_window();
8997 })
8998 .log_err();
8999 }
9000
9001 result
9002 };
9003
9004 #[cfg(target_os = "windows")]
9005 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9006 && let Ok(ref result) = result
9007 {
9008 result.window
9009 .update(cx, move |multi_workspace, _window, cx| {
9010 struct OpenInWsl;
9011 let workspace = multi_workspace.workspace().clone();
9012 workspace.update(cx, |workspace, cx| {
9013 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9014 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9015 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9016 cx.new(move |cx| {
9017 MessageNotification::new(msg, cx)
9018 .primary_message("Open in WSL")
9019 .primary_icon(IconName::FolderOpen)
9020 .primary_on_click(move |window, cx| {
9021 window.dispatch_action(Box::new(remote::OpenWslPath {
9022 distro: remote::WslConnectionOptions {
9023 distro_name: distro.clone(),
9024 user: None,
9025 },
9026 paths: vec![path.clone().into()],
9027 }), cx)
9028 })
9029 })
9030 });
9031 });
9032 })
9033 .unwrap();
9034 };
9035 result
9036 })
9037}
9038
9039pub fn open_new(
9040 open_options: OpenOptions,
9041 app_state: Arc<AppState>,
9042 cx: &mut App,
9043 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9044) -> Task<anyhow::Result<()>> {
9045 let task = Workspace::new_local(
9046 Vec::new(),
9047 app_state,
9048 open_options.replace_window,
9049 open_options.env,
9050 Some(Box::new(init)),
9051 true,
9052 cx,
9053 );
9054 cx.spawn(async move |cx| {
9055 let OpenResult { window, .. } = task.await?;
9056 window
9057 .update(cx, |_, window, _cx| {
9058 window.activate_window();
9059 })
9060 .ok();
9061 Ok(())
9062 })
9063}
9064
9065pub fn create_and_open_local_file(
9066 path: &'static Path,
9067 window: &mut Window,
9068 cx: &mut Context<Workspace>,
9069 default_content: impl 'static + Send + FnOnce() -> Rope,
9070) -> Task<Result<Box<dyn ItemHandle>>> {
9071 cx.spawn_in(window, async move |workspace, cx| {
9072 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9073 if !fs.is_file(path).await {
9074 fs.create_file(path, Default::default()).await?;
9075 fs.save(path, &default_content(), Default::default())
9076 .await?;
9077 }
9078
9079 workspace
9080 .update_in(cx, |workspace, window, cx| {
9081 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9082 let path = workspace
9083 .project
9084 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9085 cx.spawn_in(window, async move |workspace, cx| {
9086 let path = path.await?;
9087 let mut items = workspace
9088 .update_in(cx, |workspace, window, cx| {
9089 workspace.open_paths(
9090 vec![path.to_path_buf()],
9091 OpenOptions {
9092 visible: Some(OpenVisible::None),
9093 ..Default::default()
9094 },
9095 None,
9096 window,
9097 cx,
9098 )
9099 })?
9100 .await;
9101 let item = items.pop().flatten();
9102 item.with_context(|| format!("path {path:?} is not a file"))?
9103 })
9104 })
9105 })?
9106 .await?
9107 .await
9108 })
9109}
9110
9111pub fn open_remote_project_with_new_connection(
9112 window: WindowHandle<MultiWorkspace>,
9113 remote_connection: Arc<dyn RemoteConnection>,
9114 cancel_rx: oneshot::Receiver<()>,
9115 delegate: Arc<dyn RemoteClientDelegate>,
9116 app_state: Arc<AppState>,
9117 paths: Vec<PathBuf>,
9118 cx: &mut App,
9119) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9120 cx.spawn(async move |cx| {
9121 let (workspace_id, serialized_workspace) =
9122 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9123 .await?;
9124
9125 let session = match cx
9126 .update(|cx| {
9127 remote::RemoteClient::new(
9128 ConnectionIdentifier::Workspace(workspace_id.0),
9129 remote_connection,
9130 cancel_rx,
9131 delegate,
9132 cx,
9133 )
9134 })
9135 .await?
9136 {
9137 Some(result) => result,
9138 None => return Ok(Vec::new()),
9139 };
9140
9141 let project = cx.update(|cx| {
9142 project::Project::remote(
9143 session,
9144 app_state.client.clone(),
9145 app_state.node_runtime.clone(),
9146 app_state.user_store.clone(),
9147 app_state.languages.clone(),
9148 app_state.fs.clone(),
9149 true,
9150 cx,
9151 )
9152 });
9153
9154 open_remote_project_inner(
9155 project,
9156 paths,
9157 workspace_id,
9158 serialized_workspace,
9159 app_state,
9160 window,
9161 cx,
9162 )
9163 .await
9164 })
9165}
9166
9167pub fn open_remote_project_with_existing_connection(
9168 connection_options: RemoteConnectionOptions,
9169 project: Entity<Project>,
9170 paths: Vec<PathBuf>,
9171 app_state: Arc<AppState>,
9172 window: WindowHandle<MultiWorkspace>,
9173 cx: &mut AsyncApp,
9174) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9175 cx.spawn(async move |cx| {
9176 let (workspace_id, serialized_workspace) =
9177 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9178
9179 open_remote_project_inner(
9180 project,
9181 paths,
9182 workspace_id,
9183 serialized_workspace,
9184 app_state,
9185 window,
9186 cx,
9187 )
9188 .await
9189 })
9190}
9191
9192async fn open_remote_project_inner(
9193 project: Entity<Project>,
9194 paths: Vec<PathBuf>,
9195 workspace_id: WorkspaceId,
9196 serialized_workspace: Option<SerializedWorkspace>,
9197 app_state: Arc<AppState>,
9198 window: WindowHandle<MultiWorkspace>,
9199 cx: &mut AsyncApp,
9200) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9201 let toolchains = DB.toolchains(workspace_id).await?;
9202 for (toolchain, worktree_path, path) in toolchains {
9203 project
9204 .update(cx, |this, cx| {
9205 let Some(worktree_id) =
9206 this.find_worktree(&worktree_path, cx)
9207 .and_then(|(worktree, rel_path)| {
9208 if rel_path.is_empty() {
9209 Some(worktree.read(cx).id())
9210 } else {
9211 None
9212 }
9213 })
9214 else {
9215 return Task::ready(None);
9216 };
9217
9218 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9219 })
9220 .await;
9221 }
9222 let mut project_paths_to_open = vec![];
9223 let mut project_path_errors = vec![];
9224
9225 for path in paths {
9226 let result = cx
9227 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9228 .await;
9229 match result {
9230 Ok((_, project_path)) => {
9231 project_paths_to_open.push((path.clone(), Some(project_path)));
9232 }
9233 Err(error) => {
9234 project_path_errors.push(error);
9235 }
9236 };
9237 }
9238
9239 if project_paths_to_open.is_empty() {
9240 return Err(project_path_errors.pop().context("no paths given")?);
9241 }
9242
9243 let workspace = window.update(cx, |multi_workspace, window, cx| {
9244 telemetry::event!("SSH Project Opened");
9245
9246 let new_workspace = cx.new(|cx| {
9247 let mut workspace =
9248 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9249 workspace.update_history(cx);
9250
9251 if let Some(ref serialized) = serialized_workspace {
9252 workspace.centered_layout = serialized.centered_layout;
9253 }
9254
9255 workspace
9256 });
9257
9258 multi_workspace.activate(new_workspace.clone(), cx);
9259 new_workspace
9260 })?;
9261
9262 let items = window
9263 .update(cx, |_, window, cx| {
9264 window.activate_window();
9265 workspace.update(cx, |_workspace, cx| {
9266 open_items(serialized_workspace, project_paths_to_open, window, cx)
9267 })
9268 })?
9269 .await?;
9270
9271 workspace.update(cx, |workspace, cx| {
9272 for error in project_path_errors {
9273 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9274 if let Some(path) = error.error_tag("path") {
9275 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9276 }
9277 } else {
9278 workspace.show_error(&error, cx)
9279 }
9280 }
9281 });
9282
9283 Ok(items.into_iter().map(|item| item?.ok()).collect())
9284}
9285
9286fn deserialize_remote_project(
9287 connection_options: RemoteConnectionOptions,
9288 paths: Vec<PathBuf>,
9289 cx: &AsyncApp,
9290) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9291 cx.background_spawn(async move {
9292 let remote_connection_id = persistence::DB
9293 .get_or_create_remote_connection(connection_options)
9294 .await?;
9295
9296 let serialized_workspace =
9297 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
9298
9299 let workspace_id = if let Some(workspace_id) =
9300 serialized_workspace.as_ref().map(|workspace| workspace.id)
9301 {
9302 workspace_id
9303 } else {
9304 persistence::DB.next_id().await?
9305 };
9306
9307 Ok((workspace_id, serialized_workspace))
9308 })
9309}
9310
9311pub fn join_in_room_project(
9312 project_id: u64,
9313 follow_user_id: u64,
9314 app_state: Arc<AppState>,
9315 cx: &mut App,
9316) -> Task<Result<()>> {
9317 let windows = cx.windows();
9318 cx.spawn(async move |cx| {
9319 let existing_window_and_workspace: Option<(
9320 WindowHandle<MultiWorkspace>,
9321 Entity<Workspace>,
9322 )> = windows.into_iter().find_map(|window_handle| {
9323 window_handle
9324 .downcast::<MultiWorkspace>()
9325 .and_then(|window_handle| {
9326 window_handle
9327 .update(cx, |multi_workspace, _window, cx| {
9328 for workspace in multi_workspace.workspaces() {
9329 if workspace.read(cx).project().read(cx).remote_id()
9330 == Some(project_id)
9331 {
9332 return Some((window_handle, workspace.clone()));
9333 }
9334 }
9335 None
9336 })
9337 .unwrap_or(None)
9338 })
9339 });
9340
9341 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9342 existing_window_and_workspace
9343 {
9344 existing_window
9345 .update(cx, |multi_workspace, _, cx| {
9346 multi_workspace.activate(target_workspace, cx);
9347 })
9348 .ok();
9349 existing_window
9350 } else {
9351 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9352 let project = cx
9353 .update(|cx| {
9354 active_call.0.join_project(
9355 project_id,
9356 app_state.languages.clone(),
9357 app_state.fs.clone(),
9358 cx,
9359 )
9360 })
9361 .await?;
9362
9363 let window_bounds_override = window_bounds_env_override();
9364 cx.update(|cx| {
9365 let mut options = (app_state.build_window_options)(None, cx);
9366 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9367 cx.open_window(options, |window, cx| {
9368 let workspace = cx.new(|cx| {
9369 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9370 });
9371 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9372 })
9373 })?
9374 };
9375
9376 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9377 cx.activate(true);
9378 window.activate_window();
9379
9380 // We set the active workspace above, so this is the correct workspace.
9381 let workspace = multi_workspace.workspace().clone();
9382 workspace.update(cx, |workspace, cx| {
9383 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9384 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9385 .or_else(|| {
9386 // If we couldn't follow the given user, follow the host instead.
9387 let collaborator = workspace
9388 .project()
9389 .read(cx)
9390 .collaborators()
9391 .values()
9392 .find(|collaborator| collaborator.is_host)?;
9393 Some(collaborator.peer_id)
9394 });
9395
9396 if let Some(follow_peer_id) = follow_peer_id {
9397 workspace.follow(follow_peer_id, window, cx);
9398 }
9399 });
9400 })?;
9401
9402 anyhow::Ok(())
9403 })
9404}
9405
9406pub fn reload(cx: &mut App) {
9407 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9408 let mut workspace_windows = cx
9409 .windows()
9410 .into_iter()
9411 .filter_map(|window| window.downcast::<MultiWorkspace>())
9412 .collect::<Vec<_>>();
9413
9414 // If multiple windows have unsaved changes, and need a save prompt,
9415 // prompt in the active window before switching to a different window.
9416 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9417
9418 let mut prompt = None;
9419 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9420 prompt = window
9421 .update(cx, |_, window, cx| {
9422 window.prompt(
9423 PromptLevel::Info,
9424 "Are you sure you want to restart?",
9425 None,
9426 &["Restart", "Cancel"],
9427 cx,
9428 )
9429 })
9430 .ok();
9431 }
9432
9433 cx.spawn(async move |cx| {
9434 if let Some(prompt) = prompt {
9435 let answer = prompt.await?;
9436 if answer != 0 {
9437 return anyhow::Ok(());
9438 }
9439 }
9440
9441 // If the user cancels any save prompt, then keep the app open.
9442 for window in workspace_windows {
9443 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9444 let workspace = multi_workspace.workspace().clone();
9445 workspace.update(cx, |workspace, cx| {
9446 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9447 })
9448 }) && !should_close.await?
9449 {
9450 return anyhow::Ok(());
9451 }
9452 }
9453 cx.update(|cx| cx.restart());
9454 anyhow::Ok(())
9455 })
9456 .detach_and_log_err(cx);
9457}
9458
9459fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9460 let mut parts = value.split(',');
9461 let x: usize = parts.next()?.parse().ok()?;
9462 let y: usize = parts.next()?.parse().ok()?;
9463 Some(point(px(x as f32), px(y as f32)))
9464}
9465
9466fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9467 let mut parts = value.split(',');
9468 let width: usize = parts.next()?.parse().ok()?;
9469 let height: usize = parts.next()?.parse().ok()?;
9470 Some(size(px(width as f32), px(height as f32)))
9471}
9472
9473/// Add client-side decorations (rounded corners, shadows, resize handling) when
9474/// appropriate.
9475///
9476/// The `border_radius_tiling` parameter allows overriding which corners get
9477/// rounded, independently of the actual window tiling state. This is used
9478/// specifically for the workspace switcher sidebar: when the sidebar is open,
9479/// we want square corners on the left (so the sidebar appears flush with the
9480/// window edge) but we still need the shadow padding for proper visual
9481/// appearance. Unlike actual window tiling, this only affects border radius -
9482/// not padding or shadows.
9483pub fn client_side_decorations(
9484 element: impl IntoElement,
9485 window: &mut Window,
9486 cx: &mut App,
9487 border_radius_tiling: Tiling,
9488) -> Stateful<Div> {
9489 const BORDER_SIZE: Pixels = px(1.0);
9490 let decorations = window.window_decorations();
9491 let tiling = match decorations {
9492 Decorations::Server => Tiling::default(),
9493 Decorations::Client { tiling } => tiling,
9494 };
9495
9496 match decorations {
9497 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9498 Decorations::Server => window.set_client_inset(px(0.0)),
9499 }
9500
9501 struct GlobalResizeEdge(ResizeEdge);
9502 impl Global for GlobalResizeEdge {}
9503
9504 div()
9505 .id("window-backdrop")
9506 .bg(transparent_black())
9507 .map(|div| match decorations {
9508 Decorations::Server => div,
9509 Decorations::Client { .. } => div
9510 .when(
9511 !(tiling.top
9512 || tiling.right
9513 || border_radius_tiling.top
9514 || border_radius_tiling.right),
9515 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9516 )
9517 .when(
9518 !(tiling.top
9519 || tiling.left
9520 || border_radius_tiling.top
9521 || border_radius_tiling.left),
9522 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9523 )
9524 .when(
9525 !(tiling.bottom
9526 || tiling.right
9527 || border_radius_tiling.bottom
9528 || border_radius_tiling.right),
9529 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9530 )
9531 .when(
9532 !(tiling.bottom
9533 || tiling.left
9534 || border_radius_tiling.bottom
9535 || border_radius_tiling.left),
9536 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9537 )
9538 .when(!tiling.top, |div| {
9539 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9540 })
9541 .when(!tiling.bottom, |div| {
9542 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9543 })
9544 .when(!tiling.left, |div| {
9545 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9546 })
9547 .when(!tiling.right, |div| {
9548 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9549 })
9550 .on_mouse_move(move |e, window, cx| {
9551 let size = window.window_bounds().get_bounds().size;
9552 let pos = e.position;
9553
9554 let new_edge =
9555 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9556
9557 let edge = cx.try_global::<GlobalResizeEdge>();
9558 if new_edge != edge.map(|edge| edge.0) {
9559 window
9560 .window_handle()
9561 .update(cx, |workspace, _, cx| {
9562 cx.notify(workspace.entity_id());
9563 })
9564 .ok();
9565 }
9566 })
9567 .on_mouse_down(MouseButton::Left, move |e, window, _| {
9568 let size = window.window_bounds().get_bounds().size;
9569 let pos = e.position;
9570
9571 let edge = match resize_edge(
9572 pos,
9573 theme::CLIENT_SIDE_DECORATION_SHADOW,
9574 size,
9575 tiling,
9576 ) {
9577 Some(value) => value,
9578 None => return,
9579 };
9580
9581 window.start_window_resize(edge);
9582 }),
9583 })
9584 .size_full()
9585 .child(
9586 div()
9587 .cursor(CursorStyle::Arrow)
9588 .map(|div| match decorations {
9589 Decorations::Server => div,
9590 Decorations::Client { .. } => div
9591 .border_color(cx.theme().colors().border)
9592 .when(
9593 !(tiling.top
9594 || tiling.right
9595 || border_radius_tiling.top
9596 || border_radius_tiling.right),
9597 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9598 )
9599 .when(
9600 !(tiling.top
9601 || tiling.left
9602 || border_radius_tiling.top
9603 || border_radius_tiling.left),
9604 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9605 )
9606 .when(
9607 !(tiling.bottom
9608 || tiling.right
9609 || border_radius_tiling.bottom
9610 || border_radius_tiling.right),
9611 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9612 )
9613 .when(
9614 !(tiling.bottom
9615 || tiling.left
9616 || border_radius_tiling.bottom
9617 || border_radius_tiling.left),
9618 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9619 )
9620 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
9621 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
9622 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
9623 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
9624 .when(!tiling.is_tiled(), |div| {
9625 div.shadow(vec![gpui::BoxShadow {
9626 color: Hsla {
9627 h: 0.,
9628 s: 0.,
9629 l: 0.,
9630 a: 0.4,
9631 },
9632 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
9633 spread_radius: px(0.),
9634 offset: point(px(0.0), px(0.0)),
9635 }])
9636 }),
9637 })
9638 .on_mouse_move(|_e, _, cx| {
9639 cx.stop_propagation();
9640 })
9641 .size_full()
9642 .child(element),
9643 )
9644 .map(|div| match decorations {
9645 Decorations::Server => div,
9646 Decorations::Client { tiling, .. } => div.child(
9647 canvas(
9648 |_bounds, window, _| {
9649 window.insert_hitbox(
9650 Bounds::new(
9651 point(px(0.0), px(0.0)),
9652 window.window_bounds().get_bounds().size,
9653 ),
9654 HitboxBehavior::Normal,
9655 )
9656 },
9657 move |_bounds, hitbox, window, cx| {
9658 let mouse = window.mouse_position();
9659 let size = window.window_bounds().get_bounds().size;
9660 let Some(edge) =
9661 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
9662 else {
9663 return;
9664 };
9665 cx.set_global(GlobalResizeEdge(edge));
9666 window.set_cursor_style(
9667 match edge {
9668 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
9669 ResizeEdge::Left | ResizeEdge::Right => {
9670 CursorStyle::ResizeLeftRight
9671 }
9672 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
9673 CursorStyle::ResizeUpLeftDownRight
9674 }
9675 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
9676 CursorStyle::ResizeUpRightDownLeft
9677 }
9678 },
9679 &hitbox,
9680 );
9681 },
9682 )
9683 .size_full()
9684 .absolute(),
9685 ),
9686 })
9687}
9688
9689fn resize_edge(
9690 pos: Point<Pixels>,
9691 shadow_size: Pixels,
9692 window_size: Size<Pixels>,
9693 tiling: Tiling,
9694) -> Option<ResizeEdge> {
9695 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
9696 if bounds.contains(&pos) {
9697 return None;
9698 }
9699
9700 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
9701 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
9702 if !tiling.top && top_left_bounds.contains(&pos) {
9703 return Some(ResizeEdge::TopLeft);
9704 }
9705
9706 let top_right_bounds = Bounds::new(
9707 Point::new(window_size.width - corner_size.width, px(0.)),
9708 corner_size,
9709 );
9710 if !tiling.top && top_right_bounds.contains(&pos) {
9711 return Some(ResizeEdge::TopRight);
9712 }
9713
9714 let bottom_left_bounds = Bounds::new(
9715 Point::new(px(0.), window_size.height - corner_size.height),
9716 corner_size,
9717 );
9718 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
9719 return Some(ResizeEdge::BottomLeft);
9720 }
9721
9722 let bottom_right_bounds = Bounds::new(
9723 Point::new(
9724 window_size.width - corner_size.width,
9725 window_size.height - corner_size.height,
9726 ),
9727 corner_size,
9728 );
9729 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
9730 return Some(ResizeEdge::BottomRight);
9731 }
9732
9733 if !tiling.top && pos.y < shadow_size {
9734 Some(ResizeEdge::Top)
9735 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
9736 Some(ResizeEdge::Bottom)
9737 } else if !tiling.left && pos.x < shadow_size {
9738 Some(ResizeEdge::Left)
9739 } else if !tiling.right && pos.x > window_size.width - shadow_size {
9740 Some(ResizeEdge::Right)
9741 } else {
9742 None
9743 }
9744}
9745
9746fn join_pane_into_active(
9747 active_pane: &Entity<Pane>,
9748 pane: &Entity<Pane>,
9749 window: &mut Window,
9750 cx: &mut App,
9751) {
9752 if pane == active_pane {
9753 } else if pane.read(cx).items_len() == 0 {
9754 pane.update(cx, |_, cx| {
9755 cx.emit(pane::Event::Remove {
9756 focus_on_pane: None,
9757 });
9758 })
9759 } else {
9760 move_all_items(pane, active_pane, window, cx);
9761 }
9762}
9763
9764fn move_all_items(
9765 from_pane: &Entity<Pane>,
9766 to_pane: &Entity<Pane>,
9767 window: &mut Window,
9768 cx: &mut App,
9769) {
9770 let destination_is_different = from_pane != to_pane;
9771 let mut moved_items = 0;
9772 for (item_ix, item_handle) in from_pane
9773 .read(cx)
9774 .items()
9775 .enumerate()
9776 .map(|(ix, item)| (ix, item.clone()))
9777 .collect::<Vec<_>>()
9778 {
9779 let ix = item_ix - moved_items;
9780 if destination_is_different {
9781 // Close item from previous pane
9782 from_pane.update(cx, |source, cx| {
9783 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
9784 });
9785 moved_items += 1;
9786 }
9787
9788 // This automatically removes duplicate items in the pane
9789 to_pane.update(cx, |destination, cx| {
9790 destination.add_item(item_handle, true, true, None, window, cx);
9791 window.focus(&destination.focus_handle(cx), cx)
9792 });
9793 }
9794}
9795
9796pub fn move_item(
9797 source: &Entity<Pane>,
9798 destination: &Entity<Pane>,
9799 item_id_to_move: EntityId,
9800 destination_index: usize,
9801 activate: bool,
9802 window: &mut Window,
9803 cx: &mut App,
9804) {
9805 let Some((item_ix, item_handle)) = source
9806 .read(cx)
9807 .items()
9808 .enumerate()
9809 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
9810 .map(|(ix, item)| (ix, item.clone()))
9811 else {
9812 // Tab was closed during drag
9813 return;
9814 };
9815
9816 if source != destination {
9817 // Close item from previous pane
9818 source.update(cx, |source, cx| {
9819 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
9820 });
9821 }
9822
9823 // This automatically removes duplicate items in the pane
9824 destination.update(cx, |destination, cx| {
9825 destination.add_item_inner(
9826 item_handle,
9827 activate,
9828 activate,
9829 activate,
9830 Some(destination_index),
9831 window,
9832 cx,
9833 );
9834 if activate {
9835 window.focus(&destination.focus_handle(cx), cx)
9836 }
9837 });
9838}
9839
9840pub fn move_active_item(
9841 source: &Entity<Pane>,
9842 destination: &Entity<Pane>,
9843 focus_destination: bool,
9844 close_if_empty: bool,
9845 window: &mut Window,
9846 cx: &mut App,
9847) {
9848 if source == destination {
9849 return;
9850 }
9851 let Some(active_item) = source.read(cx).active_item() else {
9852 return;
9853 };
9854 source.update(cx, |source_pane, cx| {
9855 let item_id = active_item.item_id();
9856 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
9857 destination.update(cx, |target_pane, cx| {
9858 target_pane.add_item(
9859 active_item,
9860 focus_destination,
9861 focus_destination,
9862 Some(target_pane.items_len()),
9863 window,
9864 cx,
9865 );
9866 });
9867 });
9868}
9869
9870pub fn clone_active_item(
9871 workspace_id: Option<WorkspaceId>,
9872 source: &Entity<Pane>,
9873 destination: &Entity<Pane>,
9874 focus_destination: bool,
9875 window: &mut Window,
9876 cx: &mut App,
9877) {
9878 if source == destination {
9879 return;
9880 }
9881 let Some(active_item) = source.read(cx).active_item() else {
9882 return;
9883 };
9884 if !active_item.can_split(cx) {
9885 return;
9886 }
9887 let destination = destination.downgrade();
9888 let task = active_item.clone_on_split(workspace_id, window, cx);
9889 window
9890 .spawn(cx, async move |cx| {
9891 let Some(clone) = task.await else {
9892 return;
9893 };
9894 destination
9895 .update_in(cx, |target_pane, window, cx| {
9896 target_pane.add_item(
9897 clone,
9898 focus_destination,
9899 focus_destination,
9900 Some(target_pane.items_len()),
9901 window,
9902 cx,
9903 );
9904 })
9905 .log_err();
9906 })
9907 .detach();
9908}
9909
9910#[derive(Debug)]
9911pub struct WorkspacePosition {
9912 pub window_bounds: Option<WindowBounds>,
9913 pub display: Option<Uuid>,
9914 pub centered_layout: bool,
9915}
9916
9917pub fn remote_workspace_position_from_db(
9918 connection_options: RemoteConnectionOptions,
9919 paths_to_open: &[PathBuf],
9920 cx: &App,
9921) -> Task<Result<WorkspacePosition>> {
9922 let paths = paths_to_open.to_vec();
9923
9924 cx.background_spawn(async move {
9925 let remote_connection_id = persistence::DB
9926 .get_or_create_remote_connection(connection_options)
9927 .await
9928 .context("fetching serialized ssh project")?;
9929 let serialized_workspace =
9930 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
9931
9932 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
9933 (Some(WindowBounds::Windowed(bounds)), None)
9934 } else {
9935 let restorable_bounds = serialized_workspace
9936 .as_ref()
9937 .and_then(|workspace| {
9938 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
9939 })
9940 .or_else(|| persistence::read_default_window_bounds());
9941
9942 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
9943 (Some(serialized_bounds), Some(serialized_display))
9944 } else {
9945 (None, None)
9946 }
9947 };
9948
9949 let centered_layout = serialized_workspace
9950 .as_ref()
9951 .map(|w| w.centered_layout)
9952 .unwrap_or(false);
9953
9954 Ok(WorkspacePosition {
9955 window_bounds,
9956 display,
9957 centered_layout,
9958 })
9959 })
9960}
9961
9962pub fn with_active_or_new_workspace(
9963 cx: &mut App,
9964 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
9965) {
9966 match cx
9967 .active_window()
9968 .and_then(|w| w.downcast::<MultiWorkspace>())
9969 {
9970 Some(multi_workspace) => {
9971 cx.defer(move |cx| {
9972 multi_workspace
9973 .update(cx, |multi_workspace, window, cx| {
9974 let workspace = multi_workspace.workspace().clone();
9975 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
9976 })
9977 .log_err();
9978 });
9979 }
9980 None => {
9981 let app_state = AppState::global(cx);
9982 if let Some(app_state) = app_state.upgrade() {
9983 open_new(
9984 OpenOptions::default(),
9985 app_state,
9986 cx,
9987 move |workspace, window, cx| f(workspace, window, cx),
9988 )
9989 .detach_and_log_err(cx);
9990 }
9991 }
9992 }
9993}
9994
9995#[cfg(test)]
9996mod tests {
9997 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
9998
9999 use super::*;
10000 use crate::{
10001 dock::{PanelEvent, test::TestPanel},
10002 item::{
10003 ItemBufferKind, ItemEvent,
10004 test::{TestItem, TestProjectItem},
10005 },
10006 };
10007 use fs::FakeFs;
10008 use gpui::{
10009 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10010 UpdateGlobal, VisualTestContext, px,
10011 };
10012 use project::{Project, ProjectEntryId};
10013 use serde_json::json;
10014 use settings::SettingsStore;
10015 use util::path;
10016 use util::rel_path::rel_path;
10017
10018 #[gpui::test]
10019 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10020 init_test(cx);
10021
10022 let fs = FakeFs::new(cx.executor());
10023 let project = Project::test(fs, [], cx).await;
10024 let (workspace, cx) =
10025 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10026
10027 // Adding an item with no ambiguity renders the tab without detail.
10028 let item1 = cx.new(|cx| {
10029 let mut item = TestItem::new(cx);
10030 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10031 item
10032 });
10033 workspace.update_in(cx, |workspace, window, cx| {
10034 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10035 });
10036 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10037
10038 // Adding an item that creates ambiguity increases the level of detail on
10039 // both tabs.
10040 let item2 = cx.new_window_entity(|_window, cx| {
10041 let mut item = TestItem::new(cx);
10042 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10043 item
10044 });
10045 workspace.update_in(cx, |workspace, window, cx| {
10046 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10047 });
10048 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10049 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10050
10051 // Adding an item that creates ambiguity increases the level of detail only
10052 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10053 // we stop at the highest detail available.
10054 let item3 = cx.new(|cx| {
10055 let mut item = TestItem::new(cx);
10056 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10057 item
10058 });
10059 workspace.update_in(cx, |workspace, window, cx| {
10060 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10061 });
10062 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10063 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10064 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10065 }
10066
10067 #[gpui::test]
10068 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10069 init_test(cx);
10070
10071 let fs = FakeFs::new(cx.executor());
10072 fs.insert_tree(
10073 "/root1",
10074 json!({
10075 "one.txt": "",
10076 "two.txt": "",
10077 }),
10078 )
10079 .await;
10080 fs.insert_tree(
10081 "/root2",
10082 json!({
10083 "three.txt": "",
10084 }),
10085 )
10086 .await;
10087
10088 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10089 let (workspace, cx) =
10090 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10091 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10092 let worktree_id = project.update(cx, |project, cx| {
10093 project.worktrees(cx).next().unwrap().read(cx).id()
10094 });
10095
10096 let item1 = cx.new(|cx| {
10097 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10098 });
10099 let item2 = cx.new(|cx| {
10100 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10101 });
10102
10103 // Add an item to an empty pane
10104 workspace.update_in(cx, |workspace, window, cx| {
10105 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10106 });
10107 project.update(cx, |project, cx| {
10108 assert_eq!(
10109 project.active_entry(),
10110 project
10111 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10112 .map(|e| e.id)
10113 );
10114 });
10115 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10116
10117 // Add a second item to a non-empty pane
10118 workspace.update_in(cx, |workspace, window, cx| {
10119 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10120 });
10121 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10122 project.update(cx, |project, cx| {
10123 assert_eq!(
10124 project.active_entry(),
10125 project
10126 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10127 .map(|e| e.id)
10128 );
10129 });
10130
10131 // Close the active item
10132 pane.update_in(cx, |pane, window, cx| {
10133 pane.close_active_item(&Default::default(), window, cx)
10134 })
10135 .await
10136 .unwrap();
10137 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10138 project.update(cx, |project, cx| {
10139 assert_eq!(
10140 project.active_entry(),
10141 project
10142 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10143 .map(|e| e.id)
10144 );
10145 });
10146
10147 // Add a project folder
10148 project
10149 .update(cx, |project, cx| {
10150 project.find_or_create_worktree("root2", true, cx)
10151 })
10152 .await
10153 .unwrap();
10154 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10155
10156 // Remove a project folder
10157 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10158 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10159 }
10160
10161 #[gpui::test]
10162 async fn test_close_window(cx: &mut TestAppContext) {
10163 init_test(cx);
10164
10165 let fs = FakeFs::new(cx.executor());
10166 fs.insert_tree("/root", json!({ "one": "" })).await;
10167
10168 let project = Project::test(fs, ["root".as_ref()], cx).await;
10169 let (workspace, cx) =
10170 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10171
10172 // When there are no dirty items, there's nothing to do.
10173 let item1 = cx.new(TestItem::new);
10174 workspace.update_in(cx, |w, window, cx| {
10175 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10176 });
10177 let task = workspace.update_in(cx, |w, window, cx| {
10178 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10179 });
10180 assert!(task.await.unwrap());
10181
10182 // When there are dirty untitled items, prompt to save each one. If the user
10183 // cancels any prompt, then abort.
10184 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10185 let item3 = cx.new(|cx| {
10186 TestItem::new(cx)
10187 .with_dirty(true)
10188 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10189 });
10190 workspace.update_in(cx, |w, window, cx| {
10191 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10192 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10193 });
10194 let task = workspace.update_in(cx, |w, window, cx| {
10195 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10196 });
10197 cx.executor().run_until_parked();
10198 cx.simulate_prompt_answer("Cancel"); // cancel save all
10199 cx.executor().run_until_parked();
10200 assert!(!cx.has_pending_prompt());
10201 assert!(!task.await.unwrap());
10202 }
10203
10204 #[gpui::test]
10205 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10206 init_test(cx);
10207
10208 let fs = FakeFs::new(cx.executor());
10209 fs.insert_tree("/root", json!({ "one": "" })).await;
10210
10211 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10212 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10213 let multi_workspace_handle =
10214 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10215 cx.run_until_parked();
10216
10217 let workspace_a = multi_workspace_handle
10218 .read_with(cx, |mw, _| mw.workspace().clone())
10219 .unwrap();
10220
10221 let workspace_b = multi_workspace_handle
10222 .update(cx, |mw, window, cx| {
10223 mw.test_add_workspace(project_b, window, cx)
10224 })
10225 .unwrap();
10226
10227 // Activate workspace A
10228 multi_workspace_handle
10229 .update(cx, |mw, window, cx| {
10230 mw.activate_index(0, window, cx);
10231 })
10232 .unwrap();
10233
10234 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10235
10236 // Workspace A has a clean item
10237 let item_a = cx.new(TestItem::new);
10238 workspace_a.update_in(cx, |w, window, cx| {
10239 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10240 });
10241
10242 // Workspace B has a dirty item
10243 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10244 workspace_b.update_in(cx, |w, window, cx| {
10245 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10246 });
10247
10248 // Verify workspace A is active
10249 multi_workspace_handle
10250 .read_with(cx, |mw, _| {
10251 assert_eq!(mw.active_workspace_index(), 0);
10252 })
10253 .unwrap();
10254
10255 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10256 multi_workspace_handle
10257 .update(cx, |mw, window, cx| {
10258 mw.close_window(&CloseWindow, window, cx);
10259 })
10260 .unwrap();
10261 cx.run_until_parked();
10262
10263 // Workspace B should now be active since it has dirty items that need attention
10264 multi_workspace_handle
10265 .read_with(cx, |mw, _| {
10266 assert_eq!(
10267 mw.active_workspace_index(),
10268 1,
10269 "workspace B should be activated when it prompts"
10270 );
10271 })
10272 .unwrap();
10273
10274 // User cancels the save prompt from workspace B
10275 cx.simulate_prompt_answer("Cancel");
10276 cx.run_until_parked();
10277
10278 // Window should still exist because workspace B's close was cancelled
10279 assert!(
10280 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10281 "window should still exist after cancelling one workspace's close"
10282 );
10283 }
10284
10285 #[gpui::test]
10286 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10287 init_test(cx);
10288
10289 // Register TestItem as a serializable item
10290 cx.update(|cx| {
10291 register_serializable_item::<TestItem>(cx);
10292 });
10293
10294 let fs = FakeFs::new(cx.executor());
10295 fs.insert_tree("/root", json!({ "one": "" })).await;
10296
10297 let project = Project::test(fs, ["root".as_ref()], cx).await;
10298 let (workspace, cx) =
10299 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10300
10301 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10302 let item1 = cx.new(|cx| {
10303 TestItem::new(cx)
10304 .with_dirty(true)
10305 .with_serialize(|| Some(Task::ready(Ok(()))))
10306 });
10307 let item2 = cx.new(|cx| {
10308 TestItem::new(cx)
10309 .with_dirty(true)
10310 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10311 .with_serialize(|| Some(Task::ready(Ok(()))))
10312 });
10313 workspace.update_in(cx, |w, window, cx| {
10314 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10315 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10316 });
10317 let task = workspace.update_in(cx, |w, window, cx| {
10318 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10319 });
10320 assert!(task.await.unwrap());
10321 }
10322
10323 #[gpui::test]
10324 async fn test_close_pane_items(cx: &mut TestAppContext) {
10325 init_test(cx);
10326
10327 let fs = FakeFs::new(cx.executor());
10328
10329 let project = Project::test(fs, None, cx).await;
10330 let (workspace, cx) =
10331 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10332
10333 let item1 = cx.new(|cx| {
10334 TestItem::new(cx)
10335 .with_dirty(true)
10336 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10337 });
10338 let item2 = cx.new(|cx| {
10339 TestItem::new(cx)
10340 .with_dirty(true)
10341 .with_conflict(true)
10342 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10343 });
10344 let item3 = cx.new(|cx| {
10345 TestItem::new(cx)
10346 .with_dirty(true)
10347 .with_conflict(true)
10348 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10349 });
10350 let item4 = cx.new(|cx| {
10351 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10352 let project_item = TestProjectItem::new_untitled(cx);
10353 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10354 project_item
10355 }])
10356 });
10357 let pane = workspace.update_in(cx, |workspace, window, cx| {
10358 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10359 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10360 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10361 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10362 workspace.active_pane().clone()
10363 });
10364
10365 let close_items = pane.update_in(cx, |pane, window, cx| {
10366 pane.activate_item(1, true, true, window, cx);
10367 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10368 let item1_id = item1.item_id();
10369 let item3_id = item3.item_id();
10370 let item4_id = item4.item_id();
10371 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10372 [item1_id, item3_id, item4_id].contains(&id)
10373 })
10374 });
10375 cx.executor().run_until_parked();
10376
10377 assert!(cx.has_pending_prompt());
10378 cx.simulate_prompt_answer("Save all");
10379
10380 cx.executor().run_until_parked();
10381
10382 // Item 1 is saved. There's a prompt to save item 3.
10383 pane.update(cx, |pane, cx| {
10384 assert_eq!(item1.read(cx).save_count, 1);
10385 assert_eq!(item1.read(cx).save_as_count, 0);
10386 assert_eq!(item1.read(cx).reload_count, 0);
10387 assert_eq!(pane.items_len(), 3);
10388 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10389 });
10390 assert!(cx.has_pending_prompt());
10391
10392 // Cancel saving item 3.
10393 cx.simulate_prompt_answer("Discard");
10394 cx.executor().run_until_parked();
10395
10396 // Item 3 is reloaded. There's a prompt to save item 4.
10397 pane.update(cx, |pane, cx| {
10398 assert_eq!(item3.read(cx).save_count, 0);
10399 assert_eq!(item3.read(cx).save_as_count, 0);
10400 assert_eq!(item3.read(cx).reload_count, 1);
10401 assert_eq!(pane.items_len(), 2);
10402 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10403 });
10404
10405 // There's a prompt for a path for item 4.
10406 cx.simulate_new_path_selection(|_| Some(Default::default()));
10407 close_items.await.unwrap();
10408
10409 // The requested items are closed.
10410 pane.update(cx, |pane, cx| {
10411 assert_eq!(item4.read(cx).save_count, 0);
10412 assert_eq!(item4.read(cx).save_as_count, 1);
10413 assert_eq!(item4.read(cx).reload_count, 0);
10414 assert_eq!(pane.items_len(), 1);
10415 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10416 });
10417 }
10418
10419 #[gpui::test]
10420 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10421 init_test(cx);
10422
10423 let fs = FakeFs::new(cx.executor());
10424 let project = Project::test(fs, [], cx).await;
10425 let (workspace, cx) =
10426 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10427
10428 // Create several workspace items with single project entries, and two
10429 // workspace items with multiple project entries.
10430 let single_entry_items = (0..=4)
10431 .map(|project_entry_id| {
10432 cx.new(|cx| {
10433 TestItem::new(cx)
10434 .with_dirty(true)
10435 .with_project_items(&[dirty_project_item(
10436 project_entry_id,
10437 &format!("{project_entry_id}.txt"),
10438 cx,
10439 )])
10440 })
10441 })
10442 .collect::<Vec<_>>();
10443 let item_2_3 = cx.new(|cx| {
10444 TestItem::new(cx)
10445 .with_dirty(true)
10446 .with_buffer_kind(ItemBufferKind::Multibuffer)
10447 .with_project_items(&[
10448 single_entry_items[2].read(cx).project_items[0].clone(),
10449 single_entry_items[3].read(cx).project_items[0].clone(),
10450 ])
10451 });
10452 let item_3_4 = cx.new(|cx| {
10453 TestItem::new(cx)
10454 .with_dirty(true)
10455 .with_buffer_kind(ItemBufferKind::Multibuffer)
10456 .with_project_items(&[
10457 single_entry_items[3].read(cx).project_items[0].clone(),
10458 single_entry_items[4].read(cx).project_items[0].clone(),
10459 ])
10460 });
10461
10462 // Create two panes that contain the following project entries:
10463 // left pane:
10464 // multi-entry items: (2, 3)
10465 // single-entry items: 0, 2, 3, 4
10466 // right pane:
10467 // single-entry items: 4, 1
10468 // multi-entry items: (3, 4)
10469 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10470 let left_pane = workspace.active_pane().clone();
10471 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10472 workspace.add_item_to_active_pane(
10473 single_entry_items[0].boxed_clone(),
10474 None,
10475 true,
10476 window,
10477 cx,
10478 );
10479 workspace.add_item_to_active_pane(
10480 single_entry_items[2].boxed_clone(),
10481 None,
10482 true,
10483 window,
10484 cx,
10485 );
10486 workspace.add_item_to_active_pane(
10487 single_entry_items[3].boxed_clone(),
10488 None,
10489 true,
10490 window,
10491 cx,
10492 );
10493 workspace.add_item_to_active_pane(
10494 single_entry_items[4].boxed_clone(),
10495 None,
10496 true,
10497 window,
10498 cx,
10499 );
10500
10501 let right_pane =
10502 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10503
10504 let boxed_clone = single_entry_items[1].boxed_clone();
10505 let right_pane = window.spawn(cx, async move |cx| {
10506 right_pane.await.inspect(|right_pane| {
10507 right_pane
10508 .update_in(cx, |pane, window, cx| {
10509 pane.add_item(boxed_clone, true, true, None, window, cx);
10510 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10511 })
10512 .unwrap();
10513 })
10514 });
10515
10516 (left_pane, right_pane)
10517 });
10518 let right_pane = right_pane.await.unwrap();
10519 cx.focus(&right_pane);
10520
10521 let close = right_pane.update_in(cx, |pane, window, cx| {
10522 pane.close_all_items(&CloseAllItems::default(), window, cx)
10523 .unwrap()
10524 });
10525 cx.executor().run_until_parked();
10526
10527 let msg = cx.pending_prompt().unwrap().0;
10528 assert!(msg.contains("1.txt"));
10529 assert!(!msg.contains("2.txt"));
10530 assert!(!msg.contains("3.txt"));
10531 assert!(!msg.contains("4.txt"));
10532
10533 // With best-effort close, cancelling item 1 keeps it open but items 4
10534 // and (3,4) still close since their entries exist in left pane.
10535 cx.simulate_prompt_answer("Cancel");
10536 close.await;
10537
10538 right_pane.read_with(cx, |pane, _| {
10539 assert_eq!(pane.items_len(), 1);
10540 });
10541
10542 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10543 left_pane
10544 .update_in(cx, |left_pane, window, cx| {
10545 left_pane.close_item_by_id(
10546 single_entry_items[3].entity_id(),
10547 SaveIntent::Skip,
10548 window,
10549 cx,
10550 )
10551 })
10552 .await
10553 .unwrap();
10554
10555 let close = left_pane.update_in(cx, |pane, window, cx| {
10556 pane.close_all_items(&CloseAllItems::default(), window, cx)
10557 .unwrap()
10558 });
10559 cx.executor().run_until_parked();
10560
10561 let details = cx.pending_prompt().unwrap().1;
10562 assert!(details.contains("0.txt"));
10563 assert!(details.contains("3.txt"));
10564 assert!(details.contains("4.txt"));
10565 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10566 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10567 // assert!(!details.contains("2.txt"));
10568
10569 cx.simulate_prompt_answer("Save all");
10570 cx.executor().run_until_parked();
10571 close.await;
10572
10573 left_pane.read_with(cx, |pane, _| {
10574 assert_eq!(pane.items_len(), 0);
10575 });
10576 }
10577
10578 #[gpui::test]
10579 async fn test_autosave(cx: &mut gpui::TestAppContext) {
10580 init_test(cx);
10581
10582 let fs = FakeFs::new(cx.executor());
10583 let project = Project::test(fs, [], cx).await;
10584 let (workspace, cx) =
10585 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10586 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10587
10588 let item = cx.new(|cx| {
10589 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10590 });
10591 let item_id = item.entity_id();
10592 workspace.update_in(cx, |workspace, window, cx| {
10593 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10594 });
10595
10596 // Autosave on window change.
10597 item.update(cx, |item, cx| {
10598 SettingsStore::update_global(cx, |settings, cx| {
10599 settings.update_user_settings(cx, |settings| {
10600 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10601 })
10602 });
10603 item.is_dirty = true;
10604 });
10605
10606 // Deactivating the window saves the file.
10607 cx.deactivate_window();
10608 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10609
10610 // Re-activating the window doesn't save the file.
10611 cx.update(|window, _| window.activate_window());
10612 cx.executor().run_until_parked();
10613 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10614
10615 // Autosave on focus change.
10616 item.update_in(cx, |item, window, cx| {
10617 cx.focus_self(window);
10618 SettingsStore::update_global(cx, |settings, cx| {
10619 settings.update_user_settings(cx, |settings| {
10620 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10621 })
10622 });
10623 item.is_dirty = true;
10624 });
10625 // Blurring the item saves the file.
10626 item.update_in(cx, |_, window, _| window.blur());
10627 cx.executor().run_until_parked();
10628 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10629
10630 // Deactivating the window still saves the file.
10631 item.update_in(cx, |item, window, cx| {
10632 cx.focus_self(window);
10633 item.is_dirty = true;
10634 });
10635 cx.deactivate_window();
10636 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10637
10638 // Autosave after delay.
10639 item.update(cx, |item, cx| {
10640 SettingsStore::update_global(cx, |settings, cx| {
10641 settings.update_user_settings(cx, |settings| {
10642 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10643 milliseconds: 500.into(),
10644 });
10645 })
10646 });
10647 item.is_dirty = true;
10648 cx.emit(ItemEvent::Edit);
10649 });
10650
10651 // Delay hasn't fully expired, so the file is still dirty and unsaved.
10652 cx.executor().advance_clock(Duration::from_millis(250));
10653 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10654
10655 // After delay expires, the file is saved.
10656 cx.executor().advance_clock(Duration::from_millis(250));
10657 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10658
10659 // Autosave after delay, should save earlier than delay if tab is closed
10660 item.update(cx, |item, cx| {
10661 item.is_dirty = true;
10662 cx.emit(ItemEvent::Edit);
10663 });
10664 cx.executor().advance_clock(Duration::from_millis(250));
10665 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10666
10667 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10668 pane.update_in(cx, |pane, window, cx| {
10669 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10670 })
10671 .await
10672 .unwrap();
10673 assert!(!cx.has_pending_prompt());
10674 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10675
10676 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10677 workspace.update_in(cx, |workspace, window, cx| {
10678 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10679 });
10680 item.update_in(cx, |item, _window, cx| {
10681 item.is_dirty = true;
10682 for project_item in &mut item.project_items {
10683 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10684 }
10685 });
10686 cx.run_until_parked();
10687 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10688
10689 // Autosave on focus change, ensuring closing the tab counts as such.
10690 item.update(cx, |item, cx| {
10691 SettingsStore::update_global(cx, |settings, cx| {
10692 settings.update_user_settings(cx, |settings| {
10693 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10694 })
10695 });
10696 item.is_dirty = true;
10697 for project_item in &mut item.project_items {
10698 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10699 }
10700 });
10701
10702 pane.update_in(cx, |pane, window, cx| {
10703 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10704 })
10705 .await
10706 .unwrap();
10707 assert!(!cx.has_pending_prompt());
10708 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10709
10710 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10711 workspace.update_in(cx, |workspace, window, cx| {
10712 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10713 });
10714 item.update_in(cx, |item, window, cx| {
10715 item.project_items[0].update(cx, |item, _| {
10716 item.entry_id = None;
10717 });
10718 item.is_dirty = true;
10719 window.blur();
10720 });
10721 cx.run_until_parked();
10722 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10723
10724 // Ensure autosave is prevented for deleted files also when closing the buffer.
10725 let _close_items = pane.update_in(cx, |pane, window, cx| {
10726 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10727 });
10728 cx.run_until_parked();
10729 assert!(cx.has_pending_prompt());
10730 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10731 }
10732
10733 #[gpui::test]
10734 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
10735 init_test(cx);
10736
10737 let fs = FakeFs::new(cx.executor());
10738 let project = Project::test(fs, [], cx).await;
10739 let (workspace, cx) =
10740 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10741
10742 // Create a multibuffer-like item with two child focus handles,
10743 // simulating individual buffer editors within a multibuffer.
10744 let item = cx.new(|cx| {
10745 TestItem::new(cx)
10746 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10747 .with_child_focus_handles(2, cx)
10748 });
10749 workspace.update_in(cx, |workspace, window, cx| {
10750 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10751 });
10752
10753 // Set autosave to OnFocusChange and focus the first child handle,
10754 // simulating the user's cursor being inside one of the multibuffer's excerpts.
10755 item.update_in(cx, |item, window, cx| {
10756 SettingsStore::update_global(cx, |settings, cx| {
10757 settings.update_user_settings(cx, |settings| {
10758 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10759 })
10760 });
10761 item.is_dirty = true;
10762 window.focus(&item.child_focus_handles[0], cx);
10763 });
10764 cx.executor().run_until_parked();
10765 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
10766
10767 // Moving focus from one child to another within the same item should
10768 // NOT trigger autosave — focus is still within the item's focus hierarchy.
10769 item.update_in(cx, |item, window, cx| {
10770 window.focus(&item.child_focus_handles[1], cx);
10771 });
10772 cx.executor().run_until_parked();
10773 item.read_with(cx, |item, _| {
10774 assert_eq!(
10775 item.save_count, 0,
10776 "Switching focus between children within the same item should not autosave"
10777 );
10778 });
10779
10780 // Blurring the item saves the file. This is the core regression scenario:
10781 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
10782 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
10783 // the leaf is always a child focus handle, so `on_blur` never detected
10784 // focus leaving the item.
10785 item.update_in(cx, |_, window, _| window.blur());
10786 cx.executor().run_until_parked();
10787 item.read_with(cx, |item, _| {
10788 assert_eq!(
10789 item.save_count, 1,
10790 "Blurring should trigger autosave when focus was on a child of the item"
10791 );
10792 });
10793
10794 // Deactivating the window should also trigger autosave when a child of
10795 // the multibuffer item currently owns focus.
10796 item.update_in(cx, |item, window, cx| {
10797 item.is_dirty = true;
10798 window.focus(&item.child_focus_handles[0], cx);
10799 });
10800 cx.executor().run_until_parked();
10801 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10802
10803 cx.deactivate_window();
10804 item.read_with(cx, |item, _| {
10805 assert_eq!(
10806 item.save_count, 2,
10807 "Deactivating window should trigger autosave when focus was on a child"
10808 );
10809 });
10810 }
10811
10812 #[gpui::test]
10813 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10814 init_test(cx);
10815
10816 let fs = FakeFs::new(cx.executor());
10817
10818 let project = Project::test(fs, [], cx).await;
10819 let (workspace, cx) =
10820 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10821
10822 let item = cx.new(|cx| {
10823 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10824 });
10825 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10826 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10827 let toolbar_notify_count = Rc::new(RefCell::new(0));
10828
10829 workspace.update_in(cx, |workspace, window, cx| {
10830 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10831 let toolbar_notification_count = toolbar_notify_count.clone();
10832 cx.observe_in(&toolbar, window, move |_, _, _, _| {
10833 *toolbar_notification_count.borrow_mut() += 1
10834 })
10835 .detach();
10836 });
10837
10838 pane.read_with(cx, |pane, _| {
10839 assert!(!pane.can_navigate_backward());
10840 assert!(!pane.can_navigate_forward());
10841 });
10842
10843 item.update_in(cx, |item, _, cx| {
10844 item.set_state("one".to_string(), cx);
10845 });
10846
10847 // Toolbar must be notified to re-render the navigation buttons
10848 assert_eq!(*toolbar_notify_count.borrow(), 1);
10849
10850 pane.read_with(cx, |pane, _| {
10851 assert!(pane.can_navigate_backward());
10852 assert!(!pane.can_navigate_forward());
10853 });
10854
10855 workspace
10856 .update_in(cx, |workspace, window, cx| {
10857 workspace.go_back(pane.downgrade(), window, cx)
10858 })
10859 .await
10860 .unwrap();
10861
10862 assert_eq!(*toolbar_notify_count.borrow(), 2);
10863 pane.read_with(cx, |pane, _| {
10864 assert!(!pane.can_navigate_backward());
10865 assert!(pane.can_navigate_forward());
10866 });
10867 }
10868
10869 #[gpui::test]
10870 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
10871 init_test(cx);
10872 let fs = FakeFs::new(cx.executor());
10873 let project = Project::test(fs, [], cx).await;
10874 let (multi_workspace, cx) =
10875 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
10876 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
10877
10878 workspace.update_in(cx, |workspace, window, cx| {
10879 let first_item = cx.new(|cx| {
10880 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10881 });
10882 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
10883 workspace.split_pane(
10884 workspace.active_pane().clone(),
10885 SplitDirection::Right,
10886 window,
10887 cx,
10888 );
10889 workspace.split_pane(
10890 workspace.active_pane().clone(),
10891 SplitDirection::Right,
10892 window,
10893 cx,
10894 );
10895 });
10896
10897 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
10898 let panes = workspace.center.panes();
10899 assert!(panes.len() >= 2);
10900 (
10901 panes.first().expect("at least one pane").entity_id(),
10902 panes.last().expect("at least one pane").entity_id(),
10903 )
10904 });
10905
10906 workspace.update_in(cx, |workspace, window, cx| {
10907 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
10908 });
10909 workspace.update(cx, |workspace, _| {
10910 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
10911 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
10912 });
10913
10914 cx.dispatch_action(ActivateLastPane);
10915
10916 workspace.update(cx, |workspace, _| {
10917 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
10918 });
10919 }
10920
10921 #[gpui::test]
10922 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
10923 init_test(cx);
10924 let fs = FakeFs::new(cx.executor());
10925
10926 let project = Project::test(fs, [], cx).await;
10927 let (workspace, cx) =
10928 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10929
10930 let panel = workspace.update_in(cx, |workspace, window, cx| {
10931 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10932 workspace.add_panel(panel.clone(), window, cx);
10933
10934 workspace
10935 .right_dock()
10936 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10937
10938 panel
10939 });
10940
10941 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10942 pane.update_in(cx, |pane, window, cx| {
10943 let item = cx.new(TestItem::new);
10944 pane.add_item(Box::new(item), true, true, None, window, cx);
10945 });
10946
10947 // Transfer focus from center to panel
10948 workspace.update_in(cx, |workspace, window, cx| {
10949 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10950 });
10951
10952 workspace.update_in(cx, |workspace, window, cx| {
10953 assert!(workspace.right_dock().read(cx).is_open());
10954 assert!(!panel.is_zoomed(window, cx));
10955 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10956 });
10957
10958 // Transfer focus from panel to center
10959 workspace.update_in(cx, |workspace, window, cx| {
10960 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10961 });
10962
10963 workspace.update_in(cx, |workspace, window, cx| {
10964 assert!(workspace.right_dock().read(cx).is_open());
10965 assert!(!panel.is_zoomed(window, cx));
10966 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10967 });
10968
10969 // Close the dock
10970 workspace.update_in(cx, |workspace, window, cx| {
10971 workspace.toggle_dock(DockPosition::Right, window, cx);
10972 });
10973
10974 workspace.update_in(cx, |workspace, window, cx| {
10975 assert!(!workspace.right_dock().read(cx).is_open());
10976 assert!(!panel.is_zoomed(window, cx));
10977 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10978 });
10979
10980 // Open the dock
10981 workspace.update_in(cx, |workspace, window, cx| {
10982 workspace.toggle_dock(DockPosition::Right, window, cx);
10983 });
10984
10985 workspace.update_in(cx, |workspace, window, cx| {
10986 assert!(workspace.right_dock().read(cx).is_open());
10987 assert!(!panel.is_zoomed(window, cx));
10988 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10989 });
10990
10991 // Focus and zoom panel
10992 panel.update_in(cx, |panel, window, cx| {
10993 cx.focus_self(window);
10994 panel.set_zoomed(true, window, cx)
10995 });
10996
10997 workspace.update_in(cx, |workspace, window, cx| {
10998 assert!(workspace.right_dock().read(cx).is_open());
10999 assert!(panel.is_zoomed(window, cx));
11000 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11001 });
11002
11003 // Transfer focus to the center closes the dock
11004 workspace.update_in(cx, |workspace, window, cx| {
11005 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11006 });
11007
11008 workspace.update_in(cx, |workspace, window, cx| {
11009 assert!(!workspace.right_dock().read(cx).is_open());
11010 assert!(panel.is_zoomed(window, cx));
11011 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11012 });
11013
11014 // Transferring focus back to the panel keeps it zoomed
11015 workspace.update_in(cx, |workspace, window, cx| {
11016 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11017 });
11018
11019 workspace.update_in(cx, |workspace, window, cx| {
11020 assert!(workspace.right_dock().read(cx).is_open());
11021 assert!(panel.is_zoomed(window, cx));
11022 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11023 });
11024
11025 // Close the dock while it is zoomed
11026 workspace.update_in(cx, |workspace, window, cx| {
11027 workspace.toggle_dock(DockPosition::Right, window, cx)
11028 });
11029
11030 workspace.update_in(cx, |workspace, window, cx| {
11031 assert!(!workspace.right_dock().read(cx).is_open());
11032 assert!(panel.is_zoomed(window, cx));
11033 assert!(workspace.zoomed.is_none());
11034 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11035 });
11036
11037 // Opening the dock, when it's zoomed, retains focus
11038 workspace.update_in(cx, |workspace, window, cx| {
11039 workspace.toggle_dock(DockPosition::Right, window, cx)
11040 });
11041
11042 workspace.update_in(cx, |workspace, window, cx| {
11043 assert!(workspace.right_dock().read(cx).is_open());
11044 assert!(panel.is_zoomed(window, cx));
11045 assert!(workspace.zoomed.is_some());
11046 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11047 });
11048
11049 // Unzoom and close the panel, zoom the active pane.
11050 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11051 workspace.update_in(cx, |workspace, window, cx| {
11052 workspace.toggle_dock(DockPosition::Right, window, cx)
11053 });
11054 pane.update_in(cx, |pane, window, cx| {
11055 pane.toggle_zoom(&Default::default(), window, cx)
11056 });
11057
11058 // Opening a dock unzooms the pane.
11059 workspace.update_in(cx, |workspace, window, cx| {
11060 workspace.toggle_dock(DockPosition::Right, window, cx)
11061 });
11062 workspace.update_in(cx, |workspace, window, cx| {
11063 let pane = pane.read(cx);
11064 assert!(!pane.is_zoomed());
11065 assert!(!pane.focus_handle(cx).is_focused(window));
11066 assert!(workspace.right_dock().read(cx).is_open());
11067 assert!(workspace.zoomed.is_none());
11068 });
11069 }
11070
11071 #[gpui::test]
11072 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11073 init_test(cx);
11074 let fs = FakeFs::new(cx.executor());
11075
11076 let project = Project::test(fs, [], cx).await;
11077 let (workspace, cx) =
11078 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11079
11080 let panel = workspace.update_in(cx, |workspace, window, cx| {
11081 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11082 workspace.add_panel(panel.clone(), window, cx);
11083 panel
11084 });
11085
11086 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11087 pane.update_in(cx, |pane, window, cx| {
11088 let item = cx.new(TestItem::new);
11089 pane.add_item(Box::new(item), true, true, None, window, cx);
11090 });
11091
11092 // Enable close_panel_on_toggle
11093 cx.update_global(|store: &mut SettingsStore, cx| {
11094 store.update_user_settings(cx, |settings| {
11095 settings.workspace.close_panel_on_toggle = Some(true);
11096 });
11097 });
11098
11099 // Panel starts closed. Toggling should open and focus it.
11100 workspace.update_in(cx, |workspace, window, cx| {
11101 assert!(!workspace.right_dock().read(cx).is_open());
11102 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11103 });
11104
11105 workspace.update_in(cx, |workspace, window, cx| {
11106 assert!(
11107 workspace.right_dock().read(cx).is_open(),
11108 "Dock should be open after toggling from center"
11109 );
11110 assert!(
11111 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11112 "Panel should be focused after toggling from center"
11113 );
11114 });
11115
11116 // Panel is open and focused. Toggling should close the panel and
11117 // return focus to the center.
11118 workspace.update_in(cx, |workspace, window, cx| {
11119 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11120 });
11121
11122 workspace.update_in(cx, |workspace, window, cx| {
11123 assert!(
11124 !workspace.right_dock().read(cx).is_open(),
11125 "Dock should be closed after toggling from focused panel"
11126 );
11127 assert!(
11128 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11129 "Panel should not be focused after toggling from focused panel"
11130 );
11131 });
11132
11133 // Open the dock and focus something else so the panel is open but not
11134 // focused. Toggling should focus the panel (not close it).
11135 workspace.update_in(cx, |workspace, window, cx| {
11136 workspace
11137 .right_dock()
11138 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11139 window.focus(&pane.read(cx).focus_handle(cx), cx);
11140 });
11141
11142 workspace.update_in(cx, |workspace, window, cx| {
11143 assert!(workspace.right_dock().read(cx).is_open());
11144 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11145 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11146 });
11147
11148 workspace.update_in(cx, |workspace, window, cx| {
11149 assert!(
11150 workspace.right_dock().read(cx).is_open(),
11151 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11152 );
11153 assert!(
11154 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11155 "Panel should be focused after toggling an open-but-unfocused panel"
11156 );
11157 });
11158
11159 // Now disable the setting and verify the original behavior: toggling
11160 // from a focused panel moves focus to center but leaves the dock open.
11161 cx.update_global(|store: &mut SettingsStore, cx| {
11162 store.update_user_settings(cx, |settings| {
11163 settings.workspace.close_panel_on_toggle = Some(false);
11164 });
11165 });
11166
11167 workspace.update_in(cx, |workspace, window, cx| {
11168 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11169 });
11170
11171 workspace.update_in(cx, |workspace, window, cx| {
11172 assert!(
11173 workspace.right_dock().read(cx).is_open(),
11174 "Dock should remain open when setting is disabled"
11175 );
11176 assert!(
11177 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11178 "Panel should not be focused after toggling with setting disabled"
11179 );
11180 });
11181 }
11182
11183 #[gpui::test]
11184 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11185 init_test(cx);
11186 let fs = FakeFs::new(cx.executor());
11187
11188 let project = Project::test(fs, [], cx).await;
11189 let (workspace, cx) =
11190 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11191
11192 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11193 workspace.active_pane().clone()
11194 });
11195
11196 // Add an item to the pane so it can be zoomed
11197 workspace.update_in(cx, |workspace, window, cx| {
11198 let item = cx.new(TestItem::new);
11199 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11200 });
11201
11202 // Initially not zoomed
11203 workspace.update_in(cx, |workspace, _window, cx| {
11204 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11205 assert!(
11206 workspace.zoomed.is_none(),
11207 "Workspace should track no zoomed pane"
11208 );
11209 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11210 });
11211
11212 // Zoom In
11213 pane.update_in(cx, |pane, window, cx| {
11214 pane.zoom_in(&crate::ZoomIn, window, cx);
11215 });
11216
11217 workspace.update_in(cx, |workspace, window, cx| {
11218 assert!(
11219 pane.read(cx).is_zoomed(),
11220 "Pane should be zoomed after ZoomIn"
11221 );
11222 assert!(
11223 workspace.zoomed.is_some(),
11224 "Workspace should track the zoomed pane"
11225 );
11226 assert!(
11227 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11228 "ZoomIn should focus the pane"
11229 );
11230 });
11231
11232 // Zoom In again is a no-op
11233 pane.update_in(cx, |pane, window, cx| {
11234 pane.zoom_in(&crate::ZoomIn, window, cx);
11235 });
11236
11237 workspace.update_in(cx, |workspace, window, cx| {
11238 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11239 assert!(
11240 workspace.zoomed.is_some(),
11241 "Workspace still tracks zoomed pane"
11242 );
11243 assert!(
11244 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11245 "Pane remains focused after repeated ZoomIn"
11246 );
11247 });
11248
11249 // Zoom Out
11250 pane.update_in(cx, |pane, window, cx| {
11251 pane.zoom_out(&crate::ZoomOut, window, cx);
11252 });
11253
11254 workspace.update_in(cx, |workspace, _window, cx| {
11255 assert!(
11256 !pane.read(cx).is_zoomed(),
11257 "Pane should unzoom after ZoomOut"
11258 );
11259 assert!(
11260 workspace.zoomed.is_none(),
11261 "Workspace clears zoom tracking after ZoomOut"
11262 );
11263 });
11264
11265 // Zoom Out again is a no-op
11266 pane.update_in(cx, |pane, window, cx| {
11267 pane.zoom_out(&crate::ZoomOut, window, cx);
11268 });
11269
11270 workspace.update_in(cx, |workspace, _window, cx| {
11271 assert!(
11272 !pane.read(cx).is_zoomed(),
11273 "Second ZoomOut keeps pane unzoomed"
11274 );
11275 assert!(
11276 workspace.zoomed.is_none(),
11277 "Workspace remains without zoomed pane"
11278 );
11279 });
11280 }
11281
11282 #[gpui::test]
11283 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11284 init_test(cx);
11285 let fs = FakeFs::new(cx.executor());
11286
11287 let project = Project::test(fs, [], cx).await;
11288 let (workspace, cx) =
11289 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11290 workspace.update_in(cx, |workspace, window, cx| {
11291 // Open two docks
11292 let left_dock = workspace.dock_at_position(DockPosition::Left);
11293 let right_dock = workspace.dock_at_position(DockPosition::Right);
11294
11295 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11296 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11297
11298 assert!(left_dock.read(cx).is_open());
11299 assert!(right_dock.read(cx).is_open());
11300 });
11301
11302 workspace.update_in(cx, |workspace, window, cx| {
11303 // Toggle all docks - should close both
11304 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11305
11306 let left_dock = workspace.dock_at_position(DockPosition::Left);
11307 let right_dock = workspace.dock_at_position(DockPosition::Right);
11308 assert!(!left_dock.read(cx).is_open());
11309 assert!(!right_dock.read(cx).is_open());
11310 });
11311
11312 workspace.update_in(cx, |workspace, window, cx| {
11313 // Toggle again - should reopen both
11314 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11315
11316 let left_dock = workspace.dock_at_position(DockPosition::Left);
11317 let right_dock = workspace.dock_at_position(DockPosition::Right);
11318 assert!(left_dock.read(cx).is_open());
11319 assert!(right_dock.read(cx).is_open());
11320 });
11321 }
11322
11323 #[gpui::test]
11324 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11325 init_test(cx);
11326 let fs = FakeFs::new(cx.executor());
11327
11328 let project = Project::test(fs, [], cx).await;
11329 let (workspace, cx) =
11330 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11331 workspace.update_in(cx, |workspace, window, cx| {
11332 // Open two docks
11333 let left_dock = workspace.dock_at_position(DockPosition::Left);
11334 let right_dock = workspace.dock_at_position(DockPosition::Right);
11335
11336 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11337 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11338
11339 assert!(left_dock.read(cx).is_open());
11340 assert!(right_dock.read(cx).is_open());
11341 });
11342
11343 workspace.update_in(cx, |workspace, window, cx| {
11344 // Close them manually
11345 workspace.toggle_dock(DockPosition::Left, window, cx);
11346 workspace.toggle_dock(DockPosition::Right, window, cx);
11347
11348 let left_dock = workspace.dock_at_position(DockPosition::Left);
11349 let right_dock = workspace.dock_at_position(DockPosition::Right);
11350 assert!(!left_dock.read(cx).is_open());
11351 assert!(!right_dock.read(cx).is_open());
11352 });
11353
11354 workspace.update_in(cx, |workspace, window, cx| {
11355 // Toggle all docks - only last closed (right dock) should reopen
11356 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11357
11358 let left_dock = workspace.dock_at_position(DockPosition::Left);
11359 let right_dock = workspace.dock_at_position(DockPosition::Right);
11360 assert!(!left_dock.read(cx).is_open());
11361 assert!(right_dock.read(cx).is_open());
11362 });
11363 }
11364
11365 #[gpui::test]
11366 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11367 init_test(cx);
11368 let fs = FakeFs::new(cx.executor());
11369 let project = Project::test(fs, [], cx).await;
11370 let (multi_workspace, cx) =
11371 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11372 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11373
11374 // Open two docks (left and right) with one panel each
11375 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11376 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11377 workspace.add_panel(left_panel.clone(), window, cx);
11378
11379 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11380 workspace.add_panel(right_panel.clone(), window, cx);
11381
11382 workspace.toggle_dock(DockPosition::Left, window, cx);
11383 workspace.toggle_dock(DockPosition::Right, window, cx);
11384
11385 // Verify initial state
11386 assert!(
11387 workspace.left_dock().read(cx).is_open(),
11388 "Left dock should be open"
11389 );
11390 assert_eq!(
11391 workspace
11392 .left_dock()
11393 .read(cx)
11394 .visible_panel()
11395 .unwrap()
11396 .panel_id(),
11397 left_panel.panel_id(),
11398 "Left panel should be visible in left dock"
11399 );
11400 assert!(
11401 workspace.right_dock().read(cx).is_open(),
11402 "Right dock should be open"
11403 );
11404 assert_eq!(
11405 workspace
11406 .right_dock()
11407 .read(cx)
11408 .visible_panel()
11409 .unwrap()
11410 .panel_id(),
11411 right_panel.panel_id(),
11412 "Right panel should be visible in right dock"
11413 );
11414 assert!(
11415 !workspace.bottom_dock().read(cx).is_open(),
11416 "Bottom dock should be closed"
11417 );
11418
11419 (left_panel, right_panel)
11420 });
11421
11422 // Focus the left panel and move it to the next position (bottom dock)
11423 workspace.update_in(cx, |workspace, window, cx| {
11424 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11425 assert!(
11426 left_panel.read(cx).focus_handle(cx).is_focused(window),
11427 "Left panel should be focused"
11428 );
11429 });
11430
11431 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11432
11433 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11434 workspace.update(cx, |workspace, cx| {
11435 assert!(
11436 !workspace.left_dock().read(cx).is_open(),
11437 "Left dock should be closed"
11438 );
11439 assert!(
11440 workspace.bottom_dock().read(cx).is_open(),
11441 "Bottom dock should now be open"
11442 );
11443 assert_eq!(
11444 left_panel.read(cx).position,
11445 DockPosition::Bottom,
11446 "Left panel should now be in the bottom dock"
11447 );
11448 assert_eq!(
11449 workspace
11450 .bottom_dock()
11451 .read(cx)
11452 .visible_panel()
11453 .unwrap()
11454 .panel_id(),
11455 left_panel.panel_id(),
11456 "Left panel should be the visible panel in the bottom dock"
11457 );
11458 });
11459
11460 // Toggle all docks off
11461 workspace.update_in(cx, |workspace, window, cx| {
11462 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11463 assert!(
11464 !workspace.left_dock().read(cx).is_open(),
11465 "Left dock should be closed"
11466 );
11467 assert!(
11468 !workspace.right_dock().read(cx).is_open(),
11469 "Right dock should be closed"
11470 );
11471 assert!(
11472 !workspace.bottom_dock().read(cx).is_open(),
11473 "Bottom dock should be closed"
11474 );
11475 });
11476
11477 // Toggle all docks back on and verify positions are restored
11478 workspace.update_in(cx, |workspace, window, cx| {
11479 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11480 assert!(
11481 !workspace.left_dock().read(cx).is_open(),
11482 "Left dock should remain closed"
11483 );
11484 assert!(
11485 workspace.right_dock().read(cx).is_open(),
11486 "Right dock should remain open"
11487 );
11488 assert!(
11489 workspace.bottom_dock().read(cx).is_open(),
11490 "Bottom dock should remain open"
11491 );
11492 assert_eq!(
11493 left_panel.read(cx).position,
11494 DockPosition::Bottom,
11495 "Left panel should remain in the bottom dock"
11496 );
11497 assert_eq!(
11498 right_panel.read(cx).position,
11499 DockPosition::Right,
11500 "Right panel should remain in the right dock"
11501 );
11502 assert_eq!(
11503 workspace
11504 .bottom_dock()
11505 .read(cx)
11506 .visible_panel()
11507 .unwrap()
11508 .panel_id(),
11509 left_panel.panel_id(),
11510 "Left panel should be the visible panel in the right dock"
11511 );
11512 });
11513 }
11514
11515 #[gpui::test]
11516 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11517 init_test(cx);
11518
11519 let fs = FakeFs::new(cx.executor());
11520
11521 let project = Project::test(fs, None, cx).await;
11522 let (workspace, cx) =
11523 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11524
11525 // Let's arrange the panes like this:
11526 //
11527 // +-----------------------+
11528 // | top |
11529 // +------+--------+-------+
11530 // | left | center | right |
11531 // +------+--------+-------+
11532 // | bottom |
11533 // +-----------------------+
11534
11535 let top_item = cx.new(|cx| {
11536 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11537 });
11538 let bottom_item = cx.new(|cx| {
11539 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11540 });
11541 let left_item = cx.new(|cx| {
11542 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11543 });
11544 let right_item = cx.new(|cx| {
11545 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11546 });
11547 let center_item = cx.new(|cx| {
11548 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11549 });
11550
11551 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11552 let top_pane_id = workspace.active_pane().entity_id();
11553 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11554 workspace.split_pane(
11555 workspace.active_pane().clone(),
11556 SplitDirection::Down,
11557 window,
11558 cx,
11559 );
11560 top_pane_id
11561 });
11562 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11563 let bottom_pane_id = workspace.active_pane().entity_id();
11564 workspace.add_item_to_active_pane(
11565 Box::new(bottom_item.clone()),
11566 None,
11567 false,
11568 window,
11569 cx,
11570 );
11571 workspace.split_pane(
11572 workspace.active_pane().clone(),
11573 SplitDirection::Up,
11574 window,
11575 cx,
11576 );
11577 bottom_pane_id
11578 });
11579 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11580 let left_pane_id = workspace.active_pane().entity_id();
11581 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11582 workspace.split_pane(
11583 workspace.active_pane().clone(),
11584 SplitDirection::Right,
11585 window,
11586 cx,
11587 );
11588 left_pane_id
11589 });
11590 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11591 let right_pane_id = workspace.active_pane().entity_id();
11592 workspace.add_item_to_active_pane(
11593 Box::new(right_item.clone()),
11594 None,
11595 false,
11596 window,
11597 cx,
11598 );
11599 workspace.split_pane(
11600 workspace.active_pane().clone(),
11601 SplitDirection::Left,
11602 window,
11603 cx,
11604 );
11605 right_pane_id
11606 });
11607 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11608 let center_pane_id = workspace.active_pane().entity_id();
11609 workspace.add_item_to_active_pane(
11610 Box::new(center_item.clone()),
11611 None,
11612 false,
11613 window,
11614 cx,
11615 );
11616 center_pane_id
11617 });
11618 cx.executor().run_until_parked();
11619
11620 workspace.update_in(cx, |workspace, window, cx| {
11621 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11622
11623 // Join into next from center pane into right
11624 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11625 });
11626
11627 workspace.update_in(cx, |workspace, window, cx| {
11628 let active_pane = workspace.active_pane();
11629 assert_eq!(right_pane_id, active_pane.entity_id());
11630 assert_eq!(2, active_pane.read(cx).items_len());
11631 let item_ids_in_pane =
11632 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11633 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11634 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11635
11636 // Join into next from right pane into bottom
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!(bottom_pane_id, active_pane.entity_id());
11643 assert_eq!(3, 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 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11649
11650 // Join into next from bottom pane into left
11651 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11652 });
11653
11654 workspace.update_in(cx, |workspace, window, cx| {
11655 let active_pane = workspace.active_pane();
11656 assert_eq!(left_pane_id, active_pane.entity_id());
11657 assert_eq!(4, active_pane.read(cx).items_len());
11658 let item_ids_in_pane =
11659 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11660 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11661 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11662 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11663 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11664
11665 // Join into next from left pane into top
11666 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11667 });
11668
11669 workspace.update_in(cx, |workspace, window, cx| {
11670 let active_pane = workspace.active_pane();
11671 assert_eq!(top_pane_id, active_pane.entity_id());
11672 assert_eq!(5, active_pane.read(cx).items_len());
11673 let item_ids_in_pane =
11674 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11675 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11676 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11677 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11678 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11679 assert!(item_ids_in_pane.contains(&top_item.item_id()));
11680
11681 // Single pane left: no-op
11682 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11683 });
11684
11685 workspace.update(cx, |workspace, _cx| {
11686 let active_pane = workspace.active_pane();
11687 assert_eq!(top_pane_id, active_pane.entity_id());
11688 });
11689 }
11690
11691 fn add_an_item_to_active_pane(
11692 cx: &mut VisualTestContext,
11693 workspace: &Entity<Workspace>,
11694 item_id: u64,
11695 ) -> Entity<TestItem> {
11696 let item = cx.new(|cx| {
11697 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11698 item_id,
11699 "item{item_id}.txt",
11700 cx,
11701 )])
11702 });
11703 workspace.update_in(cx, |workspace, window, cx| {
11704 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11705 });
11706 item
11707 }
11708
11709 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11710 workspace.update_in(cx, |workspace, window, cx| {
11711 workspace.split_pane(
11712 workspace.active_pane().clone(),
11713 SplitDirection::Right,
11714 window,
11715 cx,
11716 )
11717 })
11718 }
11719
11720 #[gpui::test]
11721 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11722 init_test(cx);
11723 let fs = FakeFs::new(cx.executor());
11724 let project = Project::test(fs, None, cx).await;
11725 let (workspace, cx) =
11726 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11727
11728 add_an_item_to_active_pane(cx, &workspace, 1);
11729 split_pane(cx, &workspace);
11730 add_an_item_to_active_pane(cx, &workspace, 2);
11731 split_pane(cx, &workspace); // empty pane
11732 split_pane(cx, &workspace);
11733 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11734
11735 cx.executor().run_until_parked();
11736
11737 workspace.update(cx, |workspace, cx| {
11738 let num_panes = workspace.panes().len();
11739 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11740 let active_item = workspace
11741 .active_pane()
11742 .read(cx)
11743 .active_item()
11744 .expect("item is in focus");
11745
11746 assert_eq!(num_panes, 4);
11747 assert_eq!(num_items_in_current_pane, 1);
11748 assert_eq!(active_item.item_id(), last_item.item_id());
11749 });
11750
11751 workspace.update_in(cx, |workspace, window, cx| {
11752 workspace.join_all_panes(window, cx);
11753 });
11754
11755 workspace.update(cx, |workspace, cx| {
11756 let num_panes = workspace.panes().len();
11757 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11758 let active_item = workspace
11759 .active_pane()
11760 .read(cx)
11761 .active_item()
11762 .expect("item is in focus");
11763
11764 assert_eq!(num_panes, 1);
11765 assert_eq!(num_items_in_current_pane, 3);
11766 assert_eq!(active_item.item_id(), last_item.item_id());
11767 });
11768 }
11769 struct TestModal(FocusHandle);
11770
11771 impl TestModal {
11772 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11773 Self(cx.focus_handle())
11774 }
11775 }
11776
11777 impl EventEmitter<DismissEvent> for TestModal {}
11778
11779 impl Focusable for TestModal {
11780 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11781 self.0.clone()
11782 }
11783 }
11784
11785 impl ModalView for TestModal {}
11786
11787 impl Render for TestModal {
11788 fn render(
11789 &mut self,
11790 _window: &mut Window,
11791 _cx: &mut Context<TestModal>,
11792 ) -> impl IntoElement {
11793 div().track_focus(&self.0)
11794 }
11795 }
11796
11797 #[gpui::test]
11798 async fn test_panels(cx: &mut gpui::TestAppContext) {
11799 init_test(cx);
11800 let fs = FakeFs::new(cx.executor());
11801
11802 let project = Project::test(fs, [], cx).await;
11803 let (multi_workspace, cx) =
11804 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11805 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11806
11807 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11808 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11809 workspace.add_panel(panel_1.clone(), window, cx);
11810 workspace.toggle_dock(DockPosition::Left, window, cx);
11811 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11812 workspace.add_panel(panel_2.clone(), window, cx);
11813 workspace.toggle_dock(DockPosition::Right, window, cx);
11814
11815 let left_dock = workspace.left_dock();
11816 assert_eq!(
11817 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11818 panel_1.panel_id()
11819 );
11820 assert_eq!(
11821 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11822 panel_1.size(window, cx)
11823 );
11824
11825 left_dock.update(cx, |left_dock, cx| {
11826 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11827 });
11828 assert_eq!(
11829 workspace
11830 .right_dock()
11831 .read(cx)
11832 .visible_panel()
11833 .unwrap()
11834 .panel_id(),
11835 panel_2.panel_id(),
11836 );
11837
11838 (panel_1, panel_2)
11839 });
11840
11841 // Move panel_1 to the right
11842 panel_1.update_in(cx, |panel_1, window, cx| {
11843 panel_1.set_position(DockPosition::Right, window, cx)
11844 });
11845
11846 workspace.update_in(cx, |workspace, window, cx| {
11847 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11848 // Since it was the only panel on the left, the left dock should now be closed.
11849 assert!(!workspace.left_dock().read(cx).is_open());
11850 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11851 let right_dock = workspace.right_dock();
11852 assert_eq!(
11853 right_dock.read(cx).visible_panel().unwrap().panel_id(),
11854 panel_1.panel_id()
11855 );
11856 assert_eq!(
11857 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11858 px(1337.)
11859 );
11860
11861 // Now we move panel_2 to the left
11862 panel_2.set_position(DockPosition::Left, window, cx);
11863 });
11864
11865 workspace.update(cx, |workspace, cx| {
11866 // Since panel_2 was not visible on the right, we don't open the left dock.
11867 assert!(!workspace.left_dock().read(cx).is_open());
11868 // And the right dock is unaffected in its displaying of panel_1
11869 assert!(workspace.right_dock().read(cx).is_open());
11870 assert_eq!(
11871 workspace
11872 .right_dock()
11873 .read(cx)
11874 .visible_panel()
11875 .unwrap()
11876 .panel_id(),
11877 panel_1.panel_id(),
11878 );
11879 });
11880
11881 // Move panel_1 back to the left
11882 panel_1.update_in(cx, |panel_1, window, cx| {
11883 panel_1.set_position(DockPosition::Left, window, cx)
11884 });
11885
11886 workspace.update_in(cx, |workspace, window, cx| {
11887 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11888 let left_dock = workspace.left_dock();
11889 assert!(left_dock.read(cx).is_open());
11890 assert_eq!(
11891 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11892 panel_1.panel_id()
11893 );
11894 assert_eq!(
11895 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11896 px(1337.)
11897 );
11898 // And the right dock should be closed as it no longer has any panels.
11899 assert!(!workspace.right_dock().read(cx).is_open());
11900
11901 // Now we move panel_1 to the bottom
11902 panel_1.set_position(DockPosition::Bottom, window, cx);
11903 });
11904
11905 workspace.update_in(cx, |workspace, window, cx| {
11906 // Since panel_1 was visible on the left, we close the left dock.
11907 assert!(!workspace.left_dock().read(cx).is_open());
11908 // The bottom dock is sized based on the panel's default size,
11909 // since the panel orientation changed from vertical to horizontal.
11910 let bottom_dock = workspace.bottom_dock();
11911 assert_eq!(
11912 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
11913 panel_1.size(window, cx),
11914 );
11915 // Close bottom dock and move panel_1 back to the left.
11916 bottom_dock.update(cx, |bottom_dock, cx| {
11917 bottom_dock.set_open(false, window, cx)
11918 });
11919 panel_1.set_position(DockPosition::Left, window, cx);
11920 });
11921
11922 // Emit activated event on panel 1
11923 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
11924
11925 // Now the left dock is open and panel_1 is active and focused.
11926 workspace.update_in(cx, |workspace, window, cx| {
11927 let left_dock = workspace.left_dock();
11928 assert!(left_dock.read(cx).is_open());
11929 assert_eq!(
11930 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11931 panel_1.panel_id(),
11932 );
11933 assert!(panel_1.focus_handle(cx).is_focused(window));
11934 });
11935
11936 // Emit closed event on panel 2, which is not active
11937 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11938
11939 // Wo don't close the left dock, because panel_2 wasn't the active panel
11940 workspace.update(cx, |workspace, cx| {
11941 let left_dock = workspace.left_dock();
11942 assert!(left_dock.read(cx).is_open());
11943 assert_eq!(
11944 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11945 panel_1.panel_id(),
11946 );
11947 });
11948
11949 // Emitting a ZoomIn event shows the panel as zoomed.
11950 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
11951 workspace.read_with(cx, |workspace, _| {
11952 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11953 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
11954 });
11955
11956 // Move panel to another dock while it is zoomed
11957 panel_1.update_in(cx, |panel, window, cx| {
11958 panel.set_position(DockPosition::Right, window, cx)
11959 });
11960 workspace.read_with(cx, |workspace, _| {
11961 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11962
11963 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11964 });
11965
11966 // This is a helper for getting a:
11967 // - valid focus on an element,
11968 // - that isn't a part of the panes and panels system of the Workspace,
11969 // - and doesn't trigger the 'on_focus_lost' API.
11970 let focus_other_view = {
11971 let workspace = workspace.clone();
11972 move |cx: &mut VisualTestContext| {
11973 workspace.update_in(cx, |workspace, window, cx| {
11974 if workspace.active_modal::<TestModal>(cx).is_some() {
11975 workspace.toggle_modal(window, cx, TestModal::new);
11976 workspace.toggle_modal(window, cx, TestModal::new);
11977 } else {
11978 workspace.toggle_modal(window, cx, TestModal::new);
11979 }
11980 })
11981 }
11982 };
11983
11984 // If focus is transferred to another view that's not a panel or another pane, we still show
11985 // the panel as zoomed.
11986 focus_other_view(cx);
11987 workspace.read_with(cx, |workspace, _| {
11988 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11989 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11990 });
11991
11992 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
11993 workspace.update_in(cx, |_workspace, window, cx| {
11994 cx.focus_self(window);
11995 });
11996 workspace.read_with(cx, |workspace, _| {
11997 assert_eq!(workspace.zoomed, None);
11998 assert_eq!(workspace.zoomed_position, None);
11999 });
12000
12001 // If focus is transferred again to another view that's not a panel or a pane, we won't
12002 // show the panel as zoomed because it wasn't zoomed before.
12003 focus_other_view(cx);
12004 workspace.read_with(cx, |workspace, _| {
12005 assert_eq!(workspace.zoomed, None);
12006 assert_eq!(workspace.zoomed_position, None);
12007 });
12008
12009 // When the panel is activated, it is zoomed again.
12010 cx.dispatch_action(ToggleRightDock);
12011 workspace.read_with(cx, |workspace, _| {
12012 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12013 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12014 });
12015
12016 // Emitting a ZoomOut event unzooms the panel.
12017 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12018 workspace.read_with(cx, |workspace, _| {
12019 assert_eq!(workspace.zoomed, None);
12020 assert_eq!(workspace.zoomed_position, None);
12021 });
12022
12023 // Emit closed event on panel 1, which is active
12024 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12025
12026 // Now the left dock is closed, because panel_1 was the active panel
12027 workspace.update(cx, |workspace, cx| {
12028 let right_dock = workspace.right_dock();
12029 assert!(!right_dock.read(cx).is_open());
12030 });
12031 }
12032
12033 #[gpui::test]
12034 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12035 init_test(cx);
12036
12037 let fs = FakeFs::new(cx.background_executor.clone());
12038 let project = Project::test(fs, [], cx).await;
12039 let (workspace, cx) =
12040 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12041 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12042
12043 let dirty_regular_buffer = cx.new(|cx| {
12044 TestItem::new(cx)
12045 .with_dirty(true)
12046 .with_label("1.txt")
12047 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12048 });
12049 let dirty_regular_buffer_2 = cx.new(|cx| {
12050 TestItem::new(cx)
12051 .with_dirty(true)
12052 .with_label("2.txt")
12053 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12054 });
12055 let dirty_multi_buffer_with_both = cx.new(|cx| {
12056 TestItem::new(cx)
12057 .with_dirty(true)
12058 .with_buffer_kind(ItemBufferKind::Multibuffer)
12059 .with_label("Fake Project Search")
12060 .with_project_items(&[
12061 dirty_regular_buffer.read(cx).project_items[0].clone(),
12062 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12063 ])
12064 });
12065 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12066 workspace.update_in(cx, |workspace, window, cx| {
12067 workspace.add_item(
12068 pane.clone(),
12069 Box::new(dirty_regular_buffer.clone()),
12070 None,
12071 false,
12072 false,
12073 window,
12074 cx,
12075 );
12076 workspace.add_item(
12077 pane.clone(),
12078 Box::new(dirty_regular_buffer_2.clone()),
12079 None,
12080 false,
12081 false,
12082 window,
12083 cx,
12084 );
12085 workspace.add_item(
12086 pane.clone(),
12087 Box::new(dirty_multi_buffer_with_both.clone()),
12088 None,
12089 false,
12090 false,
12091 window,
12092 cx,
12093 );
12094 });
12095
12096 pane.update_in(cx, |pane, window, cx| {
12097 pane.activate_item(2, true, true, window, cx);
12098 assert_eq!(
12099 pane.active_item().unwrap().item_id(),
12100 multi_buffer_with_both_files_id,
12101 "Should select the multi buffer in the pane"
12102 );
12103 });
12104 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12105 pane.close_other_items(
12106 &CloseOtherItems {
12107 save_intent: Some(SaveIntent::Save),
12108 close_pinned: true,
12109 },
12110 None,
12111 window,
12112 cx,
12113 )
12114 });
12115 cx.background_executor.run_until_parked();
12116 assert!(!cx.has_pending_prompt());
12117 close_all_but_multi_buffer_task
12118 .await
12119 .expect("Closing all buffers but the multi buffer failed");
12120 pane.update(cx, |pane, cx| {
12121 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12122 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12123 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12124 assert_eq!(pane.items_len(), 1);
12125 assert_eq!(
12126 pane.active_item().unwrap().item_id(),
12127 multi_buffer_with_both_files_id,
12128 "Should have only the multi buffer left in the pane"
12129 );
12130 assert!(
12131 dirty_multi_buffer_with_both.read(cx).is_dirty,
12132 "The multi buffer containing the unsaved buffer should still be dirty"
12133 );
12134 });
12135
12136 dirty_regular_buffer.update(cx, |buffer, cx| {
12137 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12138 });
12139
12140 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12141 pane.close_active_item(
12142 &CloseActiveItem {
12143 save_intent: Some(SaveIntent::Close),
12144 close_pinned: false,
12145 },
12146 window,
12147 cx,
12148 )
12149 });
12150 cx.background_executor.run_until_parked();
12151 assert!(
12152 cx.has_pending_prompt(),
12153 "Dirty multi buffer should prompt a save dialog"
12154 );
12155 cx.simulate_prompt_answer("Save");
12156 cx.background_executor.run_until_parked();
12157 close_multi_buffer_task
12158 .await
12159 .expect("Closing the multi buffer failed");
12160 pane.update(cx, |pane, cx| {
12161 assert_eq!(
12162 dirty_multi_buffer_with_both.read(cx).save_count,
12163 1,
12164 "Multi buffer item should get be saved"
12165 );
12166 // Test impl does not save inner items, so we do not assert them
12167 assert_eq!(
12168 pane.items_len(),
12169 0,
12170 "No more items should be left in the pane"
12171 );
12172 assert!(pane.active_item().is_none());
12173 });
12174 }
12175
12176 #[gpui::test]
12177 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
12178 cx: &mut TestAppContext,
12179 ) {
12180 init_test(cx);
12181
12182 let fs = FakeFs::new(cx.background_executor.clone());
12183 let project = Project::test(fs, [], cx).await;
12184 let (workspace, cx) =
12185 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12186 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12187
12188 let dirty_regular_buffer = cx.new(|cx| {
12189 TestItem::new(cx)
12190 .with_dirty(true)
12191 .with_label("1.txt")
12192 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12193 });
12194 let dirty_regular_buffer_2 = cx.new(|cx| {
12195 TestItem::new(cx)
12196 .with_dirty(true)
12197 .with_label("2.txt")
12198 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12199 });
12200 let clear_regular_buffer = cx.new(|cx| {
12201 TestItem::new(cx)
12202 .with_label("3.txt")
12203 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12204 });
12205
12206 let dirty_multi_buffer_with_both = cx.new(|cx| {
12207 TestItem::new(cx)
12208 .with_dirty(true)
12209 .with_buffer_kind(ItemBufferKind::Multibuffer)
12210 .with_label("Fake Project Search")
12211 .with_project_items(&[
12212 dirty_regular_buffer.read(cx).project_items[0].clone(),
12213 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12214 clear_regular_buffer.read(cx).project_items[0].clone(),
12215 ])
12216 });
12217 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12218 workspace.update_in(cx, |workspace, window, cx| {
12219 workspace.add_item(
12220 pane.clone(),
12221 Box::new(dirty_regular_buffer.clone()),
12222 None,
12223 false,
12224 false,
12225 window,
12226 cx,
12227 );
12228 workspace.add_item(
12229 pane.clone(),
12230 Box::new(dirty_multi_buffer_with_both.clone()),
12231 None,
12232 false,
12233 false,
12234 window,
12235 cx,
12236 );
12237 });
12238
12239 pane.update_in(cx, |pane, window, cx| {
12240 pane.activate_item(1, true, true, window, cx);
12241 assert_eq!(
12242 pane.active_item().unwrap().item_id(),
12243 multi_buffer_with_both_files_id,
12244 "Should select the multi buffer in the pane"
12245 );
12246 });
12247 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12248 pane.close_active_item(
12249 &CloseActiveItem {
12250 save_intent: None,
12251 close_pinned: false,
12252 },
12253 window,
12254 cx,
12255 )
12256 });
12257 cx.background_executor.run_until_parked();
12258 assert!(
12259 cx.has_pending_prompt(),
12260 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
12261 );
12262 }
12263
12264 /// Tests that when `close_on_file_delete` is enabled, files are automatically
12265 /// closed when they are deleted from disk.
12266 #[gpui::test]
12267 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
12268 init_test(cx);
12269
12270 // Enable the close_on_disk_deletion setting
12271 cx.update_global(|store: &mut SettingsStore, cx| {
12272 store.update_user_settings(cx, |settings| {
12273 settings.workspace.close_on_file_delete = Some(true);
12274 });
12275 });
12276
12277 let fs = FakeFs::new(cx.background_executor.clone());
12278 let project = Project::test(fs, [], cx).await;
12279 let (workspace, cx) =
12280 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12281 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12282
12283 // Create a test item that simulates a file
12284 let item = cx.new(|cx| {
12285 TestItem::new(cx)
12286 .with_label("test.txt")
12287 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12288 });
12289
12290 // Add item to workspace
12291 workspace.update_in(cx, |workspace, window, cx| {
12292 workspace.add_item(
12293 pane.clone(),
12294 Box::new(item.clone()),
12295 None,
12296 false,
12297 false,
12298 window,
12299 cx,
12300 );
12301 });
12302
12303 // Verify the item is in the pane
12304 pane.read_with(cx, |pane, _| {
12305 assert_eq!(pane.items().count(), 1);
12306 });
12307
12308 // Simulate file deletion by setting the item's deleted state
12309 item.update(cx, |item, _| {
12310 item.set_has_deleted_file(true);
12311 });
12312
12313 // Emit UpdateTab event to trigger the close behavior
12314 cx.run_until_parked();
12315 item.update(cx, |_, cx| {
12316 cx.emit(ItemEvent::UpdateTab);
12317 });
12318
12319 // Allow the close operation to complete
12320 cx.run_until_parked();
12321
12322 // Verify the item was automatically closed
12323 pane.read_with(cx, |pane, _| {
12324 assert_eq!(
12325 pane.items().count(),
12326 0,
12327 "Item should be automatically closed when file is deleted"
12328 );
12329 });
12330 }
12331
12332 /// Tests that when `close_on_file_delete` is disabled (default), files remain
12333 /// open with a strikethrough when they are deleted from disk.
12334 #[gpui::test]
12335 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12336 init_test(cx);
12337
12338 // Ensure close_on_disk_deletion is disabled (default)
12339 cx.update_global(|store: &mut SettingsStore, cx| {
12340 store.update_user_settings(cx, |settings| {
12341 settings.workspace.close_on_file_delete = Some(false);
12342 });
12343 });
12344
12345 let fs = FakeFs::new(cx.background_executor.clone());
12346 let project = Project::test(fs, [], cx).await;
12347 let (workspace, cx) =
12348 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12349 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12350
12351 // Create a test item that simulates a file
12352 let item = cx.new(|cx| {
12353 TestItem::new(cx)
12354 .with_label("test.txt")
12355 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12356 });
12357
12358 // Add item to workspace
12359 workspace.update_in(cx, |workspace, window, cx| {
12360 workspace.add_item(
12361 pane.clone(),
12362 Box::new(item.clone()),
12363 None,
12364 false,
12365 false,
12366 window,
12367 cx,
12368 );
12369 });
12370
12371 // Verify the item is in the pane
12372 pane.read_with(cx, |pane, _| {
12373 assert_eq!(pane.items().count(), 1);
12374 });
12375
12376 // Simulate file deletion
12377 item.update(cx, |item, _| {
12378 item.set_has_deleted_file(true);
12379 });
12380
12381 // Emit UpdateTab event
12382 cx.run_until_parked();
12383 item.update(cx, |_, cx| {
12384 cx.emit(ItemEvent::UpdateTab);
12385 });
12386
12387 // Allow any potential close operation to complete
12388 cx.run_until_parked();
12389
12390 // Verify the item remains open (with strikethrough)
12391 pane.read_with(cx, |pane, _| {
12392 assert_eq!(
12393 pane.items().count(),
12394 1,
12395 "Item should remain open when close_on_disk_deletion is disabled"
12396 );
12397 });
12398
12399 // Verify the item shows as deleted
12400 item.read_with(cx, |item, _| {
12401 assert!(
12402 item.has_deleted_file,
12403 "Item should be marked as having deleted file"
12404 );
12405 });
12406 }
12407
12408 /// Tests that dirty files are not automatically closed when deleted from disk,
12409 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12410 /// unsaved changes without being prompted.
12411 #[gpui::test]
12412 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12413 init_test(cx);
12414
12415 // Enable the close_on_file_delete setting
12416 cx.update_global(|store: &mut SettingsStore, cx| {
12417 store.update_user_settings(cx, |settings| {
12418 settings.workspace.close_on_file_delete = Some(true);
12419 });
12420 });
12421
12422 let fs = FakeFs::new(cx.background_executor.clone());
12423 let project = Project::test(fs, [], cx).await;
12424 let (workspace, cx) =
12425 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12426 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12427
12428 // Create a dirty test item
12429 let item = cx.new(|cx| {
12430 TestItem::new(cx)
12431 .with_dirty(true)
12432 .with_label("test.txt")
12433 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12434 });
12435
12436 // Add item to workspace
12437 workspace.update_in(cx, |workspace, window, cx| {
12438 workspace.add_item(
12439 pane.clone(),
12440 Box::new(item.clone()),
12441 None,
12442 false,
12443 false,
12444 window,
12445 cx,
12446 );
12447 });
12448
12449 // Simulate file deletion
12450 item.update(cx, |item, _| {
12451 item.set_has_deleted_file(true);
12452 });
12453
12454 // Emit UpdateTab event to trigger the close behavior
12455 cx.run_until_parked();
12456 item.update(cx, |_, cx| {
12457 cx.emit(ItemEvent::UpdateTab);
12458 });
12459
12460 // Allow any potential close operation to complete
12461 cx.run_until_parked();
12462
12463 // Verify the item remains open (dirty files are not auto-closed)
12464 pane.read_with(cx, |pane, _| {
12465 assert_eq!(
12466 pane.items().count(),
12467 1,
12468 "Dirty items should not be automatically closed even when file is deleted"
12469 );
12470 });
12471
12472 // Verify the item is marked as deleted and still dirty
12473 item.read_with(cx, |item, _| {
12474 assert!(
12475 item.has_deleted_file,
12476 "Item should be marked as having deleted file"
12477 );
12478 assert!(item.is_dirty, "Item should still be dirty");
12479 });
12480 }
12481
12482 /// Tests that navigation history is cleaned up when files are auto-closed
12483 /// due to deletion from disk.
12484 #[gpui::test]
12485 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12486 init_test(cx);
12487
12488 // Enable the close_on_file_delete setting
12489 cx.update_global(|store: &mut SettingsStore, cx| {
12490 store.update_user_settings(cx, |settings| {
12491 settings.workspace.close_on_file_delete = Some(true);
12492 });
12493 });
12494
12495 let fs = FakeFs::new(cx.background_executor.clone());
12496 let project = Project::test(fs, [], cx).await;
12497 let (workspace, cx) =
12498 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12499 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12500
12501 // Create test items
12502 let item1 = cx.new(|cx| {
12503 TestItem::new(cx)
12504 .with_label("test1.txt")
12505 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12506 });
12507 let item1_id = item1.item_id();
12508
12509 let item2 = cx.new(|cx| {
12510 TestItem::new(cx)
12511 .with_label("test2.txt")
12512 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12513 });
12514
12515 // Add items to workspace
12516 workspace.update_in(cx, |workspace, window, cx| {
12517 workspace.add_item(
12518 pane.clone(),
12519 Box::new(item1.clone()),
12520 None,
12521 false,
12522 false,
12523 window,
12524 cx,
12525 );
12526 workspace.add_item(
12527 pane.clone(),
12528 Box::new(item2.clone()),
12529 None,
12530 false,
12531 false,
12532 window,
12533 cx,
12534 );
12535 });
12536
12537 // Activate item1 to ensure it gets navigation entries
12538 pane.update_in(cx, |pane, window, cx| {
12539 pane.activate_item(0, true, true, window, cx);
12540 });
12541
12542 // Switch to item2 and back to create navigation history
12543 pane.update_in(cx, |pane, window, cx| {
12544 pane.activate_item(1, true, true, window, cx);
12545 });
12546 cx.run_until_parked();
12547
12548 pane.update_in(cx, |pane, window, cx| {
12549 pane.activate_item(0, true, true, window, cx);
12550 });
12551 cx.run_until_parked();
12552
12553 // Simulate file deletion for item1
12554 item1.update(cx, |item, _| {
12555 item.set_has_deleted_file(true);
12556 });
12557
12558 // Emit UpdateTab event to trigger the close behavior
12559 item1.update(cx, |_, cx| {
12560 cx.emit(ItemEvent::UpdateTab);
12561 });
12562 cx.run_until_parked();
12563
12564 // Verify item1 was closed
12565 pane.read_with(cx, |pane, _| {
12566 assert_eq!(
12567 pane.items().count(),
12568 1,
12569 "Should have 1 item remaining after auto-close"
12570 );
12571 });
12572
12573 // Check navigation history after close
12574 let has_item = pane.read_with(cx, |pane, cx| {
12575 let mut has_item = false;
12576 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12577 if entry.item.id() == item1_id {
12578 has_item = true;
12579 }
12580 });
12581 has_item
12582 });
12583
12584 assert!(
12585 !has_item,
12586 "Navigation history should not contain closed item entries"
12587 );
12588 }
12589
12590 #[gpui::test]
12591 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12592 cx: &mut TestAppContext,
12593 ) {
12594 init_test(cx);
12595
12596 let fs = FakeFs::new(cx.background_executor.clone());
12597 let project = Project::test(fs, [], cx).await;
12598 let (workspace, cx) =
12599 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12600 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12601
12602 let dirty_regular_buffer = cx.new(|cx| {
12603 TestItem::new(cx)
12604 .with_dirty(true)
12605 .with_label("1.txt")
12606 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12607 });
12608 let dirty_regular_buffer_2 = cx.new(|cx| {
12609 TestItem::new(cx)
12610 .with_dirty(true)
12611 .with_label("2.txt")
12612 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12613 });
12614 let clear_regular_buffer = cx.new(|cx| {
12615 TestItem::new(cx)
12616 .with_label("3.txt")
12617 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12618 });
12619
12620 let dirty_multi_buffer = cx.new(|cx| {
12621 TestItem::new(cx)
12622 .with_dirty(true)
12623 .with_buffer_kind(ItemBufferKind::Multibuffer)
12624 .with_label("Fake Project Search")
12625 .with_project_items(&[
12626 dirty_regular_buffer.read(cx).project_items[0].clone(),
12627 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12628 clear_regular_buffer.read(cx).project_items[0].clone(),
12629 ])
12630 });
12631 workspace.update_in(cx, |workspace, window, cx| {
12632 workspace.add_item(
12633 pane.clone(),
12634 Box::new(dirty_regular_buffer.clone()),
12635 None,
12636 false,
12637 false,
12638 window,
12639 cx,
12640 );
12641 workspace.add_item(
12642 pane.clone(),
12643 Box::new(dirty_regular_buffer_2.clone()),
12644 None,
12645 false,
12646 false,
12647 window,
12648 cx,
12649 );
12650 workspace.add_item(
12651 pane.clone(),
12652 Box::new(dirty_multi_buffer.clone()),
12653 None,
12654 false,
12655 false,
12656 window,
12657 cx,
12658 );
12659 });
12660
12661 pane.update_in(cx, |pane, window, cx| {
12662 pane.activate_item(2, true, true, window, cx);
12663 assert_eq!(
12664 pane.active_item().unwrap().item_id(),
12665 dirty_multi_buffer.item_id(),
12666 "Should select the multi buffer in the pane"
12667 );
12668 });
12669 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12670 pane.close_active_item(
12671 &CloseActiveItem {
12672 save_intent: None,
12673 close_pinned: false,
12674 },
12675 window,
12676 cx,
12677 )
12678 });
12679 cx.background_executor.run_until_parked();
12680 assert!(
12681 !cx.has_pending_prompt(),
12682 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12683 );
12684 close_multi_buffer_task
12685 .await
12686 .expect("Closing multi buffer failed");
12687 pane.update(cx, |pane, cx| {
12688 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12689 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12690 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12691 assert_eq!(
12692 pane.items()
12693 .map(|item| item.item_id())
12694 .sorted()
12695 .collect::<Vec<_>>(),
12696 vec![
12697 dirty_regular_buffer.item_id(),
12698 dirty_regular_buffer_2.item_id(),
12699 ],
12700 "Should have no multi buffer left in the pane"
12701 );
12702 assert!(dirty_regular_buffer.read(cx).is_dirty);
12703 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12704 });
12705 }
12706
12707 #[gpui::test]
12708 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12709 init_test(cx);
12710 let fs = FakeFs::new(cx.executor());
12711 let project = Project::test(fs, [], cx).await;
12712 let (multi_workspace, cx) =
12713 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12714 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12715
12716 // Add a new panel to the right dock, opening the dock and setting the
12717 // focus to the new panel.
12718 let panel = workspace.update_in(cx, |workspace, window, cx| {
12719 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12720 workspace.add_panel(panel.clone(), window, cx);
12721
12722 workspace
12723 .right_dock()
12724 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12725
12726 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12727
12728 panel
12729 });
12730
12731 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12732 // panel to the next valid position which, in this case, is the left
12733 // dock.
12734 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12735 workspace.update(cx, |workspace, cx| {
12736 assert!(workspace.left_dock().read(cx).is_open());
12737 assert_eq!(panel.read(cx).position, DockPosition::Left);
12738 });
12739
12740 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12741 // panel to the next valid position which, in this case, is the bottom
12742 // dock.
12743 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12744 workspace.update(cx, |workspace, cx| {
12745 assert!(workspace.bottom_dock().read(cx).is_open());
12746 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12747 });
12748
12749 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12750 // around moving the panel to its initial position, the right dock.
12751 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12752 workspace.update(cx, |workspace, cx| {
12753 assert!(workspace.right_dock().read(cx).is_open());
12754 assert_eq!(panel.read(cx).position, DockPosition::Right);
12755 });
12756
12757 // Remove focus from the panel, ensuring that, if the panel is not
12758 // focused, the `MoveFocusedPanelToNextPosition` action does not update
12759 // the panel's position, so the panel is still in the right dock.
12760 workspace.update_in(cx, |workspace, window, cx| {
12761 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12762 });
12763
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
12771 #[gpui::test]
12772 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12773 init_test(cx);
12774
12775 let fs = FakeFs::new(cx.executor());
12776 let project = Project::test(fs, [], cx).await;
12777 let (workspace, cx) =
12778 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12779
12780 let item_1 = cx.new(|cx| {
12781 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12782 });
12783 workspace.update_in(cx, |workspace, window, cx| {
12784 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12785 workspace.move_item_to_pane_in_direction(
12786 &MoveItemToPaneInDirection {
12787 direction: SplitDirection::Right,
12788 focus: true,
12789 clone: false,
12790 },
12791 window,
12792 cx,
12793 );
12794 workspace.move_item_to_pane_at_index(
12795 &MoveItemToPane {
12796 destination: 3,
12797 focus: true,
12798 clone: false,
12799 },
12800 window,
12801 cx,
12802 );
12803
12804 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12805 assert_eq!(
12806 pane_items_paths(&workspace.active_pane, cx),
12807 vec!["first.txt".to_string()],
12808 "Single item was not moved anywhere"
12809 );
12810 });
12811
12812 let item_2 = cx.new(|cx| {
12813 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12814 });
12815 workspace.update_in(cx, |workspace, window, cx| {
12816 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12817 assert_eq!(
12818 pane_items_paths(&workspace.panes[0], cx),
12819 vec!["first.txt".to_string(), "second.txt".to_string()],
12820 );
12821 workspace.move_item_to_pane_in_direction(
12822 &MoveItemToPaneInDirection {
12823 direction: SplitDirection::Right,
12824 focus: true,
12825 clone: false,
12826 },
12827 window,
12828 cx,
12829 );
12830
12831 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12832 assert_eq!(
12833 pane_items_paths(&workspace.panes[0], cx),
12834 vec!["first.txt".to_string()],
12835 "After moving, one item should be left in the original pane"
12836 );
12837 assert_eq!(
12838 pane_items_paths(&workspace.panes[1], cx),
12839 vec!["second.txt".to_string()],
12840 "New item should have been moved to the new pane"
12841 );
12842 });
12843
12844 let item_3 = cx.new(|cx| {
12845 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12846 });
12847 workspace.update_in(cx, |workspace, window, cx| {
12848 let original_pane = workspace.panes[0].clone();
12849 workspace.set_active_pane(&original_pane, window, cx);
12850 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12851 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12852 assert_eq!(
12853 pane_items_paths(&workspace.active_pane, cx),
12854 vec!["first.txt".to_string(), "third.txt".to_string()],
12855 "New pane should be ready to move one item out"
12856 );
12857
12858 workspace.move_item_to_pane_at_index(
12859 &MoveItemToPane {
12860 destination: 3,
12861 focus: true,
12862 clone: false,
12863 },
12864 window,
12865 cx,
12866 );
12867 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12868 assert_eq!(
12869 pane_items_paths(&workspace.active_pane, cx),
12870 vec!["first.txt".to_string()],
12871 "After moving, one item should be left in the original pane"
12872 );
12873 assert_eq!(
12874 pane_items_paths(&workspace.panes[1], cx),
12875 vec!["second.txt".to_string()],
12876 "Previously created pane should be unchanged"
12877 );
12878 assert_eq!(
12879 pane_items_paths(&workspace.panes[2], cx),
12880 vec!["third.txt".to_string()],
12881 "New item should have been moved to the new pane"
12882 );
12883 });
12884 }
12885
12886 #[gpui::test]
12887 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12888 init_test(cx);
12889
12890 let fs = FakeFs::new(cx.executor());
12891 let project = Project::test(fs, [], cx).await;
12892 let (workspace, cx) =
12893 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12894
12895 let item_1 = cx.new(|cx| {
12896 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12897 });
12898 workspace.update_in(cx, |workspace, window, cx| {
12899 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12900 workspace.move_item_to_pane_in_direction(
12901 &MoveItemToPaneInDirection {
12902 direction: SplitDirection::Right,
12903 focus: true,
12904 clone: true,
12905 },
12906 window,
12907 cx,
12908 );
12909 });
12910 cx.run_until_parked();
12911 workspace.update_in(cx, |workspace, window, cx| {
12912 workspace.move_item_to_pane_at_index(
12913 &MoveItemToPane {
12914 destination: 3,
12915 focus: true,
12916 clone: true,
12917 },
12918 window,
12919 cx,
12920 );
12921 });
12922 cx.run_until_parked();
12923
12924 workspace.update(cx, |workspace, cx| {
12925 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
12926 for pane in workspace.panes() {
12927 assert_eq!(
12928 pane_items_paths(pane, cx),
12929 vec!["first.txt".to_string()],
12930 "Single item exists in all panes"
12931 );
12932 }
12933 });
12934
12935 // verify that the active pane has been updated after waiting for the
12936 // pane focus event to fire and resolve
12937 workspace.read_with(cx, |workspace, _app| {
12938 assert_eq!(
12939 workspace.active_pane(),
12940 &workspace.panes[2],
12941 "The third pane should be the active one: {:?}",
12942 workspace.panes
12943 );
12944 })
12945 }
12946
12947 #[gpui::test]
12948 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
12949 init_test(cx);
12950
12951 let fs = FakeFs::new(cx.executor());
12952 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
12953
12954 let project = Project::test(fs, ["root".as_ref()], cx).await;
12955 let (workspace, cx) =
12956 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12957
12958 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12959 // Add item to pane A with project path
12960 let item_a = cx.new(|cx| {
12961 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12962 });
12963 workspace.update_in(cx, |workspace, window, cx| {
12964 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
12965 });
12966
12967 // Split to create pane B
12968 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
12969 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
12970 });
12971
12972 // Add item with SAME project path to pane B, and pin it
12973 let item_b = cx.new(|cx| {
12974 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12975 });
12976 pane_b.update_in(cx, |pane, window, cx| {
12977 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
12978 pane.set_pinned_count(1);
12979 });
12980
12981 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
12982 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
12983
12984 // close_pinned: false should only close the unpinned copy
12985 workspace.update_in(cx, |workspace, window, cx| {
12986 workspace.close_item_in_all_panes(
12987 &CloseItemInAllPanes {
12988 save_intent: Some(SaveIntent::Close),
12989 close_pinned: false,
12990 },
12991 window,
12992 cx,
12993 )
12994 });
12995 cx.executor().run_until_parked();
12996
12997 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
12998 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12999 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13000 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13001
13002 // Split again, seeing as closing the previous item also closed its
13003 // pane, so only pane remains, which does not allow us to properly test
13004 // that both items close when `close_pinned: true`.
13005 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13006 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13007 });
13008
13009 // Add an item with the same project path to pane C so that
13010 // close_item_in_all_panes can determine what to close across all panes
13011 // (it reads the active item from the active pane, and split_pane
13012 // creates an empty pane).
13013 let item_c = cx.new(|cx| {
13014 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13015 });
13016 pane_c.update_in(cx, |pane, window, cx| {
13017 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13018 });
13019
13020 // close_pinned: true should close the pinned copy too
13021 workspace.update_in(cx, |workspace, window, cx| {
13022 let panes_count = workspace.panes().len();
13023 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13024
13025 workspace.close_item_in_all_panes(
13026 &CloseItemInAllPanes {
13027 save_intent: Some(SaveIntent::Close),
13028 close_pinned: true,
13029 },
13030 window,
13031 cx,
13032 )
13033 });
13034 cx.executor().run_until_parked();
13035
13036 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13037 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13038 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13039 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13040 }
13041
13042 mod register_project_item_tests {
13043
13044 use super::*;
13045
13046 // View
13047 struct TestPngItemView {
13048 focus_handle: FocusHandle,
13049 }
13050 // Model
13051 struct TestPngItem {}
13052
13053 impl project::ProjectItem for TestPngItem {
13054 fn try_open(
13055 _project: &Entity<Project>,
13056 path: &ProjectPath,
13057 cx: &mut App,
13058 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13059 if path.path.extension().unwrap() == "png" {
13060 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13061 } else {
13062 None
13063 }
13064 }
13065
13066 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13067 None
13068 }
13069
13070 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13071 None
13072 }
13073
13074 fn is_dirty(&self) -> bool {
13075 false
13076 }
13077 }
13078
13079 impl Item for TestPngItemView {
13080 type Event = ();
13081 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13082 "".into()
13083 }
13084 }
13085 impl EventEmitter<()> for TestPngItemView {}
13086 impl Focusable for TestPngItemView {
13087 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13088 self.focus_handle.clone()
13089 }
13090 }
13091
13092 impl Render for TestPngItemView {
13093 fn render(
13094 &mut self,
13095 _window: &mut Window,
13096 _cx: &mut Context<Self>,
13097 ) -> impl IntoElement {
13098 Empty
13099 }
13100 }
13101
13102 impl ProjectItem for TestPngItemView {
13103 type Item = TestPngItem;
13104
13105 fn for_project_item(
13106 _project: Entity<Project>,
13107 _pane: Option<&Pane>,
13108 _item: Entity<Self::Item>,
13109 _: &mut Window,
13110 cx: &mut Context<Self>,
13111 ) -> Self
13112 where
13113 Self: Sized,
13114 {
13115 Self {
13116 focus_handle: cx.focus_handle(),
13117 }
13118 }
13119 }
13120
13121 // View
13122 struct TestIpynbItemView {
13123 focus_handle: FocusHandle,
13124 }
13125 // Model
13126 struct TestIpynbItem {}
13127
13128 impl project::ProjectItem for TestIpynbItem {
13129 fn try_open(
13130 _project: &Entity<Project>,
13131 path: &ProjectPath,
13132 cx: &mut App,
13133 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13134 if path.path.extension().unwrap() == "ipynb" {
13135 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13136 } else {
13137 None
13138 }
13139 }
13140
13141 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13142 None
13143 }
13144
13145 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13146 None
13147 }
13148
13149 fn is_dirty(&self) -> bool {
13150 false
13151 }
13152 }
13153
13154 impl Item for TestIpynbItemView {
13155 type Event = ();
13156 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13157 "".into()
13158 }
13159 }
13160 impl EventEmitter<()> for TestIpynbItemView {}
13161 impl Focusable for TestIpynbItemView {
13162 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13163 self.focus_handle.clone()
13164 }
13165 }
13166
13167 impl Render for TestIpynbItemView {
13168 fn render(
13169 &mut self,
13170 _window: &mut Window,
13171 _cx: &mut Context<Self>,
13172 ) -> impl IntoElement {
13173 Empty
13174 }
13175 }
13176
13177 impl ProjectItem for TestIpynbItemView {
13178 type Item = TestIpynbItem;
13179
13180 fn for_project_item(
13181 _project: Entity<Project>,
13182 _pane: Option<&Pane>,
13183 _item: Entity<Self::Item>,
13184 _: &mut Window,
13185 cx: &mut Context<Self>,
13186 ) -> Self
13187 where
13188 Self: Sized,
13189 {
13190 Self {
13191 focus_handle: cx.focus_handle(),
13192 }
13193 }
13194 }
13195
13196 struct TestAlternatePngItemView {
13197 focus_handle: FocusHandle,
13198 }
13199
13200 impl Item for TestAlternatePngItemView {
13201 type Event = ();
13202 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13203 "".into()
13204 }
13205 }
13206
13207 impl EventEmitter<()> for TestAlternatePngItemView {}
13208 impl Focusable for TestAlternatePngItemView {
13209 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13210 self.focus_handle.clone()
13211 }
13212 }
13213
13214 impl Render for TestAlternatePngItemView {
13215 fn render(
13216 &mut self,
13217 _window: &mut Window,
13218 _cx: &mut Context<Self>,
13219 ) -> impl IntoElement {
13220 Empty
13221 }
13222 }
13223
13224 impl ProjectItem for TestAlternatePngItemView {
13225 type Item = TestPngItem;
13226
13227 fn for_project_item(
13228 _project: Entity<Project>,
13229 _pane: Option<&Pane>,
13230 _item: Entity<Self::Item>,
13231 _: &mut Window,
13232 cx: &mut Context<Self>,
13233 ) -> Self
13234 where
13235 Self: Sized,
13236 {
13237 Self {
13238 focus_handle: cx.focus_handle(),
13239 }
13240 }
13241 }
13242
13243 #[gpui::test]
13244 async fn test_register_project_item(cx: &mut TestAppContext) {
13245 init_test(cx);
13246
13247 cx.update(|cx| {
13248 register_project_item::<TestPngItemView>(cx);
13249 register_project_item::<TestIpynbItemView>(cx);
13250 });
13251
13252 let fs = FakeFs::new(cx.executor());
13253 fs.insert_tree(
13254 "/root1",
13255 json!({
13256 "one.png": "BINARYDATAHERE",
13257 "two.ipynb": "{ totally a notebook }",
13258 "three.txt": "editing text, sure why not?"
13259 }),
13260 )
13261 .await;
13262
13263 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13264 let (workspace, cx) =
13265 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13266
13267 let worktree_id = project.update(cx, |project, cx| {
13268 project.worktrees(cx).next().unwrap().read(cx).id()
13269 });
13270
13271 let handle = workspace
13272 .update_in(cx, |workspace, window, cx| {
13273 let project_path = (worktree_id, rel_path("one.png"));
13274 workspace.open_path(project_path, None, true, window, cx)
13275 })
13276 .await
13277 .unwrap();
13278
13279 // Now we can check if the handle we got back errored or not
13280 assert_eq!(
13281 handle.to_any_view().entity_type(),
13282 TypeId::of::<TestPngItemView>()
13283 );
13284
13285 let handle = workspace
13286 .update_in(cx, |workspace, window, cx| {
13287 let project_path = (worktree_id, rel_path("two.ipynb"));
13288 workspace.open_path(project_path, None, true, window, cx)
13289 })
13290 .await
13291 .unwrap();
13292
13293 assert_eq!(
13294 handle.to_any_view().entity_type(),
13295 TypeId::of::<TestIpynbItemView>()
13296 );
13297
13298 let handle = workspace
13299 .update_in(cx, |workspace, window, cx| {
13300 let project_path = (worktree_id, rel_path("three.txt"));
13301 workspace.open_path(project_path, None, true, window, cx)
13302 })
13303 .await;
13304 assert!(handle.is_err());
13305 }
13306
13307 #[gpui::test]
13308 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
13309 init_test(cx);
13310
13311 cx.update(|cx| {
13312 register_project_item::<TestPngItemView>(cx);
13313 register_project_item::<TestAlternatePngItemView>(cx);
13314 });
13315
13316 let fs = FakeFs::new(cx.executor());
13317 fs.insert_tree(
13318 "/root1",
13319 json!({
13320 "one.png": "BINARYDATAHERE",
13321 "two.ipynb": "{ totally a notebook }",
13322 "three.txt": "editing text, sure why not?"
13323 }),
13324 )
13325 .await;
13326 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13327 let (workspace, cx) =
13328 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13329 let worktree_id = project.update(cx, |project, cx| {
13330 project.worktrees(cx).next().unwrap().read(cx).id()
13331 });
13332
13333 let handle = workspace
13334 .update_in(cx, |workspace, window, cx| {
13335 let project_path = (worktree_id, rel_path("one.png"));
13336 workspace.open_path(project_path, None, true, window, cx)
13337 })
13338 .await
13339 .unwrap();
13340
13341 // This _must_ be the second item registered
13342 assert_eq!(
13343 handle.to_any_view().entity_type(),
13344 TypeId::of::<TestAlternatePngItemView>()
13345 );
13346
13347 let handle = workspace
13348 .update_in(cx, |workspace, window, cx| {
13349 let project_path = (worktree_id, rel_path("three.txt"));
13350 workspace.open_path(project_path, None, true, window, cx)
13351 })
13352 .await;
13353 assert!(handle.is_err());
13354 }
13355 }
13356
13357 #[gpui::test]
13358 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13359 init_test(cx);
13360
13361 let fs = FakeFs::new(cx.executor());
13362 let project = Project::test(fs, [], cx).await;
13363 let (workspace, _cx) =
13364 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13365
13366 // Test with status bar shown (default)
13367 workspace.read_with(cx, |workspace, cx| {
13368 let visible = workspace.status_bar_visible(cx);
13369 assert!(visible, "Status bar should be visible by default");
13370 });
13371
13372 // Test with status bar hidden
13373 cx.update_global(|store: &mut SettingsStore, cx| {
13374 store.update_user_settings(cx, |settings| {
13375 settings.status_bar.get_or_insert_default().show = Some(false);
13376 });
13377 });
13378
13379 workspace.read_with(cx, |workspace, cx| {
13380 let visible = workspace.status_bar_visible(cx);
13381 assert!(!visible, "Status bar should be hidden when show is false");
13382 });
13383
13384 // Test with status bar shown explicitly
13385 cx.update_global(|store: &mut SettingsStore, cx| {
13386 store.update_user_settings(cx, |settings| {
13387 settings.status_bar.get_or_insert_default().show = Some(true);
13388 });
13389 });
13390
13391 workspace.read_with(cx, |workspace, cx| {
13392 let visible = workspace.status_bar_visible(cx);
13393 assert!(visible, "Status bar should be visible when show is true");
13394 });
13395 }
13396
13397 #[gpui::test]
13398 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13399 init_test(cx);
13400
13401 let fs = FakeFs::new(cx.executor());
13402 let project = Project::test(fs, [], cx).await;
13403 let (multi_workspace, cx) =
13404 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13405 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13406 let panel = workspace.update_in(cx, |workspace, window, cx| {
13407 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13408 workspace.add_panel(panel.clone(), window, cx);
13409
13410 workspace
13411 .right_dock()
13412 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13413
13414 panel
13415 });
13416
13417 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13418 let item_a = cx.new(TestItem::new);
13419 let item_b = cx.new(TestItem::new);
13420 let item_a_id = item_a.entity_id();
13421 let item_b_id = item_b.entity_id();
13422
13423 pane.update_in(cx, |pane, window, cx| {
13424 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13425 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13426 });
13427
13428 pane.read_with(cx, |pane, _| {
13429 assert_eq!(pane.items_len(), 2);
13430 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13431 });
13432
13433 workspace.update_in(cx, |workspace, window, cx| {
13434 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13435 });
13436
13437 workspace.update_in(cx, |_, window, cx| {
13438 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13439 });
13440
13441 // Assert that the `pane::CloseActiveItem` action is handled at the
13442 // workspace level when one of the dock panels is focused and, in that
13443 // case, the center pane's active item is closed but the focus is not
13444 // moved.
13445 cx.dispatch_action(pane::CloseActiveItem::default());
13446 cx.run_until_parked();
13447
13448 pane.read_with(cx, |pane, _| {
13449 assert_eq!(pane.items_len(), 1);
13450 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13451 });
13452
13453 workspace.update_in(cx, |workspace, window, cx| {
13454 assert!(workspace.right_dock().read(cx).is_open());
13455 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13456 });
13457 }
13458
13459 #[gpui::test]
13460 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13461 init_test(cx);
13462 let fs = FakeFs::new(cx.executor());
13463
13464 let project_a = Project::test(fs.clone(), [], cx).await;
13465 let project_b = Project::test(fs, [], cx).await;
13466
13467 let multi_workspace_handle =
13468 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13469 cx.run_until_parked();
13470
13471 let workspace_a = multi_workspace_handle
13472 .read_with(cx, |mw, _| mw.workspace().clone())
13473 .unwrap();
13474
13475 let _workspace_b = multi_workspace_handle
13476 .update(cx, |mw, window, cx| {
13477 mw.test_add_workspace(project_b, window, cx)
13478 })
13479 .unwrap();
13480
13481 // Switch to workspace A
13482 multi_workspace_handle
13483 .update(cx, |mw, window, cx| {
13484 mw.activate_index(0, window, cx);
13485 })
13486 .unwrap();
13487
13488 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13489
13490 // Add a panel to workspace A's right dock and open the dock
13491 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13492 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13493 workspace.add_panel(panel.clone(), window, cx);
13494 workspace
13495 .right_dock()
13496 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13497 panel
13498 });
13499
13500 // Focus the panel through the workspace (matching existing test pattern)
13501 workspace_a.update_in(cx, |workspace, window, cx| {
13502 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13503 });
13504
13505 // Zoom the panel
13506 panel.update_in(cx, |panel, window, cx| {
13507 panel.set_zoomed(true, window, cx);
13508 });
13509
13510 // Verify the panel is zoomed and the dock is open
13511 workspace_a.update_in(cx, |workspace, window, cx| {
13512 assert!(
13513 workspace.right_dock().read(cx).is_open(),
13514 "dock should be open before switch"
13515 );
13516 assert!(
13517 panel.is_zoomed(window, cx),
13518 "panel should be zoomed before switch"
13519 );
13520 assert!(
13521 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13522 "panel should be focused before switch"
13523 );
13524 });
13525
13526 // Switch to workspace B
13527 multi_workspace_handle
13528 .update(cx, |mw, window, cx| {
13529 mw.activate_index(1, window, cx);
13530 })
13531 .unwrap();
13532 cx.run_until_parked();
13533
13534 // Switch back to workspace A
13535 multi_workspace_handle
13536 .update(cx, |mw, window, cx| {
13537 mw.activate_index(0, window, cx);
13538 })
13539 .unwrap();
13540 cx.run_until_parked();
13541
13542 // Verify the panel is still zoomed and the dock is still open
13543 workspace_a.update_in(cx, |workspace, window, cx| {
13544 assert!(
13545 workspace.right_dock().read(cx).is_open(),
13546 "dock should still be open after switching back"
13547 );
13548 assert!(
13549 panel.is_zoomed(window, cx),
13550 "panel should still be zoomed after switching back"
13551 );
13552 });
13553 }
13554
13555 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13556 pane.read(cx)
13557 .items()
13558 .flat_map(|item| {
13559 item.project_paths(cx)
13560 .into_iter()
13561 .map(|path| path.path.display(PathStyle::local()).into_owned())
13562 })
13563 .collect()
13564 }
13565
13566 pub fn init_test(cx: &mut TestAppContext) {
13567 cx.update(|cx| {
13568 let settings_store = SettingsStore::test(cx);
13569 cx.set_global(settings_store);
13570 theme::init(theme::LoadThemes::JustBase, cx);
13571 });
13572 }
13573
13574 #[gpui::test]
13575 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
13576 use settings::{ThemeName, ThemeSelection};
13577 use theme::SystemAppearance;
13578 use zed_actions::theme::ToggleMode;
13579
13580 init_test(cx);
13581
13582 let fs = FakeFs::new(cx.executor());
13583 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
13584
13585 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
13586 .await;
13587
13588 // Build a test project and workspace view so the test can invoke
13589 // the workspace action handler the same way the UI would.
13590 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
13591 let (workspace, cx) =
13592 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13593
13594 // Seed the settings file with a plain static light theme so the
13595 // first toggle always starts from a known persisted state.
13596 workspace.update_in(cx, |_workspace, _window, cx| {
13597 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
13598 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
13599 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
13600 });
13601 });
13602 cx.executor().advance_clock(Duration::from_millis(200));
13603 cx.run_until_parked();
13604
13605 // Confirm the initial persisted settings contain the static theme
13606 // we just wrote before any toggling happens.
13607 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13608 assert!(settings_text.contains(r#""theme": "One Light""#));
13609
13610 // Toggle once. This should migrate the persisted theme settings
13611 // into light/dark slots and enable system mode.
13612 workspace.update_in(cx, |workspace, window, cx| {
13613 workspace.toggle_theme_mode(&ToggleMode, window, cx);
13614 });
13615 cx.executor().advance_clock(Duration::from_millis(200));
13616 cx.run_until_parked();
13617
13618 // 1. Static -> Dynamic
13619 // this assertion checks theme changed from static to dynamic.
13620 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13621 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
13622 assert_eq!(
13623 parsed["theme"],
13624 serde_json::json!({
13625 "mode": "system",
13626 "light": "One Light",
13627 "dark": "One Dark"
13628 })
13629 );
13630
13631 // 2. Toggle again, suppose it will change the mode to light
13632 workspace.update_in(cx, |workspace, window, cx| {
13633 workspace.toggle_theme_mode(&ToggleMode, window, cx);
13634 });
13635 cx.executor().advance_clock(Duration::from_millis(200));
13636 cx.run_until_parked();
13637
13638 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13639 assert!(settings_text.contains(r#""mode": "light""#));
13640 }
13641
13642 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13643 let item = TestProjectItem::new(id, path, cx);
13644 item.update(cx, |item, _| {
13645 item.is_dirty = true;
13646 });
13647 item
13648 }
13649
13650 #[gpui::test]
13651 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13652 cx: &mut gpui::TestAppContext,
13653 ) {
13654 init_test(cx);
13655 let fs = FakeFs::new(cx.executor());
13656
13657 let project = Project::test(fs, [], cx).await;
13658 let (workspace, cx) =
13659 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13660
13661 let panel = workspace.update_in(cx, |workspace, window, cx| {
13662 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13663 workspace.add_panel(panel.clone(), window, cx);
13664 workspace
13665 .right_dock()
13666 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13667 panel
13668 });
13669
13670 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13671 pane.update_in(cx, |pane, window, cx| {
13672 let item = cx.new(TestItem::new);
13673 pane.add_item(Box::new(item), true, true, None, window, cx);
13674 });
13675
13676 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13677 // mirrors the real-world flow and avoids side effects from directly
13678 // focusing the panel while the center pane is active.
13679 workspace.update_in(cx, |workspace, window, cx| {
13680 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13681 });
13682
13683 panel.update_in(cx, |panel, window, cx| {
13684 panel.set_zoomed(true, window, cx);
13685 });
13686
13687 workspace.update_in(cx, |workspace, window, cx| {
13688 assert!(workspace.right_dock().read(cx).is_open());
13689 assert!(panel.is_zoomed(window, cx));
13690 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13691 });
13692
13693 // Simulate a spurious pane::Event::Focus on the center pane while the
13694 // panel still has focus. This mirrors what happens during macOS window
13695 // activation: the center pane fires a focus event even though actual
13696 // focus remains on the dock panel.
13697 pane.update_in(cx, |_, _, cx| {
13698 cx.emit(pane::Event::Focus);
13699 });
13700
13701 // The dock must remain open because the panel had focus at the time the
13702 // event was processed. Before the fix, dock_to_preserve was None for
13703 // panels that don't implement pane(), causing the dock to close.
13704 workspace.update_in(cx, |workspace, window, cx| {
13705 assert!(
13706 workspace.right_dock().read(cx).is_open(),
13707 "Dock should stay open when its zoomed panel (without pane()) still has focus"
13708 );
13709 assert!(panel.is_zoomed(window, cx));
13710 });
13711 }
13712}