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 MouseUpEvent, PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful,
58 Subscription, SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle,
59 WindowId, WindowOptions, actions, canvas, deferred, 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 left_drawer: Option<Drawer>,
1296 right_drawer: Option<Drawer>,
1297 panes: Vec<Entity<Pane>>,
1298 active_worktree_override: Option<WorktreeId>,
1299 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1300 active_pane: Entity<Pane>,
1301 last_active_center_pane: Option<WeakEntity<Pane>>,
1302 last_active_view_id: Option<proto::ViewId>,
1303 status_bar: Entity<StatusBar>,
1304 pub(crate) modal_layer: Entity<ModalLayer>,
1305 toast_layer: Entity<ToastLayer>,
1306 titlebar_item: Option<AnyView>,
1307 notifications: Notifications,
1308 suppressed_notifications: HashSet<NotificationId>,
1309 project: Entity<Project>,
1310 follower_states: HashMap<CollaboratorId, FollowerState>,
1311 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1312 window_edited: bool,
1313 last_window_title: Option<String>,
1314 dirty_items: HashMap<EntityId, Subscription>,
1315 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1316 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1317 database_id: Option<WorkspaceId>,
1318 app_state: Arc<AppState>,
1319 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1320 _subscriptions: Vec<Subscription>,
1321 _apply_leader_updates: Task<Result<()>>,
1322 _observe_current_user: Task<Result<()>>,
1323 _schedule_serialize_workspace: Option<Task<()>>,
1324 _serialize_workspace_task: Option<Task<()>>,
1325 _schedule_serialize_ssh_paths: Option<Task<()>>,
1326 pane_history_timestamp: Arc<AtomicUsize>,
1327 bounds: Bounds<Pixels>,
1328 pub centered_layout: bool,
1329 bounds_save_task_queued: Option<Task<()>>,
1330 on_prompt_for_new_path: Option<PromptForNewPath>,
1331 on_prompt_for_open_path: Option<PromptForOpenPath>,
1332 terminal_provider: Option<Box<dyn TerminalProvider>>,
1333 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1334 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1335 _items_serializer: Task<Result<()>>,
1336 session_id: Option<String>,
1337 scheduled_tasks: Vec<Task<()>>,
1338 last_open_dock_positions: Vec<DockPosition>,
1339 removing: bool,
1340 _panels_task: Option<Task<Result<()>>>,
1341}
1342
1343impl EventEmitter<Event> for Workspace {}
1344
1345#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1346pub struct ViewId {
1347 pub creator: CollaboratorId,
1348 pub id: u64,
1349}
1350
1351pub struct FollowerState {
1352 center_pane: Entity<Pane>,
1353 dock_pane: Option<Entity<Pane>>,
1354 active_view_id: Option<ViewId>,
1355 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1356}
1357
1358struct FollowerView {
1359 view: Box<dyn FollowableItemHandle>,
1360 location: Option<proto::PanelId>,
1361}
1362
1363impl Workspace {
1364 pub fn new(
1365 workspace_id: Option<WorkspaceId>,
1366 project: Entity<Project>,
1367 app_state: Arc<AppState>,
1368 window: &mut Window,
1369 cx: &mut Context<Self>,
1370 ) -> Self {
1371 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1372 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1373 if let TrustedWorktreesEvent::Trusted(..) = e {
1374 // Do not persist auto trusted worktrees
1375 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1376 worktrees_store.update(cx, |worktrees_store, cx| {
1377 worktrees_store.schedule_serialization(
1378 cx,
1379 |new_trusted_worktrees, cx| {
1380 let timeout =
1381 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1382 cx.background_spawn(async move {
1383 timeout.await;
1384 persistence::DB
1385 .save_trusted_worktrees(new_trusted_worktrees)
1386 .await
1387 .log_err();
1388 })
1389 },
1390 )
1391 });
1392 }
1393 }
1394 })
1395 .detach();
1396
1397 cx.observe_global::<SettingsStore>(|_, cx| {
1398 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1399 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1400 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1401 trusted_worktrees.auto_trust_all(cx);
1402 })
1403 }
1404 }
1405 })
1406 .detach();
1407 }
1408
1409 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1410 match event {
1411 project::Event::RemoteIdChanged(_) => {
1412 this.update_window_title(window, cx);
1413 }
1414
1415 project::Event::CollaboratorLeft(peer_id) => {
1416 this.collaborator_left(*peer_id, window, cx);
1417 }
1418
1419 &project::Event::WorktreeRemoved(id) | &project::Event::WorktreeAdded(id) => {
1420 this.update_window_title(window, cx);
1421 if this
1422 .project()
1423 .read(cx)
1424 .worktree_for_id(id, cx)
1425 .is_some_and(|wt| wt.read(cx).is_visible())
1426 {
1427 this.serialize_workspace(window, cx);
1428 this.update_history(cx);
1429 }
1430 }
1431 project::Event::WorktreeUpdatedEntries(..) => {
1432 this.update_window_title(window, cx);
1433 this.serialize_workspace(window, cx);
1434 }
1435
1436 project::Event::DisconnectedFromHost => {
1437 this.update_window_edited(window, cx);
1438 let leaders_to_unfollow =
1439 this.follower_states.keys().copied().collect::<Vec<_>>();
1440 for leader_id in leaders_to_unfollow {
1441 this.unfollow(leader_id, window, cx);
1442 }
1443 }
1444
1445 project::Event::DisconnectedFromRemote {
1446 server_not_running: _,
1447 } => {
1448 this.update_window_edited(window, cx);
1449 }
1450
1451 project::Event::Closed => {
1452 window.remove_window();
1453 }
1454
1455 project::Event::DeletedEntry(_, entry_id) => {
1456 for pane in this.panes.iter() {
1457 pane.update(cx, |pane, cx| {
1458 pane.handle_deleted_project_item(*entry_id, window, cx)
1459 });
1460 }
1461 }
1462
1463 project::Event::Toast {
1464 notification_id,
1465 message,
1466 link,
1467 } => this.show_notification(
1468 NotificationId::named(notification_id.clone()),
1469 cx,
1470 |cx| {
1471 let mut notification = MessageNotification::new(message.clone(), cx);
1472 if let Some(link) = link {
1473 notification = notification
1474 .more_info_message(link.label)
1475 .more_info_url(link.url);
1476 }
1477
1478 cx.new(|_| notification)
1479 },
1480 ),
1481
1482 project::Event::HideToast { notification_id } => {
1483 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1484 }
1485
1486 project::Event::LanguageServerPrompt(request) => {
1487 struct LanguageServerPrompt;
1488
1489 this.show_notification(
1490 NotificationId::composite::<LanguageServerPrompt>(request.id),
1491 cx,
1492 |cx| {
1493 cx.new(|cx| {
1494 notifications::LanguageServerPrompt::new(request.clone(), cx)
1495 })
1496 },
1497 );
1498 }
1499
1500 project::Event::AgentLocationChanged => {
1501 this.handle_agent_location_changed(window, cx)
1502 }
1503
1504 _ => {}
1505 }
1506 cx.notify()
1507 })
1508 .detach();
1509
1510 cx.subscribe_in(
1511 &project.read(cx).breakpoint_store(),
1512 window,
1513 |workspace, _, event, window, cx| match event {
1514 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1515 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1516 workspace.serialize_workspace(window, cx);
1517 }
1518 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1519 },
1520 )
1521 .detach();
1522 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1523 cx.subscribe_in(
1524 &toolchain_store,
1525 window,
1526 |workspace, _, event, window, cx| match event {
1527 ToolchainStoreEvent::CustomToolchainsModified => {
1528 workspace.serialize_workspace(window, cx);
1529 }
1530 _ => {}
1531 },
1532 )
1533 .detach();
1534 }
1535
1536 cx.on_focus_lost(window, |this, window, cx| {
1537 let focus_handle = this.focus_handle(cx);
1538 window.focus(&focus_handle, cx);
1539 })
1540 .detach();
1541
1542 let weak_handle = cx.entity().downgrade();
1543 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1544
1545 let center_pane = cx.new(|cx| {
1546 let mut center_pane = Pane::new(
1547 weak_handle.clone(),
1548 project.clone(),
1549 pane_history_timestamp.clone(),
1550 None,
1551 NewFile.boxed_clone(),
1552 true,
1553 window,
1554 cx,
1555 );
1556 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1557 center_pane.set_should_display_welcome_page(true);
1558 center_pane
1559 });
1560 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1561 .detach();
1562
1563 window.focus(¢er_pane.focus_handle(cx), cx);
1564
1565 cx.emit(Event::PaneAdded(center_pane.clone()));
1566
1567 let any_window_handle = window.window_handle();
1568 app_state.workspace_store.update(cx, |store, _| {
1569 store
1570 .workspaces
1571 .insert((any_window_handle, weak_handle.clone()));
1572 });
1573
1574 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1575 let mut connection_status = app_state.client.status();
1576 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1577 current_user.next().await;
1578 connection_status.next().await;
1579 let mut stream =
1580 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1581
1582 while stream.recv().await.is_some() {
1583 this.update(cx, |_, cx| cx.notify())?;
1584 }
1585 anyhow::Ok(())
1586 });
1587
1588 // All leader updates are enqueued and then processed in a single task, so
1589 // that each asynchronous operation can be run in order.
1590 let (leader_updates_tx, mut leader_updates_rx) =
1591 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1592 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1593 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1594 Self::process_leader_update(&this, leader_id, update, cx)
1595 .await
1596 .log_err();
1597 }
1598
1599 Ok(())
1600 });
1601
1602 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1603 let modal_layer = cx.new(|_| ModalLayer::new());
1604 let toast_layer = cx.new(|_| ToastLayer::new());
1605 cx.subscribe(
1606 &modal_layer,
1607 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1608 cx.emit(Event::ModalOpened);
1609 },
1610 )
1611 .detach();
1612
1613 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1614 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1615 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1616 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1617 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1618 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1619 let status_bar = cx.new(|cx| {
1620 let mut status_bar = StatusBar::new(¢er_pane.clone(), window, cx);
1621 status_bar.add_left_item(left_dock_buttons, window, cx);
1622 status_bar.add_right_item(right_dock_buttons, window, cx);
1623 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1624 status_bar
1625 });
1626
1627 let session_id = app_state.session.read(cx).id().to_owned();
1628
1629 let mut active_call = None;
1630 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1631 let subscriptions =
1632 vec![
1633 call.0
1634 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1635 ];
1636 active_call = Some((call, subscriptions));
1637 }
1638
1639 let (serializable_items_tx, serializable_items_rx) =
1640 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1641 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1642 Self::serialize_items(&this, serializable_items_rx, cx).await
1643 });
1644
1645 let subscriptions = vec![
1646 cx.observe_window_activation(window, Self::on_window_activation_changed),
1647 cx.observe_window_bounds(window, move |this, window, cx| {
1648 if this.bounds_save_task_queued.is_some() {
1649 return;
1650 }
1651 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1652 cx.background_executor()
1653 .timer(Duration::from_millis(100))
1654 .await;
1655 this.update_in(cx, |this, window, cx| {
1656 this.save_window_bounds(window, cx).detach();
1657 this.bounds_save_task_queued.take();
1658 })
1659 .ok();
1660 }));
1661 cx.notify();
1662 }),
1663 cx.observe_window_appearance(window, |_, window, cx| {
1664 let window_appearance = window.appearance();
1665
1666 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1667
1668 GlobalTheme::reload_theme(cx);
1669 GlobalTheme::reload_icon_theme(cx);
1670 }),
1671 cx.on_release({
1672 let weak_handle = weak_handle.clone();
1673 move |this, cx| {
1674 this.app_state.workspace_store.update(cx, move |store, _| {
1675 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1676 })
1677 }
1678 }),
1679 ];
1680
1681 cx.defer_in(window, move |this, window, cx| {
1682 this.update_window_title(window, cx);
1683 this.show_initial_notifications(cx);
1684 });
1685
1686 let mut center = PaneGroup::new(center_pane.clone());
1687 center.set_is_center(true);
1688 center.mark_positions(cx);
1689
1690 Workspace {
1691 weak_self: weak_handle.clone(),
1692 zoomed: None,
1693 zoomed_position: None,
1694 previous_dock_drag_coordinates: None,
1695 center,
1696 panes: vec![center_pane.clone()],
1697 panes_by_item: Default::default(),
1698 active_pane: center_pane.clone(),
1699 last_active_center_pane: Some(center_pane.downgrade()),
1700 last_active_view_id: None,
1701 status_bar,
1702 modal_layer,
1703 toast_layer,
1704 titlebar_item: None,
1705 active_worktree_override: None,
1706 notifications: Notifications::default(),
1707 suppressed_notifications: HashSet::default(),
1708 left_dock,
1709 bottom_dock,
1710 right_dock,
1711 left_drawer: None,
1712 right_drawer: None,
1713 _panels_task: None,
1714 project: project.clone(),
1715 follower_states: Default::default(),
1716 last_leaders_by_pane: Default::default(),
1717 dispatching_keystrokes: Default::default(),
1718 window_edited: false,
1719 last_window_title: None,
1720 dirty_items: Default::default(),
1721 active_call,
1722 database_id: workspace_id,
1723 app_state,
1724 _observe_current_user,
1725 _apply_leader_updates,
1726 _schedule_serialize_workspace: None,
1727 _serialize_workspace_task: None,
1728 _schedule_serialize_ssh_paths: None,
1729 leader_updates_tx,
1730 _subscriptions: subscriptions,
1731 pane_history_timestamp,
1732 workspace_actions: Default::default(),
1733 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1734 bounds: Default::default(),
1735 centered_layout: false,
1736 bounds_save_task_queued: None,
1737 on_prompt_for_new_path: None,
1738 on_prompt_for_open_path: None,
1739 terminal_provider: None,
1740 debugger_provider: None,
1741 serializable_items_tx,
1742 _items_serializer,
1743 session_id: Some(session_id),
1744
1745 scheduled_tasks: Vec::new(),
1746 last_open_dock_positions: Vec::new(),
1747 removing: false,
1748 }
1749 }
1750
1751 pub fn new_local(
1752 abs_paths: Vec<PathBuf>,
1753 app_state: Arc<AppState>,
1754 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1755 env: Option<HashMap<String, String>>,
1756 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1757 activate: bool,
1758 cx: &mut App,
1759 ) -> Task<anyhow::Result<OpenResult>> {
1760 let project_handle = Project::local(
1761 app_state.client.clone(),
1762 app_state.node_runtime.clone(),
1763 app_state.user_store.clone(),
1764 app_state.languages.clone(),
1765 app_state.fs.clone(),
1766 env,
1767 Default::default(),
1768 cx,
1769 );
1770
1771 cx.spawn(async move |cx| {
1772 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1773 for path in abs_paths.into_iter() {
1774 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1775 paths_to_open.push(canonical)
1776 } else {
1777 paths_to_open.push(path)
1778 }
1779 }
1780
1781 let serialized_workspace =
1782 persistence::DB.workspace_for_roots(paths_to_open.as_slice());
1783
1784 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1785 paths_to_open = paths.ordered_paths().cloned().collect();
1786 if !paths.is_lexicographically_ordered() {
1787 project_handle.update(cx, |project, cx| {
1788 project.set_worktrees_reordered(true, cx);
1789 });
1790 }
1791 }
1792
1793 // Get project paths for all of the abs_paths
1794 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1795 Vec::with_capacity(paths_to_open.len());
1796
1797 for path in paths_to_open.into_iter() {
1798 if let Some((_, project_entry)) = cx
1799 .update(|cx| {
1800 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1801 })
1802 .await
1803 .log_err()
1804 {
1805 project_paths.push((path, Some(project_entry)));
1806 } else {
1807 project_paths.push((path, None));
1808 }
1809 }
1810
1811 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1812 serialized_workspace.id
1813 } else {
1814 DB.next_id().await.unwrap_or_else(|_| Default::default())
1815 };
1816
1817 let toolchains = DB.toolchains(workspace_id).await?;
1818
1819 for (toolchain, worktree_path, path) in toolchains {
1820 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1821 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1822 this.find_worktree(&worktree_path, cx)
1823 .and_then(|(worktree, rel_path)| {
1824 if rel_path.is_empty() {
1825 Some(worktree.read(cx).id())
1826 } else {
1827 None
1828 }
1829 })
1830 }) else {
1831 // We did not find a worktree with a given path, but that's whatever.
1832 continue;
1833 };
1834 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1835 continue;
1836 }
1837
1838 project_handle
1839 .update(cx, |this, cx| {
1840 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1841 })
1842 .await;
1843 }
1844 if let Some(workspace) = serialized_workspace.as_ref() {
1845 project_handle.update(cx, |this, cx| {
1846 for (scope, toolchains) in &workspace.user_toolchains {
1847 for toolchain in toolchains {
1848 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1849 }
1850 }
1851 });
1852 }
1853
1854 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1855 if let Some(window) = requesting_window {
1856 let centered_layout = serialized_workspace
1857 .as_ref()
1858 .map(|w| w.centered_layout)
1859 .unwrap_or(false);
1860
1861 let workspace = window.update(cx, |multi_workspace, window, cx| {
1862 let workspace = cx.new(|cx| {
1863 let mut workspace = Workspace::new(
1864 Some(workspace_id),
1865 project_handle.clone(),
1866 app_state.clone(),
1867 window,
1868 cx,
1869 );
1870
1871 workspace.centered_layout = centered_layout;
1872
1873 // Call init callback to add items before window renders
1874 if let Some(init) = init {
1875 init(&mut workspace, window, cx);
1876 }
1877
1878 workspace
1879 });
1880 if activate {
1881 multi_workspace.activate(workspace.clone(), cx);
1882 } else {
1883 multi_workspace.add_workspace(workspace.clone(), cx);
1884 }
1885 workspace
1886 })?;
1887 (window, workspace)
1888 } else {
1889 let window_bounds_override = window_bounds_env_override();
1890
1891 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1892 (Some(WindowBounds::Windowed(bounds)), None)
1893 } else if let Some(workspace) = serialized_workspace.as_ref()
1894 && let Some(display) = workspace.display
1895 && let Some(bounds) = workspace.window_bounds.as_ref()
1896 {
1897 // Reopening an existing workspace - restore its saved bounds
1898 (Some(bounds.0), Some(display))
1899 } else if let Some((display, bounds)) =
1900 persistence::read_default_window_bounds()
1901 {
1902 // New or empty workspace - use the last known window bounds
1903 (Some(bounds), Some(display))
1904 } else {
1905 // New window - let GPUI's default_bounds() handle cascading
1906 (None, None)
1907 };
1908
1909 // Use the serialized workspace to construct the new window
1910 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1911 options.window_bounds = window_bounds;
1912 let centered_layout = serialized_workspace
1913 .as_ref()
1914 .map(|w| w.centered_layout)
1915 .unwrap_or(false);
1916 let window = cx.open_window(options, {
1917 let app_state = app_state.clone();
1918 let project_handle = project_handle.clone();
1919 move |window, cx| {
1920 let workspace = cx.new(|cx| {
1921 let mut workspace = Workspace::new(
1922 Some(workspace_id),
1923 project_handle,
1924 app_state,
1925 window,
1926 cx,
1927 );
1928 workspace.centered_layout = centered_layout;
1929
1930 // Call init callback to add items before window renders
1931 if let Some(init) = init {
1932 init(&mut workspace, window, cx);
1933 }
1934
1935 workspace
1936 });
1937 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1938 }
1939 })?;
1940 let workspace =
1941 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
1942 multi_workspace.workspace().clone()
1943 })?;
1944 (window, workspace)
1945 };
1946
1947 notify_if_database_failed(window, cx);
1948 // Check if this is an empty workspace (no paths to open)
1949 // An empty workspace is one where project_paths is empty
1950 let is_empty_workspace = project_paths.is_empty();
1951 // Check if serialized workspace has paths before it's moved
1952 let serialized_workspace_has_paths = serialized_workspace
1953 .as_ref()
1954 .map(|ws| !ws.paths.is_empty())
1955 .unwrap_or(false);
1956
1957 let opened_items = window
1958 .update(cx, |_, window, cx| {
1959 workspace.update(cx, |_workspace: &mut Workspace, cx| {
1960 open_items(serialized_workspace, project_paths, window, cx)
1961 })
1962 })?
1963 .await
1964 .unwrap_or_default();
1965
1966 // Restore default dock state for empty workspaces
1967 // Only restore if:
1968 // 1. This is an empty workspace (no paths), AND
1969 // 2. The serialized workspace either doesn't exist or has no paths
1970 if is_empty_workspace && !serialized_workspace_has_paths {
1971 if let Some(default_docks) = persistence::read_default_dock_state() {
1972 window
1973 .update(cx, |_, window, cx| {
1974 workspace.update(cx, |workspace, cx| {
1975 for (dock, serialized_dock) in [
1976 (&workspace.right_dock, &default_docks.right),
1977 (&workspace.left_dock, &default_docks.left),
1978 (&workspace.bottom_dock, &default_docks.bottom),
1979 ] {
1980 dock.update(cx, |dock, cx| {
1981 dock.serialized_dock = Some(serialized_dock.clone());
1982 dock.restore_state(window, cx);
1983 });
1984 }
1985 cx.notify();
1986 });
1987 })
1988 .log_err();
1989 }
1990 }
1991
1992 window
1993 .update(cx, |_, _window, cx| {
1994 workspace.update(cx, |this: &mut Workspace, cx| {
1995 this.update_history(cx);
1996 });
1997 })
1998 .log_err();
1999 Ok(OpenResult {
2000 window,
2001 workspace,
2002 opened_items,
2003 })
2004 })
2005 }
2006
2007 pub fn weak_handle(&self) -> WeakEntity<Self> {
2008 self.weak_self.clone()
2009 }
2010
2011 pub fn left_dock(&self) -> &Entity<Dock> {
2012 &self.left_dock
2013 }
2014
2015 pub fn bottom_dock(&self) -> &Entity<Dock> {
2016 &self.bottom_dock
2017 }
2018
2019 pub fn set_bottom_dock_layout(
2020 &mut self,
2021 layout: BottomDockLayout,
2022 window: &mut Window,
2023 cx: &mut Context<Self>,
2024 ) {
2025 let fs = self.project().read(cx).fs();
2026 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2027 content.workspace.bottom_dock_layout = Some(layout);
2028 });
2029
2030 cx.notify();
2031 self.serialize_workspace(window, cx);
2032 }
2033
2034 pub fn right_dock(&self) -> &Entity<Dock> {
2035 &self.right_dock
2036 }
2037
2038 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2039 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2040 }
2041
2042 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2043 let left_dock = self.left_dock.read(cx);
2044 let left_visible = left_dock.is_open();
2045 let left_active_panel = left_dock
2046 .active_panel()
2047 .map(|panel| panel.persistent_name().to_string());
2048 // `zoomed_position` is kept in sync with individual panel zoom state
2049 // by the dock code in `Dock::new` and `Dock::add_panel`.
2050 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2051
2052 let right_dock = self.right_dock.read(cx);
2053 let right_visible = right_dock.is_open();
2054 let right_active_panel = right_dock
2055 .active_panel()
2056 .map(|panel| panel.persistent_name().to_string());
2057 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2058
2059 let bottom_dock = self.bottom_dock.read(cx);
2060 let bottom_visible = bottom_dock.is_open();
2061 let bottom_active_panel = bottom_dock
2062 .active_panel()
2063 .map(|panel| panel.persistent_name().to_string());
2064 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2065
2066 DockStructure {
2067 left: DockData {
2068 visible: left_visible,
2069 active_panel: left_active_panel,
2070 zoom: left_dock_zoom,
2071 },
2072 right: DockData {
2073 visible: right_visible,
2074 active_panel: right_active_panel,
2075 zoom: right_dock_zoom,
2076 },
2077 bottom: DockData {
2078 visible: bottom_visible,
2079 active_panel: bottom_active_panel,
2080 zoom: bottom_dock_zoom,
2081 },
2082 }
2083 }
2084
2085 pub fn set_dock_structure(
2086 &self,
2087 docks: DockStructure,
2088 window: &mut Window,
2089 cx: &mut Context<Self>,
2090 ) {
2091 for (dock, data) in [
2092 (&self.left_dock, docks.left),
2093 (&self.bottom_dock, docks.bottom),
2094 (&self.right_dock, docks.right),
2095 ] {
2096 dock.update(cx, |dock, cx| {
2097 dock.serialized_dock = Some(data);
2098 dock.restore_state(window, cx);
2099 });
2100 }
2101 }
2102
2103 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2104 self.items(cx)
2105 .filter_map(|item| {
2106 let project_path = item.project_path(cx)?;
2107 self.project.read(cx).absolute_path(&project_path, cx)
2108 })
2109 .collect()
2110 }
2111
2112 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2113 match position {
2114 DockPosition::Left => &self.left_dock,
2115 DockPosition::Bottom => &self.bottom_dock,
2116 DockPosition::Right => &self.right_dock,
2117 }
2118 }
2119
2120 pub fn is_edited(&self) -> bool {
2121 self.window_edited
2122 }
2123
2124 pub fn add_panel<T: Panel>(
2125 &mut self,
2126 panel: Entity<T>,
2127 window: &mut Window,
2128 cx: &mut Context<Self>,
2129 ) {
2130 let focus_handle = panel.panel_focus_handle(cx);
2131 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2132 .detach();
2133
2134 let dock_position = panel.position(window, cx);
2135 let dock = self.dock_at_position(dock_position);
2136 let any_panel = panel.to_any();
2137
2138 dock.update(cx, |dock, cx| {
2139 dock.add_panel(panel, self.weak_self.clone(), window, cx)
2140 });
2141
2142 cx.emit(Event::PanelAdded(any_panel));
2143 }
2144
2145 pub fn remove_panel<T: Panel>(
2146 &mut self,
2147 panel: &Entity<T>,
2148 window: &mut Window,
2149 cx: &mut Context<Self>,
2150 ) {
2151 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2152 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2153 }
2154 }
2155
2156 pub fn status_bar(&self) -> &Entity<StatusBar> {
2157 &self.status_bar
2158 }
2159
2160 pub fn status_bar_visible(&self, cx: &App) -> bool {
2161 StatusBarSettings::get_global(cx).show
2162 }
2163
2164 pub fn app_state(&self) -> &Arc<AppState> {
2165 &self.app_state
2166 }
2167
2168 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2169 self._panels_task = Some(task);
2170 }
2171
2172 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2173 self._panels_task.take()
2174 }
2175
2176 pub fn user_store(&self) -> &Entity<UserStore> {
2177 &self.app_state.user_store
2178 }
2179
2180 pub fn project(&self) -> &Entity<Project> {
2181 &self.project
2182 }
2183
2184 pub fn path_style(&self, cx: &App) -> PathStyle {
2185 self.project.read(cx).path_style(cx)
2186 }
2187
2188 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2189 let mut history: HashMap<EntityId, usize> = HashMap::default();
2190
2191 for pane_handle in &self.panes {
2192 let pane = pane_handle.read(cx);
2193
2194 for entry in pane.activation_history() {
2195 history.insert(
2196 entry.entity_id,
2197 history
2198 .get(&entry.entity_id)
2199 .cloned()
2200 .unwrap_or(0)
2201 .max(entry.timestamp),
2202 );
2203 }
2204 }
2205
2206 history
2207 }
2208
2209 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2210 let mut recent_item: Option<Entity<T>> = None;
2211 let mut recent_timestamp = 0;
2212 for pane_handle in &self.panes {
2213 let pane = pane_handle.read(cx);
2214 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2215 pane.items().map(|item| (item.item_id(), item)).collect();
2216 for entry in pane.activation_history() {
2217 if entry.timestamp > recent_timestamp
2218 && let Some(&item) = item_map.get(&entry.entity_id)
2219 && let Some(typed_item) = item.act_as::<T>(cx)
2220 {
2221 recent_timestamp = entry.timestamp;
2222 recent_item = Some(typed_item);
2223 }
2224 }
2225 }
2226 recent_item
2227 }
2228
2229 pub fn recent_navigation_history_iter(
2230 &self,
2231 cx: &App,
2232 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2233 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2234 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2235
2236 for pane in &self.panes {
2237 let pane = pane.read(cx);
2238
2239 pane.nav_history()
2240 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2241 if let Some(fs_path) = &fs_path {
2242 abs_paths_opened
2243 .entry(fs_path.clone())
2244 .or_default()
2245 .insert(project_path.clone());
2246 }
2247 let timestamp = entry.timestamp;
2248 match history.entry(project_path) {
2249 hash_map::Entry::Occupied(mut entry) => {
2250 let (_, old_timestamp) = entry.get();
2251 if ×tamp > old_timestamp {
2252 entry.insert((fs_path, timestamp));
2253 }
2254 }
2255 hash_map::Entry::Vacant(entry) => {
2256 entry.insert((fs_path, timestamp));
2257 }
2258 }
2259 });
2260
2261 if let Some(item) = pane.active_item()
2262 && let Some(project_path) = item.project_path(cx)
2263 {
2264 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2265
2266 if let Some(fs_path) = &fs_path {
2267 abs_paths_opened
2268 .entry(fs_path.clone())
2269 .or_default()
2270 .insert(project_path.clone());
2271 }
2272
2273 history.insert(project_path, (fs_path, std::usize::MAX));
2274 }
2275 }
2276
2277 history
2278 .into_iter()
2279 .sorted_by_key(|(_, (_, order))| *order)
2280 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2281 .rev()
2282 .filter(move |(history_path, abs_path)| {
2283 let latest_project_path_opened = abs_path
2284 .as_ref()
2285 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2286 .and_then(|project_paths| {
2287 project_paths
2288 .iter()
2289 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2290 });
2291
2292 latest_project_path_opened.is_none_or(|path| path == history_path)
2293 })
2294 }
2295
2296 pub fn recent_navigation_history(
2297 &self,
2298 limit: Option<usize>,
2299 cx: &App,
2300 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2301 self.recent_navigation_history_iter(cx)
2302 .take(limit.unwrap_or(usize::MAX))
2303 .collect()
2304 }
2305
2306 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2307 for pane in &self.panes {
2308 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2309 }
2310 }
2311
2312 fn navigate_history(
2313 &mut self,
2314 pane: WeakEntity<Pane>,
2315 mode: NavigationMode,
2316 window: &mut Window,
2317 cx: &mut Context<Workspace>,
2318 ) -> Task<Result<()>> {
2319 self.navigate_history_impl(
2320 pane,
2321 mode,
2322 window,
2323 &mut |history, cx| history.pop(mode, cx),
2324 cx,
2325 )
2326 }
2327
2328 fn navigate_tag_history(
2329 &mut self,
2330 pane: WeakEntity<Pane>,
2331 mode: TagNavigationMode,
2332 window: &mut Window,
2333 cx: &mut Context<Workspace>,
2334 ) -> Task<Result<()>> {
2335 self.navigate_history_impl(
2336 pane,
2337 NavigationMode::Normal,
2338 window,
2339 &mut |history, _cx| history.pop_tag(mode),
2340 cx,
2341 )
2342 }
2343
2344 fn navigate_history_impl(
2345 &mut self,
2346 pane: WeakEntity<Pane>,
2347 mode: NavigationMode,
2348 window: &mut Window,
2349 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2350 cx: &mut Context<Workspace>,
2351 ) -> Task<Result<()>> {
2352 let to_load = if let Some(pane) = pane.upgrade() {
2353 pane.update(cx, |pane, cx| {
2354 window.focus(&pane.focus_handle(cx), cx);
2355 loop {
2356 // Retrieve the weak item handle from the history.
2357 let entry = cb(pane.nav_history_mut(), cx)?;
2358
2359 // If the item is still present in this pane, then activate it.
2360 if let Some(index) = entry
2361 .item
2362 .upgrade()
2363 .and_then(|v| pane.index_for_item(v.as_ref()))
2364 {
2365 let prev_active_item_index = pane.active_item_index();
2366 pane.nav_history_mut().set_mode(mode);
2367 pane.activate_item(index, true, true, window, cx);
2368 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2369
2370 let mut navigated = prev_active_item_index != pane.active_item_index();
2371 if let Some(data) = entry.data {
2372 navigated |= pane.active_item()?.navigate(data, window, cx);
2373 }
2374
2375 if navigated {
2376 break None;
2377 }
2378 } else {
2379 // If the item is no longer present in this pane, then retrieve its
2380 // path info in order to reopen it.
2381 break pane
2382 .nav_history()
2383 .path_for_item(entry.item.id())
2384 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2385 }
2386 }
2387 })
2388 } else {
2389 None
2390 };
2391
2392 if let Some((project_path, abs_path, entry)) = to_load {
2393 // If the item was no longer present, then load it again from its previous path, first try the local path
2394 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2395
2396 cx.spawn_in(window, async move |workspace, cx| {
2397 let open_by_project_path = open_by_project_path.await;
2398 let mut navigated = false;
2399 match open_by_project_path
2400 .with_context(|| format!("Navigating to {project_path:?}"))
2401 {
2402 Ok((project_entry_id, build_item)) => {
2403 let prev_active_item_id = pane.update(cx, |pane, _| {
2404 pane.nav_history_mut().set_mode(mode);
2405 pane.active_item().map(|p| p.item_id())
2406 })?;
2407
2408 pane.update_in(cx, |pane, window, cx| {
2409 let item = pane.open_item(
2410 project_entry_id,
2411 project_path,
2412 true,
2413 entry.is_preview,
2414 true,
2415 None,
2416 window, cx,
2417 build_item,
2418 );
2419 navigated |= Some(item.item_id()) != prev_active_item_id;
2420 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2421 if let Some(data) = entry.data {
2422 navigated |= item.navigate(data, window, cx);
2423 }
2424 })?;
2425 }
2426 Err(open_by_project_path_e) => {
2427 // Fall back to opening by abs path, in case an external file was opened and closed,
2428 // and its worktree is now dropped
2429 if let Some(abs_path) = abs_path {
2430 let prev_active_item_id = pane.update(cx, |pane, _| {
2431 pane.nav_history_mut().set_mode(mode);
2432 pane.active_item().map(|p| p.item_id())
2433 })?;
2434 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2435 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2436 })?;
2437 match open_by_abs_path
2438 .await
2439 .with_context(|| format!("Navigating to {abs_path:?}"))
2440 {
2441 Ok(item) => {
2442 pane.update_in(cx, |pane, window, cx| {
2443 navigated |= Some(item.item_id()) != prev_active_item_id;
2444 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2445 if let Some(data) = entry.data {
2446 navigated |= item.navigate(data, window, cx);
2447 }
2448 })?;
2449 }
2450 Err(open_by_abs_path_e) => {
2451 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2452 }
2453 }
2454 }
2455 }
2456 }
2457
2458 if !navigated {
2459 workspace
2460 .update_in(cx, |workspace, window, cx| {
2461 Self::navigate_history(workspace, pane, mode, window, cx)
2462 })?
2463 .await?;
2464 }
2465
2466 Ok(())
2467 })
2468 } else {
2469 Task::ready(Ok(()))
2470 }
2471 }
2472
2473 pub fn go_back(
2474 &mut self,
2475 pane: WeakEntity<Pane>,
2476 window: &mut Window,
2477 cx: &mut Context<Workspace>,
2478 ) -> Task<Result<()>> {
2479 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2480 }
2481
2482 pub fn go_forward(
2483 &mut self,
2484 pane: WeakEntity<Pane>,
2485 window: &mut Window,
2486 cx: &mut Context<Workspace>,
2487 ) -> Task<Result<()>> {
2488 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2489 }
2490
2491 pub fn reopen_closed_item(
2492 &mut self,
2493 window: &mut Window,
2494 cx: &mut Context<Workspace>,
2495 ) -> Task<Result<()>> {
2496 self.navigate_history(
2497 self.active_pane().downgrade(),
2498 NavigationMode::ReopeningClosedItem,
2499 window,
2500 cx,
2501 )
2502 }
2503
2504 pub fn client(&self) -> &Arc<Client> {
2505 &self.app_state.client
2506 }
2507
2508 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2509 self.titlebar_item = Some(item);
2510 cx.notify();
2511 }
2512
2513 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2514 self.on_prompt_for_new_path = Some(prompt)
2515 }
2516
2517 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2518 self.on_prompt_for_open_path = Some(prompt)
2519 }
2520
2521 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2522 self.terminal_provider = Some(Box::new(provider));
2523 }
2524
2525 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2526 self.debugger_provider = Some(Arc::new(provider));
2527 }
2528
2529 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2530 self.debugger_provider.clone()
2531 }
2532
2533 pub fn prompt_for_open_path(
2534 &mut self,
2535 path_prompt_options: PathPromptOptions,
2536 lister: DirectoryLister,
2537 window: &mut Window,
2538 cx: &mut Context<Self>,
2539 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2540 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2541 let prompt = self.on_prompt_for_open_path.take().unwrap();
2542 let rx = prompt(self, lister, window, cx);
2543 self.on_prompt_for_open_path = Some(prompt);
2544 rx
2545 } else {
2546 let (tx, rx) = oneshot::channel();
2547 let abs_path = cx.prompt_for_paths(path_prompt_options);
2548
2549 cx.spawn_in(window, async move |workspace, cx| {
2550 let Ok(result) = abs_path.await else {
2551 return Ok(());
2552 };
2553
2554 match result {
2555 Ok(result) => {
2556 tx.send(result).ok();
2557 }
2558 Err(err) => {
2559 let rx = workspace.update_in(cx, |workspace, window, cx| {
2560 workspace.show_portal_error(err.to_string(), cx);
2561 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2562 let rx = prompt(workspace, lister, window, cx);
2563 workspace.on_prompt_for_open_path = Some(prompt);
2564 rx
2565 })?;
2566 if let Ok(path) = rx.await {
2567 tx.send(path).ok();
2568 }
2569 }
2570 };
2571 anyhow::Ok(())
2572 })
2573 .detach();
2574
2575 rx
2576 }
2577 }
2578
2579 pub fn prompt_for_new_path(
2580 &mut self,
2581 lister: DirectoryLister,
2582 suggested_name: Option<String>,
2583 window: &mut Window,
2584 cx: &mut Context<Self>,
2585 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2586 if self.project.read(cx).is_via_collab()
2587 || self.project.read(cx).is_via_remote_server()
2588 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2589 {
2590 let prompt = self.on_prompt_for_new_path.take().unwrap();
2591 let rx = prompt(self, lister, suggested_name, window, cx);
2592 self.on_prompt_for_new_path = Some(prompt);
2593 return rx;
2594 }
2595
2596 let (tx, rx) = oneshot::channel();
2597 cx.spawn_in(window, async move |workspace, cx| {
2598 let abs_path = workspace.update(cx, |workspace, cx| {
2599 let relative_to = workspace
2600 .most_recent_active_path(cx)
2601 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2602 .or_else(|| {
2603 let project = workspace.project.read(cx);
2604 project.visible_worktrees(cx).find_map(|worktree| {
2605 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2606 })
2607 })
2608 .or_else(std::env::home_dir)
2609 .unwrap_or_else(|| PathBuf::from(""));
2610 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2611 })?;
2612 let abs_path = match abs_path.await? {
2613 Ok(path) => path,
2614 Err(err) => {
2615 let rx = workspace.update_in(cx, |workspace, window, cx| {
2616 workspace.show_portal_error(err.to_string(), cx);
2617
2618 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2619 let rx = prompt(workspace, lister, suggested_name, window, cx);
2620 workspace.on_prompt_for_new_path = Some(prompt);
2621 rx
2622 })?;
2623 if let Ok(path) = rx.await {
2624 tx.send(path).ok();
2625 }
2626 return anyhow::Ok(());
2627 }
2628 };
2629
2630 tx.send(abs_path.map(|path| vec![path])).ok();
2631 anyhow::Ok(())
2632 })
2633 .detach();
2634
2635 rx
2636 }
2637
2638 pub fn titlebar_item(&self) -> Option<AnyView> {
2639 self.titlebar_item.clone()
2640 }
2641
2642 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2643 /// When set, git-related operations should use this worktree instead of deriving
2644 /// the active worktree from the focused file.
2645 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2646 self.active_worktree_override
2647 }
2648
2649 pub fn set_active_worktree_override(
2650 &mut self,
2651 worktree_id: Option<WorktreeId>,
2652 cx: &mut Context<Self>,
2653 ) {
2654 self.active_worktree_override = worktree_id;
2655 cx.notify();
2656 }
2657
2658 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2659 self.active_worktree_override = None;
2660 cx.notify();
2661 }
2662
2663 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2664 ///
2665 /// If the given workspace has a local project, then it will be passed
2666 /// to the callback. Otherwise, a new empty window will be created.
2667 pub fn with_local_workspace<T, F>(
2668 &mut self,
2669 window: &mut Window,
2670 cx: &mut Context<Self>,
2671 callback: F,
2672 ) -> Task<Result<T>>
2673 where
2674 T: 'static,
2675 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2676 {
2677 if self.project.read(cx).is_local() {
2678 Task::ready(Ok(callback(self, window, cx)))
2679 } else {
2680 let env = self.project.read(cx).cli_environment(cx);
2681 let task = Self::new_local(
2682 Vec::new(),
2683 self.app_state.clone(),
2684 None,
2685 env,
2686 None,
2687 true,
2688 cx,
2689 );
2690 cx.spawn_in(window, async move |_vh, cx| {
2691 let OpenResult {
2692 window: multi_workspace_window,
2693 ..
2694 } = task.await?;
2695 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2696 let workspace = multi_workspace.workspace().clone();
2697 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2698 })
2699 })
2700 }
2701 }
2702
2703 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2704 ///
2705 /// If the given workspace has a local project, then it will be passed
2706 /// to the callback. Otherwise, a new empty window will be created.
2707 pub fn with_local_or_wsl_workspace<T, F>(
2708 &mut self,
2709 window: &mut Window,
2710 cx: &mut Context<Self>,
2711 callback: F,
2712 ) -> Task<Result<T>>
2713 where
2714 T: 'static,
2715 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2716 {
2717 let project = self.project.read(cx);
2718 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
2719 Task::ready(Ok(callback(self, window, cx)))
2720 } else {
2721 let env = self.project.read(cx).cli_environment(cx);
2722 let task = Self::new_local(
2723 Vec::new(),
2724 self.app_state.clone(),
2725 None,
2726 env,
2727 None,
2728 true,
2729 cx,
2730 );
2731 cx.spawn_in(window, async move |_vh, cx| {
2732 let OpenResult {
2733 window: multi_workspace_window,
2734 ..
2735 } = task.await?;
2736 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2737 let workspace = multi_workspace.workspace().clone();
2738 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2739 })
2740 })
2741 }
2742 }
2743
2744 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2745 self.project.read(cx).worktrees(cx)
2746 }
2747
2748 pub fn visible_worktrees<'a>(
2749 &self,
2750 cx: &'a App,
2751 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2752 self.project.read(cx).visible_worktrees(cx)
2753 }
2754
2755 #[cfg(any(test, feature = "test-support"))]
2756 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
2757 let futures = self
2758 .worktrees(cx)
2759 .filter_map(|worktree| worktree.read(cx).as_local())
2760 .map(|worktree| worktree.scan_complete())
2761 .collect::<Vec<_>>();
2762 async move {
2763 for future in futures {
2764 future.await;
2765 }
2766 }
2767 }
2768
2769 pub fn close_global(cx: &mut App) {
2770 cx.defer(|cx| {
2771 cx.windows().iter().find(|window| {
2772 window
2773 .update(cx, |_, window, _| {
2774 if window.is_window_active() {
2775 //This can only get called when the window's project connection has been lost
2776 //so we don't need to prompt the user for anything and instead just close the window
2777 window.remove_window();
2778 true
2779 } else {
2780 false
2781 }
2782 })
2783 .unwrap_or(false)
2784 });
2785 });
2786 }
2787
2788 pub fn move_focused_panel_to_next_position(
2789 &mut self,
2790 _: &MoveFocusedPanelToNextPosition,
2791 window: &mut Window,
2792 cx: &mut Context<Self>,
2793 ) {
2794 let docks = self.all_docks();
2795 let active_dock = docks
2796 .into_iter()
2797 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
2798
2799 if let Some(dock) = active_dock {
2800 dock.update(cx, |dock, cx| {
2801 let active_panel = dock
2802 .active_panel()
2803 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
2804
2805 if let Some(panel) = active_panel {
2806 panel.move_to_next_position(window, cx);
2807 }
2808 })
2809 }
2810 }
2811
2812 pub fn prepare_to_close(
2813 &mut self,
2814 close_intent: CloseIntent,
2815 window: &mut Window,
2816 cx: &mut Context<Self>,
2817 ) -> Task<Result<bool>> {
2818 let active_call = self.active_global_call();
2819
2820 cx.spawn_in(window, async move |this, cx| {
2821 this.update(cx, |this, _| {
2822 if close_intent == CloseIntent::CloseWindow {
2823 this.removing = true;
2824 }
2825 })?;
2826
2827 let workspace_count = cx.update(|_window, cx| {
2828 cx.windows()
2829 .iter()
2830 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
2831 .count()
2832 })?;
2833
2834 #[cfg(target_os = "macos")]
2835 let save_last_workspace = false;
2836
2837 // On Linux and Windows, closing the last window should restore the last workspace.
2838 #[cfg(not(target_os = "macos"))]
2839 let save_last_workspace = {
2840 let remaining_workspaces = cx.update(|_window, cx| {
2841 cx.windows()
2842 .iter()
2843 .filter_map(|window| window.downcast::<MultiWorkspace>())
2844 .filter_map(|multi_workspace| {
2845 multi_workspace
2846 .update(cx, |multi_workspace, _, cx| {
2847 multi_workspace.workspace().read(cx).removing
2848 })
2849 .ok()
2850 })
2851 .filter(|removing| !removing)
2852 .count()
2853 })?;
2854
2855 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
2856 };
2857
2858 if let Some(active_call) = active_call
2859 && workspace_count == 1
2860 && cx
2861 .update(|_window, cx| active_call.0.is_in_room(cx))
2862 .unwrap_or(false)
2863 {
2864 if close_intent == CloseIntent::CloseWindow {
2865 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
2866 let answer = cx.update(|window, cx| {
2867 window.prompt(
2868 PromptLevel::Warning,
2869 "Do you want to leave the current call?",
2870 None,
2871 &["Close window and hang up", "Cancel"],
2872 cx,
2873 )
2874 })?;
2875
2876 if answer.await.log_err() == Some(1) {
2877 return anyhow::Ok(false);
2878 } else {
2879 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
2880 task.await.log_err();
2881 }
2882 }
2883 }
2884 if close_intent == CloseIntent::ReplaceWindow {
2885 _ = cx.update(|_window, cx| {
2886 let multi_workspace = cx
2887 .windows()
2888 .iter()
2889 .filter_map(|window| window.downcast::<MultiWorkspace>())
2890 .next()
2891 .unwrap();
2892 let project = multi_workspace
2893 .read(cx)?
2894 .workspace()
2895 .read(cx)
2896 .project
2897 .clone();
2898 if project.read(cx).is_shared() {
2899 active_call.0.unshare_project(project, cx)?;
2900 }
2901 Ok::<_, anyhow::Error>(())
2902 });
2903 }
2904 }
2905
2906 let save_result = this
2907 .update_in(cx, |this, window, cx| {
2908 this.save_all_internal(SaveIntent::Close, window, cx)
2909 })?
2910 .await;
2911
2912 // If we're not quitting, but closing, we remove the workspace from
2913 // the current session.
2914 if close_intent != CloseIntent::Quit
2915 && !save_last_workspace
2916 && save_result.as_ref().is_ok_and(|&res| res)
2917 {
2918 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
2919 .await;
2920 }
2921
2922 save_result
2923 })
2924 }
2925
2926 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
2927 self.save_all_internal(
2928 action.save_intent.unwrap_or(SaveIntent::SaveAll),
2929 window,
2930 cx,
2931 )
2932 .detach_and_log_err(cx);
2933 }
2934
2935 fn send_keystrokes(
2936 &mut self,
2937 action: &SendKeystrokes,
2938 window: &mut Window,
2939 cx: &mut Context<Self>,
2940 ) {
2941 let keystrokes: Vec<Keystroke> = action
2942 .0
2943 .split(' ')
2944 .flat_map(|k| Keystroke::parse(k).log_err())
2945 .map(|k| {
2946 cx.keyboard_mapper()
2947 .map_key_equivalent(k, false)
2948 .inner()
2949 .clone()
2950 })
2951 .collect();
2952 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
2953 }
2954
2955 pub fn send_keystrokes_impl(
2956 &mut self,
2957 keystrokes: Vec<Keystroke>,
2958 window: &mut Window,
2959 cx: &mut Context<Self>,
2960 ) -> Shared<Task<()>> {
2961 let mut state = self.dispatching_keystrokes.borrow_mut();
2962 if !state.dispatched.insert(keystrokes.clone()) {
2963 cx.propagate();
2964 return state.task.clone().unwrap();
2965 }
2966
2967 state.queue.extend(keystrokes);
2968
2969 let keystrokes = self.dispatching_keystrokes.clone();
2970 if state.task.is_none() {
2971 state.task = Some(
2972 window
2973 .spawn(cx, async move |cx| {
2974 // limit to 100 keystrokes to avoid infinite recursion.
2975 for _ in 0..100 {
2976 let keystroke = {
2977 let mut state = keystrokes.borrow_mut();
2978 let Some(keystroke) = state.queue.pop_front() else {
2979 state.dispatched.clear();
2980 state.task.take();
2981 return;
2982 };
2983 keystroke
2984 };
2985 cx.update(|window, cx| {
2986 let focused = window.focused(cx);
2987 window.dispatch_keystroke(keystroke.clone(), cx);
2988 if window.focused(cx) != focused {
2989 // dispatch_keystroke may cause the focus to change.
2990 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
2991 // And we need that to happen before the next keystroke to keep vim mode happy...
2992 // (Note that the tests always do this implicitly, so you must manually test with something like:
2993 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
2994 // )
2995 window.draw(cx).clear();
2996 }
2997 })
2998 .ok();
2999
3000 // Yield between synthetic keystrokes so deferred focus and
3001 // other effects can settle before dispatching the next key.
3002 yield_now().await;
3003 }
3004
3005 *keystrokes.borrow_mut() = Default::default();
3006 log::error!("over 100 keystrokes passed to send_keystrokes");
3007 })
3008 .shared(),
3009 );
3010 }
3011 state.task.clone().unwrap()
3012 }
3013
3014 fn save_all_internal(
3015 &mut self,
3016 mut save_intent: SaveIntent,
3017 window: &mut Window,
3018 cx: &mut Context<Self>,
3019 ) -> Task<Result<bool>> {
3020 if self.project.read(cx).is_disconnected(cx) {
3021 return Task::ready(Ok(true));
3022 }
3023 let dirty_items = self
3024 .panes
3025 .iter()
3026 .flat_map(|pane| {
3027 pane.read(cx).items().filter_map(|item| {
3028 if item.is_dirty(cx) {
3029 item.tab_content_text(0, cx);
3030 Some((pane.downgrade(), item.boxed_clone()))
3031 } else {
3032 None
3033 }
3034 })
3035 })
3036 .collect::<Vec<_>>();
3037
3038 let project = self.project.clone();
3039 cx.spawn_in(window, async move |workspace, cx| {
3040 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3041 let (serialize_tasks, remaining_dirty_items) =
3042 workspace.update_in(cx, |workspace, window, cx| {
3043 let mut remaining_dirty_items = Vec::new();
3044 let mut serialize_tasks = Vec::new();
3045 for (pane, item) in dirty_items {
3046 if let Some(task) = item
3047 .to_serializable_item_handle(cx)
3048 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3049 {
3050 serialize_tasks.push(task);
3051 } else {
3052 remaining_dirty_items.push((pane, item));
3053 }
3054 }
3055 (serialize_tasks, remaining_dirty_items)
3056 })?;
3057
3058 futures::future::try_join_all(serialize_tasks).await?;
3059
3060 if !remaining_dirty_items.is_empty() {
3061 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3062 }
3063
3064 if remaining_dirty_items.len() > 1 {
3065 let answer = workspace.update_in(cx, |_, window, cx| {
3066 let detail = Pane::file_names_for_prompt(
3067 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3068 cx,
3069 );
3070 window.prompt(
3071 PromptLevel::Warning,
3072 "Do you want to save all changes in the following files?",
3073 Some(&detail),
3074 &["Save all", "Discard all", "Cancel"],
3075 cx,
3076 )
3077 })?;
3078 match answer.await.log_err() {
3079 Some(0) => save_intent = SaveIntent::SaveAll,
3080 Some(1) => save_intent = SaveIntent::Skip,
3081 Some(2) => return Ok(false),
3082 _ => {}
3083 }
3084 }
3085
3086 remaining_dirty_items
3087 } else {
3088 dirty_items
3089 };
3090
3091 for (pane, item) in dirty_items {
3092 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3093 (
3094 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3095 item.project_entry_ids(cx),
3096 )
3097 })?;
3098 if (singleton || !project_entry_ids.is_empty())
3099 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3100 {
3101 return Ok(false);
3102 }
3103 }
3104 Ok(true)
3105 })
3106 }
3107
3108 pub fn open_workspace_for_paths(
3109 &mut self,
3110 replace_current_window: bool,
3111 paths: Vec<PathBuf>,
3112 window: &mut Window,
3113 cx: &mut Context<Self>,
3114 ) -> Task<Result<Entity<Workspace>>> {
3115 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
3116 let is_remote = self.project.read(cx).is_via_collab();
3117 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3118 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3119
3120 let window_to_replace = if replace_current_window {
3121 window_handle
3122 } else if is_remote || has_worktree || has_dirty_items {
3123 None
3124 } else {
3125 window_handle
3126 };
3127 let app_state = self.app_state.clone();
3128
3129 cx.spawn(async move |_, cx| {
3130 let OpenResult { workspace, .. } = cx
3131 .update(|cx| {
3132 open_paths(
3133 &paths,
3134 app_state,
3135 OpenOptions {
3136 replace_window: window_to_replace,
3137 ..Default::default()
3138 },
3139 cx,
3140 )
3141 })
3142 .await?;
3143 Ok(workspace)
3144 })
3145 }
3146
3147 #[allow(clippy::type_complexity)]
3148 pub fn open_paths(
3149 &mut self,
3150 mut abs_paths: Vec<PathBuf>,
3151 options: OpenOptions,
3152 pane: Option<WeakEntity<Pane>>,
3153 window: &mut Window,
3154 cx: &mut Context<Self>,
3155 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3156 let fs = self.app_state.fs.clone();
3157
3158 let caller_ordered_abs_paths = abs_paths.clone();
3159
3160 // Sort the paths to ensure we add worktrees for parents before their children.
3161 abs_paths.sort_unstable();
3162 cx.spawn_in(window, async move |this, cx| {
3163 let mut tasks = Vec::with_capacity(abs_paths.len());
3164
3165 for abs_path in &abs_paths {
3166 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3167 OpenVisible::All => Some(true),
3168 OpenVisible::None => Some(false),
3169 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3170 Some(Some(metadata)) => Some(!metadata.is_dir),
3171 Some(None) => Some(true),
3172 None => None,
3173 },
3174 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3175 Some(Some(metadata)) => Some(metadata.is_dir),
3176 Some(None) => Some(false),
3177 None => None,
3178 },
3179 };
3180 let project_path = match visible {
3181 Some(visible) => match this
3182 .update(cx, |this, cx| {
3183 Workspace::project_path_for_path(
3184 this.project.clone(),
3185 abs_path,
3186 visible,
3187 cx,
3188 )
3189 })
3190 .log_err()
3191 {
3192 Some(project_path) => project_path.await.log_err(),
3193 None => None,
3194 },
3195 None => None,
3196 };
3197
3198 let this = this.clone();
3199 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3200 let fs = fs.clone();
3201 let pane = pane.clone();
3202 let task = cx.spawn(async move |cx| {
3203 let (_worktree, project_path) = project_path?;
3204 if fs.is_dir(&abs_path).await {
3205 // Opening a directory should not race to update the active entry.
3206 // We'll select/reveal a deterministic final entry after all paths finish opening.
3207 None
3208 } else {
3209 Some(
3210 this.update_in(cx, |this, window, cx| {
3211 this.open_path(
3212 project_path,
3213 pane,
3214 options.focus.unwrap_or(true),
3215 window,
3216 cx,
3217 )
3218 })
3219 .ok()?
3220 .await,
3221 )
3222 }
3223 });
3224 tasks.push(task);
3225 }
3226
3227 let results = futures::future::join_all(tasks).await;
3228
3229 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3230 let mut winner: Option<(PathBuf, bool)> = None;
3231 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3232 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3233 if !metadata.is_dir {
3234 winner = Some((abs_path, false));
3235 break;
3236 }
3237 if winner.is_none() {
3238 winner = Some((abs_path, true));
3239 }
3240 } else if winner.is_none() {
3241 winner = Some((abs_path, false));
3242 }
3243 }
3244
3245 // Compute the winner entry id on the foreground thread and emit once, after all
3246 // paths finish opening. This avoids races between concurrently-opening paths
3247 // (directories in particular) and makes the resulting project panel selection
3248 // deterministic.
3249 if let Some((winner_abs_path, winner_is_dir)) = winner {
3250 'emit_winner: {
3251 let winner_abs_path: Arc<Path> =
3252 SanitizedPath::new(&winner_abs_path).as_path().into();
3253
3254 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3255 OpenVisible::All => true,
3256 OpenVisible::None => false,
3257 OpenVisible::OnlyFiles => !winner_is_dir,
3258 OpenVisible::OnlyDirectories => winner_is_dir,
3259 };
3260
3261 let Some(worktree_task) = this
3262 .update(cx, |workspace, cx| {
3263 workspace.project.update(cx, |project, cx| {
3264 project.find_or_create_worktree(
3265 winner_abs_path.as_ref(),
3266 visible,
3267 cx,
3268 )
3269 })
3270 })
3271 .ok()
3272 else {
3273 break 'emit_winner;
3274 };
3275
3276 let Ok((worktree, _)) = worktree_task.await else {
3277 break 'emit_winner;
3278 };
3279
3280 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3281 let worktree = worktree.read(cx);
3282 let worktree_abs_path = worktree.abs_path();
3283 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3284 worktree.root_entry()
3285 } else {
3286 winner_abs_path
3287 .strip_prefix(worktree_abs_path.as_ref())
3288 .ok()
3289 .and_then(|relative_path| {
3290 let relative_path =
3291 RelPath::new(relative_path, PathStyle::local())
3292 .log_err()?;
3293 worktree.entry_for_path(&relative_path)
3294 })
3295 }?;
3296 Some(entry.id)
3297 }) else {
3298 break 'emit_winner;
3299 };
3300
3301 this.update(cx, |workspace, cx| {
3302 workspace.project.update(cx, |_, cx| {
3303 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3304 });
3305 })
3306 .ok();
3307 }
3308 }
3309
3310 results
3311 })
3312 }
3313
3314 pub fn open_resolved_path(
3315 &mut self,
3316 path: ResolvedPath,
3317 window: &mut Window,
3318 cx: &mut Context<Self>,
3319 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3320 match path {
3321 ResolvedPath::ProjectPath { project_path, .. } => {
3322 self.open_path(project_path, None, true, window, cx)
3323 }
3324 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3325 PathBuf::from(path),
3326 OpenOptions {
3327 visible: Some(OpenVisible::None),
3328 ..Default::default()
3329 },
3330 window,
3331 cx,
3332 ),
3333 }
3334 }
3335
3336 pub fn absolute_path_of_worktree(
3337 &self,
3338 worktree_id: WorktreeId,
3339 cx: &mut Context<Self>,
3340 ) -> Option<PathBuf> {
3341 self.project
3342 .read(cx)
3343 .worktree_for_id(worktree_id, cx)
3344 // TODO: use `abs_path` or `root_dir`
3345 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3346 }
3347
3348 fn add_folder_to_project(
3349 &mut self,
3350 _: &AddFolderToProject,
3351 window: &mut Window,
3352 cx: &mut Context<Self>,
3353 ) {
3354 let project = self.project.read(cx);
3355 if project.is_via_collab() {
3356 self.show_error(
3357 &anyhow!("You cannot add folders to someone else's project"),
3358 cx,
3359 );
3360 return;
3361 }
3362 let paths = self.prompt_for_open_path(
3363 PathPromptOptions {
3364 files: false,
3365 directories: true,
3366 multiple: true,
3367 prompt: None,
3368 },
3369 DirectoryLister::Project(self.project.clone()),
3370 window,
3371 cx,
3372 );
3373 cx.spawn_in(window, async move |this, cx| {
3374 if let Some(paths) = paths.await.log_err().flatten() {
3375 let results = this
3376 .update_in(cx, |this, window, cx| {
3377 this.open_paths(
3378 paths,
3379 OpenOptions {
3380 visible: Some(OpenVisible::All),
3381 ..Default::default()
3382 },
3383 None,
3384 window,
3385 cx,
3386 )
3387 })?
3388 .await;
3389 for result in results.into_iter().flatten() {
3390 result.log_err();
3391 }
3392 }
3393 anyhow::Ok(())
3394 })
3395 .detach_and_log_err(cx);
3396 }
3397
3398 pub fn project_path_for_path(
3399 project: Entity<Project>,
3400 abs_path: &Path,
3401 visible: bool,
3402 cx: &mut App,
3403 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3404 let entry = project.update(cx, |project, cx| {
3405 project.find_or_create_worktree(abs_path, visible, cx)
3406 });
3407 cx.spawn(async move |cx| {
3408 let (worktree, path) = entry.await?;
3409 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3410 Ok((worktree, ProjectPath { worktree_id, path }))
3411 })
3412 }
3413
3414 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3415 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3416 }
3417
3418 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3419 self.items_of_type(cx).max_by_key(|item| item.item_id())
3420 }
3421
3422 pub fn items_of_type<'a, T: Item>(
3423 &'a self,
3424 cx: &'a App,
3425 ) -> impl 'a + Iterator<Item = Entity<T>> {
3426 self.panes
3427 .iter()
3428 .flat_map(|pane| pane.read(cx).items_of_type())
3429 }
3430
3431 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3432 self.active_pane().read(cx).active_item()
3433 }
3434
3435 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3436 let item = self.active_item(cx)?;
3437 item.to_any_view().downcast::<I>().ok()
3438 }
3439
3440 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3441 self.active_item(cx).and_then(|item| item.project_path(cx))
3442 }
3443
3444 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3445 self.recent_navigation_history_iter(cx)
3446 .filter_map(|(path, abs_path)| {
3447 let worktree = self
3448 .project
3449 .read(cx)
3450 .worktree_for_id(path.worktree_id, cx)?;
3451 if worktree.read(cx).is_visible() {
3452 abs_path
3453 } else {
3454 None
3455 }
3456 })
3457 .next()
3458 }
3459
3460 pub fn save_active_item(
3461 &mut self,
3462 save_intent: SaveIntent,
3463 window: &mut Window,
3464 cx: &mut App,
3465 ) -> Task<Result<()>> {
3466 let project = self.project.clone();
3467 let pane = self.active_pane();
3468 let item = pane.read(cx).active_item();
3469 let pane = pane.downgrade();
3470
3471 window.spawn(cx, async move |cx| {
3472 if let Some(item) = item {
3473 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3474 .await
3475 .map(|_| ())
3476 } else {
3477 Ok(())
3478 }
3479 })
3480 }
3481
3482 pub fn close_inactive_items_and_panes(
3483 &mut self,
3484 action: &CloseInactiveTabsAndPanes,
3485 window: &mut Window,
3486 cx: &mut Context<Self>,
3487 ) {
3488 if let Some(task) = self.close_all_internal(
3489 true,
3490 action.save_intent.unwrap_or(SaveIntent::Close),
3491 window,
3492 cx,
3493 ) {
3494 task.detach_and_log_err(cx)
3495 }
3496 }
3497
3498 pub fn close_all_items_and_panes(
3499 &mut self,
3500 action: &CloseAllItemsAndPanes,
3501 window: &mut Window,
3502 cx: &mut Context<Self>,
3503 ) {
3504 if let Some(task) = self.close_all_internal(
3505 false,
3506 action.save_intent.unwrap_or(SaveIntent::Close),
3507 window,
3508 cx,
3509 ) {
3510 task.detach_and_log_err(cx)
3511 }
3512 }
3513
3514 /// Closes the active item across all panes.
3515 pub fn close_item_in_all_panes(
3516 &mut self,
3517 action: &CloseItemInAllPanes,
3518 window: &mut Window,
3519 cx: &mut Context<Self>,
3520 ) {
3521 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3522 return;
3523 };
3524
3525 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3526 let close_pinned = action.close_pinned;
3527
3528 if let Some(project_path) = active_item.project_path(cx) {
3529 self.close_items_with_project_path(
3530 &project_path,
3531 save_intent,
3532 close_pinned,
3533 window,
3534 cx,
3535 );
3536 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3537 let item_id = active_item.item_id();
3538 self.active_pane().update(cx, |pane, cx| {
3539 pane.close_item_by_id(item_id, save_intent, window, cx)
3540 .detach_and_log_err(cx);
3541 });
3542 }
3543 }
3544
3545 /// Closes all items with the given project path across all panes.
3546 pub fn close_items_with_project_path(
3547 &mut self,
3548 project_path: &ProjectPath,
3549 save_intent: SaveIntent,
3550 close_pinned: bool,
3551 window: &mut Window,
3552 cx: &mut Context<Self>,
3553 ) {
3554 let panes = self.panes().to_vec();
3555 for pane in panes {
3556 pane.update(cx, |pane, cx| {
3557 pane.close_items_for_project_path(
3558 project_path,
3559 save_intent,
3560 close_pinned,
3561 window,
3562 cx,
3563 )
3564 .detach_and_log_err(cx);
3565 });
3566 }
3567 }
3568
3569 fn close_all_internal(
3570 &mut self,
3571 retain_active_pane: bool,
3572 save_intent: SaveIntent,
3573 window: &mut Window,
3574 cx: &mut Context<Self>,
3575 ) -> Option<Task<Result<()>>> {
3576 let current_pane = self.active_pane();
3577
3578 let mut tasks = Vec::new();
3579
3580 if retain_active_pane {
3581 let current_pane_close = current_pane.update(cx, |pane, cx| {
3582 pane.close_other_items(
3583 &CloseOtherItems {
3584 save_intent: None,
3585 close_pinned: false,
3586 },
3587 None,
3588 window,
3589 cx,
3590 )
3591 });
3592
3593 tasks.push(current_pane_close);
3594 }
3595
3596 for pane in self.panes() {
3597 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3598 continue;
3599 }
3600
3601 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3602 pane.close_all_items(
3603 &CloseAllItems {
3604 save_intent: Some(save_intent),
3605 close_pinned: false,
3606 },
3607 window,
3608 cx,
3609 )
3610 });
3611
3612 tasks.push(close_pane_items)
3613 }
3614
3615 if tasks.is_empty() {
3616 None
3617 } else {
3618 Some(cx.spawn_in(window, async move |_, _| {
3619 for task in tasks {
3620 task.await?
3621 }
3622 Ok(())
3623 }))
3624 }
3625 }
3626
3627 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3628 self.dock_at_position(position).read(cx).is_open()
3629 }
3630
3631 pub fn toggle_dock(
3632 &mut self,
3633 dock_side: DockPosition,
3634 window: &mut Window,
3635 cx: &mut Context<Self>,
3636 ) {
3637 let mut focus_center = false;
3638 let mut reveal_dock = false;
3639
3640 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3641 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3642
3643 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3644 telemetry::event!(
3645 "Panel Button Clicked",
3646 name = panel.persistent_name(),
3647 toggle_state = !was_visible
3648 );
3649 }
3650 if was_visible {
3651 self.save_open_dock_positions(cx);
3652 }
3653
3654 let dock = self.dock_at_position(dock_side);
3655 dock.update(cx, |dock, cx| {
3656 dock.set_open(!was_visible, window, cx);
3657
3658 if dock.active_panel().is_none() {
3659 let Some(panel_ix) = dock
3660 .first_enabled_panel_idx(cx)
3661 .log_with_level(log::Level::Info)
3662 else {
3663 return;
3664 };
3665 dock.activate_panel(panel_ix, window, cx);
3666 }
3667
3668 if let Some(active_panel) = dock.active_panel() {
3669 if was_visible {
3670 if active_panel
3671 .panel_focus_handle(cx)
3672 .contains_focused(window, cx)
3673 {
3674 focus_center = true;
3675 }
3676 } else {
3677 let focus_handle = &active_panel.panel_focus_handle(cx);
3678 window.focus(focus_handle, cx);
3679 reveal_dock = true;
3680 }
3681 }
3682 });
3683
3684 if reveal_dock {
3685 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3686 }
3687
3688 if focus_center {
3689 self.active_pane
3690 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3691 }
3692
3693 cx.notify();
3694 self.serialize_workspace(window, cx);
3695 }
3696
3697 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3698 self.all_docks().into_iter().find(|&dock| {
3699 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3700 })
3701 }
3702
3703 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3704 if let Some(dock) = self.active_dock(window, cx).cloned() {
3705 self.save_open_dock_positions(cx);
3706 dock.update(cx, |dock, cx| {
3707 dock.set_open(false, window, cx);
3708 });
3709 return true;
3710 }
3711 false
3712 }
3713
3714 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3715 self.save_open_dock_positions(cx);
3716 for dock in self.all_docks() {
3717 dock.update(cx, |dock, cx| {
3718 dock.set_open(false, window, cx);
3719 });
3720 }
3721
3722 cx.focus_self(window);
3723 cx.notify();
3724 self.serialize_workspace(window, cx);
3725 }
3726
3727 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
3728 self.all_docks()
3729 .into_iter()
3730 .filter_map(|dock| {
3731 let dock_ref = dock.read(cx);
3732 if dock_ref.is_open() {
3733 Some(dock_ref.position())
3734 } else {
3735 None
3736 }
3737 })
3738 .collect()
3739 }
3740
3741 /// Saves the positions of currently open docks.
3742 ///
3743 /// Updates `last_open_dock_positions` with positions of all currently open
3744 /// docks, to later be restored by the 'Toggle All Docks' action.
3745 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
3746 let open_dock_positions = self.get_open_dock_positions(cx);
3747 if !open_dock_positions.is_empty() {
3748 self.last_open_dock_positions = open_dock_positions;
3749 }
3750 }
3751
3752 /// Toggles all docks between open and closed states.
3753 ///
3754 /// If any docks are open, closes all and remembers their positions. If all
3755 /// docks are closed, restores the last remembered dock configuration.
3756 fn toggle_all_docks(
3757 &mut self,
3758 _: &ToggleAllDocks,
3759 window: &mut Window,
3760 cx: &mut Context<Self>,
3761 ) {
3762 let open_dock_positions = self.get_open_dock_positions(cx);
3763
3764 if !open_dock_positions.is_empty() {
3765 self.close_all_docks(window, cx);
3766 } else if !self.last_open_dock_positions.is_empty() {
3767 self.restore_last_open_docks(window, cx);
3768 }
3769 }
3770
3771 /// Reopens docks from the most recently remembered configuration.
3772 ///
3773 /// Opens all docks whose positions are stored in `last_open_dock_positions`
3774 /// and clears the stored positions.
3775 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3776 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
3777
3778 for position in positions_to_open {
3779 let dock = self.dock_at_position(position);
3780 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
3781 }
3782
3783 cx.focus_self(window);
3784 cx.notify();
3785 self.serialize_workspace(window, cx);
3786 }
3787
3788 /// Transfer focus to the panel of the given type.
3789 pub fn focus_panel<T: Panel>(
3790 &mut self,
3791 window: &mut Window,
3792 cx: &mut Context<Self>,
3793 ) -> Option<Entity<T>> {
3794 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
3795 panel.to_any().downcast().ok()
3796 }
3797
3798 /// Focus the panel of the given type if it isn't already focused. If it is
3799 /// already focused, then transfer focus back to the workspace center.
3800 /// When the `close_panel_on_toggle` setting is enabled, also closes the
3801 /// panel when transferring focus back to the center.
3802 pub fn toggle_panel_focus<T: Panel>(
3803 &mut self,
3804 window: &mut Window,
3805 cx: &mut Context<Self>,
3806 ) -> bool {
3807 let mut did_focus_panel = false;
3808 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
3809 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
3810 did_focus_panel
3811 });
3812
3813 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
3814 self.close_panel::<T>(window, cx);
3815 }
3816
3817 telemetry::event!(
3818 "Panel Button Clicked",
3819 name = T::persistent_name(),
3820 toggle_state = did_focus_panel
3821 );
3822
3823 did_focus_panel
3824 }
3825
3826 pub fn activate_panel_for_proto_id(
3827 &mut self,
3828 panel_id: PanelId,
3829 window: &mut Window,
3830 cx: &mut Context<Self>,
3831 ) -> Option<Arc<dyn PanelHandle>> {
3832 let mut panel = None;
3833 for dock in self.all_docks() {
3834 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
3835 panel = dock.update(cx, |dock, cx| {
3836 dock.activate_panel(panel_index, window, cx);
3837 dock.set_open(true, window, cx);
3838 dock.active_panel().cloned()
3839 });
3840 break;
3841 }
3842 }
3843
3844 if panel.is_some() {
3845 cx.notify();
3846 self.serialize_workspace(window, cx);
3847 }
3848
3849 panel
3850 }
3851
3852 /// Focus or unfocus the given panel type, depending on the given callback.
3853 fn focus_or_unfocus_panel<T: Panel>(
3854 &mut self,
3855 window: &mut Window,
3856 cx: &mut Context<Self>,
3857 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
3858 ) -> Option<Arc<dyn PanelHandle>> {
3859 let mut result_panel = None;
3860 let mut serialize = false;
3861 for dock in self.all_docks() {
3862 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3863 let mut focus_center = false;
3864 let panel = dock.update(cx, |dock, cx| {
3865 dock.activate_panel(panel_index, window, cx);
3866
3867 let panel = dock.active_panel().cloned();
3868 if let Some(panel) = panel.as_ref() {
3869 if should_focus(&**panel, window, cx) {
3870 dock.set_open(true, window, cx);
3871 panel.panel_focus_handle(cx).focus(window, cx);
3872 } else {
3873 focus_center = true;
3874 }
3875 }
3876 panel
3877 });
3878
3879 if focus_center {
3880 self.active_pane
3881 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3882 }
3883
3884 result_panel = panel;
3885 serialize = true;
3886 break;
3887 }
3888 }
3889
3890 if serialize {
3891 self.serialize_workspace(window, cx);
3892 }
3893
3894 cx.notify();
3895 result_panel
3896 }
3897
3898 /// Open the panel of the given type
3899 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3900 for dock in self.all_docks() {
3901 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3902 dock.update(cx, |dock, cx| {
3903 dock.activate_panel(panel_index, window, cx);
3904 dock.set_open(true, window, cx);
3905 });
3906 }
3907 }
3908 }
3909
3910 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
3911 for dock in self.all_docks().iter() {
3912 dock.update(cx, |dock, cx| {
3913 if dock.panel::<T>().is_some() {
3914 dock.set_open(false, window, cx)
3915 }
3916 })
3917 }
3918 }
3919
3920 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
3921 self.all_docks()
3922 .iter()
3923 .find_map(|dock| dock.read(cx).panel::<T>())
3924 }
3925
3926 fn dismiss_zoomed_items_to_reveal(
3927 &mut self,
3928 dock_to_reveal: Option<DockPosition>,
3929 window: &mut Window,
3930 cx: &mut Context<Self>,
3931 ) {
3932 // If a center pane is zoomed, unzoom it.
3933 for pane in &self.panes {
3934 if pane != &self.active_pane || dock_to_reveal.is_some() {
3935 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
3936 }
3937 }
3938
3939 // If another dock is zoomed, hide it.
3940 let mut focus_center = false;
3941 for dock in self.all_docks() {
3942 dock.update(cx, |dock, cx| {
3943 if Some(dock.position()) != dock_to_reveal
3944 && let Some(panel) = dock.active_panel()
3945 && panel.is_zoomed(window, cx)
3946 {
3947 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
3948 dock.set_open(false, window, cx);
3949 }
3950 });
3951 }
3952
3953 if focus_center {
3954 self.active_pane
3955 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3956 }
3957
3958 if self.zoomed_position != dock_to_reveal {
3959 self.zoomed = None;
3960 self.zoomed_position = None;
3961 cx.emit(Event::ZoomChanged);
3962 }
3963
3964 cx.notify();
3965 }
3966
3967 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
3968 let pane = cx.new(|cx| {
3969 let mut pane = Pane::new(
3970 self.weak_handle(),
3971 self.project.clone(),
3972 self.pane_history_timestamp.clone(),
3973 None,
3974 NewFile.boxed_clone(),
3975 true,
3976 window,
3977 cx,
3978 );
3979 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
3980 pane
3981 });
3982 cx.subscribe_in(&pane, window, Self::handle_pane_event)
3983 .detach();
3984 self.panes.push(pane.clone());
3985
3986 window.focus(&pane.focus_handle(cx), cx);
3987
3988 cx.emit(Event::PaneAdded(pane.clone()));
3989 pane
3990 }
3991
3992 pub fn add_item_to_center(
3993 &mut self,
3994 item: Box<dyn ItemHandle>,
3995 window: &mut Window,
3996 cx: &mut Context<Self>,
3997 ) -> bool {
3998 if let Some(center_pane) = self.last_active_center_pane.clone() {
3999 if let Some(center_pane) = center_pane.upgrade() {
4000 center_pane.update(cx, |pane, cx| {
4001 pane.add_item(item, true, true, None, window, cx)
4002 });
4003 true
4004 } else {
4005 false
4006 }
4007 } else {
4008 false
4009 }
4010 }
4011
4012 pub fn add_item_to_active_pane(
4013 &mut self,
4014 item: Box<dyn ItemHandle>,
4015 destination_index: Option<usize>,
4016 focus_item: bool,
4017 window: &mut Window,
4018 cx: &mut App,
4019 ) {
4020 self.add_item(
4021 self.active_pane.clone(),
4022 item,
4023 destination_index,
4024 false,
4025 focus_item,
4026 window,
4027 cx,
4028 )
4029 }
4030
4031 pub fn add_item(
4032 &mut self,
4033 pane: Entity<Pane>,
4034 item: Box<dyn ItemHandle>,
4035 destination_index: Option<usize>,
4036 activate_pane: bool,
4037 focus_item: bool,
4038 window: &mut Window,
4039 cx: &mut App,
4040 ) {
4041 pane.update(cx, |pane, cx| {
4042 pane.add_item(
4043 item,
4044 activate_pane,
4045 focus_item,
4046 destination_index,
4047 window,
4048 cx,
4049 )
4050 });
4051 }
4052
4053 pub fn split_item(
4054 &mut self,
4055 split_direction: SplitDirection,
4056 item: Box<dyn ItemHandle>,
4057 window: &mut Window,
4058 cx: &mut Context<Self>,
4059 ) {
4060 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4061 self.add_item(new_pane, item, None, true, true, window, cx);
4062 }
4063
4064 pub fn open_abs_path(
4065 &mut self,
4066 abs_path: PathBuf,
4067 options: OpenOptions,
4068 window: &mut Window,
4069 cx: &mut Context<Self>,
4070 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4071 cx.spawn_in(window, async move |workspace, cx| {
4072 let open_paths_task_result = workspace
4073 .update_in(cx, |workspace, window, cx| {
4074 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4075 })
4076 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4077 .await;
4078 anyhow::ensure!(
4079 open_paths_task_result.len() == 1,
4080 "open abs path {abs_path:?} task returned incorrect number of results"
4081 );
4082 match open_paths_task_result
4083 .into_iter()
4084 .next()
4085 .expect("ensured single task result")
4086 {
4087 Some(open_result) => {
4088 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4089 }
4090 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4091 }
4092 })
4093 }
4094
4095 pub fn split_abs_path(
4096 &mut self,
4097 abs_path: PathBuf,
4098 visible: bool,
4099 window: &mut Window,
4100 cx: &mut Context<Self>,
4101 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4102 let project_path_task =
4103 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4104 cx.spawn_in(window, async move |this, cx| {
4105 let (_, path) = project_path_task.await?;
4106 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4107 .await
4108 })
4109 }
4110
4111 pub fn open_path(
4112 &mut self,
4113 path: impl Into<ProjectPath>,
4114 pane: Option<WeakEntity<Pane>>,
4115 focus_item: bool,
4116 window: &mut Window,
4117 cx: &mut App,
4118 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4119 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4120 }
4121
4122 pub fn open_path_preview(
4123 &mut self,
4124 path: impl Into<ProjectPath>,
4125 pane: Option<WeakEntity<Pane>>,
4126 focus_item: bool,
4127 allow_preview: bool,
4128 activate: bool,
4129 window: &mut Window,
4130 cx: &mut App,
4131 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4132 let pane = pane.unwrap_or_else(|| {
4133 self.last_active_center_pane.clone().unwrap_or_else(|| {
4134 self.panes
4135 .first()
4136 .expect("There must be an active pane")
4137 .downgrade()
4138 })
4139 });
4140
4141 let project_path = path.into();
4142 let task = self.load_path(project_path.clone(), window, cx);
4143 window.spawn(cx, async move |cx| {
4144 let (project_entry_id, build_item) = task.await?;
4145
4146 pane.update_in(cx, |pane, window, cx| {
4147 pane.open_item(
4148 project_entry_id,
4149 project_path,
4150 focus_item,
4151 allow_preview,
4152 activate,
4153 None,
4154 window,
4155 cx,
4156 build_item,
4157 )
4158 })
4159 })
4160 }
4161
4162 pub fn split_path(
4163 &mut self,
4164 path: impl Into<ProjectPath>,
4165 window: &mut Window,
4166 cx: &mut Context<Self>,
4167 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4168 self.split_path_preview(path, false, None, window, cx)
4169 }
4170
4171 pub fn split_path_preview(
4172 &mut self,
4173 path: impl Into<ProjectPath>,
4174 allow_preview: bool,
4175 split_direction: Option<SplitDirection>,
4176 window: &mut Window,
4177 cx: &mut Context<Self>,
4178 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4179 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4180 self.panes
4181 .first()
4182 .expect("There must be an active pane")
4183 .downgrade()
4184 });
4185
4186 if let Member::Pane(center_pane) = &self.center.root
4187 && center_pane.read(cx).items_len() == 0
4188 {
4189 return self.open_path(path, Some(pane), true, window, cx);
4190 }
4191
4192 let project_path = path.into();
4193 let task = self.load_path(project_path.clone(), window, cx);
4194 cx.spawn_in(window, async move |this, cx| {
4195 let (project_entry_id, build_item) = task.await?;
4196 this.update_in(cx, move |this, window, cx| -> Option<_> {
4197 let pane = pane.upgrade()?;
4198 let new_pane = this.split_pane(
4199 pane,
4200 split_direction.unwrap_or(SplitDirection::Right),
4201 window,
4202 cx,
4203 );
4204 new_pane.update(cx, |new_pane, cx| {
4205 Some(new_pane.open_item(
4206 project_entry_id,
4207 project_path,
4208 true,
4209 allow_preview,
4210 true,
4211 None,
4212 window,
4213 cx,
4214 build_item,
4215 ))
4216 })
4217 })
4218 .map(|option| option.context("pane was dropped"))?
4219 })
4220 }
4221
4222 fn load_path(
4223 &mut self,
4224 path: ProjectPath,
4225 window: &mut Window,
4226 cx: &mut App,
4227 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4228 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4229 registry.open_path(self.project(), &path, window, cx)
4230 }
4231
4232 pub fn find_project_item<T>(
4233 &self,
4234 pane: &Entity<Pane>,
4235 project_item: &Entity<T::Item>,
4236 cx: &App,
4237 ) -> Option<Entity<T>>
4238 where
4239 T: ProjectItem,
4240 {
4241 use project::ProjectItem as _;
4242 let project_item = project_item.read(cx);
4243 let entry_id = project_item.entry_id(cx);
4244 let project_path = project_item.project_path(cx);
4245
4246 let mut item = None;
4247 if let Some(entry_id) = entry_id {
4248 item = pane.read(cx).item_for_entry(entry_id, cx);
4249 }
4250 if item.is_none()
4251 && let Some(project_path) = project_path
4252 {
4253 item = pane.read(cx).item_for_path(project_path, cx);
4254 }
4255
4256 item.and_then(|item| item.downcast::<T>())
4257 }
4258
4259 pub fn is_project_item_open<T>(
4260 &self,
4261 pane: &Entity<Pane>,
4262 project_item: &Entity<T::Item>,
4263 cx: &App,
4264 ) -> bool
4265 where
4266 T: ProjectItem,
4267 {
4268 self.find_project_item::<T>(pane, project_item, cx)
4269 .is_some()
4270 }
4271
4272 pub fn open_project_item<T>(
4273 &mut self,
4274 pane: Entity<Pane>,
4275 project_item: Entity<T::Item>,
4276 activate_pane: bool,
4277 focus_item: bool,
4278 keep_old_preview: bool,
4279 allow_new_preview: bool,
4280 window: &mut Window,
4281 cx: &mut Context<Self>,
4282 ) -> Entity<T>
4283 where
4284 T: ProjectItem,
4285 {
4286 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4287
4288 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4289 if !keep_old_preview
4290 && let Some(old_id) = old_item_id
4291 && old_id != item.item_id()
4292 {
4293 // switching to a different item, so unpreview old active item
4294 pane.update(cx, |pane, _| {
4295 pane.unpreview_item_if_preview(old_id);
4296 });
4297 }
4298
4299 self.activate_item(&item, activate_pane, focus_item, window, cx);
4300 if !allow_new_preview {
4301 pane.update(cx, |pane, _| {
4302 pane.unpreview_item_if_preview(item.item_id());
4303 });
4304 }
4305 return item;
4306 }
4307
4308 let item = pane.update(cx, |pane, cx| {
4309 cx.new(|cx| {
4310 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4311 })
4312 });
4313 let mut destination_index = None;
4314 pane.update(cx, |pane, cx| {
4315 if !keep_old_preview && let Some(old_id) = old_item_id {
4316 pane.unpreview_item_if_preview(old_id);
4317 }
4318 if allow_new_preview {
4319 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4320 }
4321 });
4322
4323 self.add_item(
4324 pane,
4325 Box::new(item.clone()),
4326 destination_index,
4327 activate_pane,
4328 focus_item,
4329 window,
4330 cx,
4331 );
4332 item
4333 }
4334
4335 pub fn open_shared_screen(
4336 &mut self,
4337 peer_id: PeerId,
4338 window: &mut Window,
4339 cx: &mut Context<Self>,
4340 ) {
4341 if let Some(shared_screen) =
4342 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4343 {
4344 self.active_pane.update(cx, |pane, cx| {
4345 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4346 });
4347 }
4348 }
4349
4350 pub fn activate_item(
4351 &mut self,
4352 item: &dyn ItemHandle,
4353 activate_pane: bool,
4354 focus_item: bool,
4355 window: &mut Window,
4356 cx: &mut App,
4357 ) -> bool {
4358 let result = self.panes.iter().find_map(|pane| {
4359 pane.read(cx)
4360 .index_for_item(item)
4361 .map(|ix| (pane.clone(), ix))
4362 });
4363 if let Some((pane, ix)) = result {
4364 pane.update(cx, |pane, cx| {
4365 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4366 });
4367 true
4368 } else {
4369 false
4370 }
4371 }
4372
4373 fn activate_pane_at_index(
4374 &mut self,
4375 action: &ActivatePane,
4376 window: &mut Window,
4377 cx: &mut Context<Self>,
4378 ) {
4379 let panes = self.center.panes();
4380 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4381 window.focus(&pane.focus_handle(cx), cx);
4382 } else {
4383 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4384 .detach();
4385 }
4386 }
4387
4388 fn move_item_to_pane_at_index(
4389 &mut self,
4390 action: &MoveItemToPane,
4391 window: &mut Window,
4392 cx: &mut Context<Self>,
4393 ) {
4394 let panes = self.center.panes();
4395 let destination = match panes.get(action.destination) {
4396 Some(&destination) => destination.clone(),
4397 None => {
4398 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4399 return;
4400 }
4401 let direction = SplitDirection::Right;
4402 let split_off_pane = self
4403 .find_pane_in_direction(direction, cx)
4404 .unwrap_or_else(|| self.active_pane.clone());
4405 let new_pane = self.add_pane(window, cx);
4406 self.center.split(&split_off_pane, &new_pane, direction, cx);
4407 new_pane
4408 }
4409 };
4410
4411 if action.clone {
4412 if self
4413 .active_pane
4414 .read(cx)
4415 .active_item()
4416 .is_some_and(|item| item.can_split(cx))
4417 {
4418 clone_active_item(
4419 self.database_id(),
4420 &self.active_pane,
4421 &destination,
4422 action.focus,
4423 window,
4424 cx,
4425 );
4426 return;
4427 }
4428 }
4429 move_active_item(
4430 &self.active_pane,
4431 &destination,
4432 action.focus,
4433 true,
4434 window,
4435 cx,
4436 )
4437 }
4438
4439 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4440 let panes = self.center.panes();
4441 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4442 let next_ix = (ix + 1) % panes.len();
4443 let next_pane = panes[next_ix].clone();
4444 window.focus(&next_pane.focus_handle(cx), cx);
4445 }
4446 }
4447
4448 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4449 let panes = self.center.panes();
4450 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4451 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4452 let prev_pane = panes[prev_ix].clone();
4453 window.focus(&prev_pane.focus_handle(cx), cx);
4454 }
4455 }
4456
4457 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4458 let last_pane = self.center.last_pane();
4459 window.focus(&last_pane.focus_handle(cx), cx);
4460 }
4461
4462 pub fn activate_pane_in_direction(
4463 &mut self,
4464 direction: SplitDirection,
4465 window: &mut Window,
4466 cx: &mut App,
4467 ) {
4468 use ActivateInDirectionTarget as Target;
4469 enum Origin {
4470 LeftDock,
4471 RightDock,
4472 BottomDock,
4473 Center,
4474 }
4475
4476 let origin: Origin = [
4477 (&self.left_dock, Origin::LeftDock),
4478 (&self.right_dock, Origin::RightDock),
4479 (&self.bottom_dock, Origin::BottomDock),
4480 ]
4481 .into_iter()
4482 .find_map(|(dock, origin)| {
4483 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4484 Some(origin)
4485 } else {
4486 None
4487 }
4488 })
4489 .unwrap_or(Origin::Center);
4490
4491 let get_last_active_pane = || {
4492 let pane = self
4493 .last_active_center_pane
4494 .clone()
4495 .unwrap_or_else(|| {
4496 self.panes
4497 .first()
4498 .expect("There must be an active pane")
4499 .downgrade()
4500 })
4501 .upgrade()?;
4502 (pane.read(cx).items_len() != 0).then_some(pane)
4503 };
4504
4505 let try_dock =
4506 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4507
4508 let target = match (origin, direction) {
4509 // We're in the center, so we first try to go to a different pane,
4510 // otherwise try to go to a dock.
4511 (Origin::Center, direction) => {
4512 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4513 Some(Target::Pane(pane))
4514 } else {
4515 match direction {
4516 SplitDirection::Up => None,
4517 SplitDirection::Down => try_dock(&self.bottom_dock),
4518 SplitDirection::Left => try_dock(&self.left_dock),
4519 SplitDirection::Right => try_dock(&self.right_dock),
4520 }
4521 }
4522 }
4523
4524 (Origin::LeftDock, SplitDirection::Right) => {
4525 if let Some(last_active_pane) = get_last_active_pane() {
4526 Some(Target::Pane(last_active_pane))
4527 } else {
4528 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4529 }
4530 }
4531
4532 (Origin::LeftDock, SplitDirection::Down)
4533 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4534
4535 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4536 (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
4537 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4538
4539 (Origin::RightDock, SplitDirection::Left) => {
4540 if let Some(last_active_pane) = get_last_active_pane() {
4541 Some(Target::Pane(last_active_pane))
4542 } else {
4543 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
4544 }
4545 }
4546
4547 _ => None,
4548 };
4549
4550 match target {
4551 Some(ActivateInDirectionTarget::Pane(pane)) => {
4552 let pane = pane.read(cx);
4553 if let Some(item) = pane.active_item() {
4554 item.item_focus_handle(cx).focus(window, cx);
4555 } else {
4556 log::error!(
4557 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4558 );
4559 }
4560 }
4561 Some(ActivateInDirectionTarget::Dock(dock)) => {
4562 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4563 window.defer(cx, move |window, cx| {
4564 let dock = dock.read(cx);
4565 if let Some(panel) = dock.active_panel() {
4566 panel.panel_focus_handle(cx).focus(window, cx);
4567 } else {
4568 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4569 }
4570 })
4571 }
4572 None => {}
4573 }
4574 }
4575
4576 pub fn move_item_to_pane_in_direction(
4577 &mut self,
4578 action: &MoveItemToPaneInDirection,
4579 window: &mut Window,
4580 cx: &mut Context<Self>,
4581 ) {
4582 let destination = match self.find_pane_in_direction(action.direction, cx) {
4583 Some(destination) => destination,
4584 None => {
4585 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4586 return;
4587 }
4588 let new_pane = self.add_pane(window, cx);
4589 self.center
4590 .split(&self.active_pane, &new_pane, action.direction, cx);
4591 new_pane
4592 }
4593 };
4594
4595 if action.clone {
4596 if self
4597 .active_pane
4598 .read(cx)
4599 .active_item()
4600 .is_some_and(|item| item.can_split(cx))
4601 {
4602 clone_active_item(
4603 self.database_id(),
4604 &self.active_pane,
4605 &destination,
4606 action.focus,
4607 window,
4608 cx,
4609 );
4610 return;
4611 }
4612 }
4613 move_active_item(
4614 &self.active_pane,
4615 &destination,
4616 action.focus,
4617 true,
4618 window,
4619 cx,
4620 );
4621 }
4622
4623 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4624 self.center.bounding_box_for_pane(pane)
4625 }
4626
4627 pub fn find_pane_in_direction(
4628 &mut self,
4629 direction: SplitDirection,
4630 cx: &App,
4631 ) -> Option<Entity<Pane>> {
4632 self.center
4633 .find_pane_in_direction(&self.active_pane, direction, cx)
4634 .cloned()
4635 }
4636
4637 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4638 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4639 self.center.swap(&self.active_pane, &to, cx);
4640 cx.notify();
4641 }
4642 }
4643
4644 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4645 if self
4646 .center
4647 .move_to_border(&self.active_pane, direction, cx)
4648 .unwrap()
4649 {
4650 cx.notify();
4651 }
4652 }
4653
4654 pub fn resize_pane(
4655 &mut self,
4656 axis: gpui::Axis,
4657 amount: Pixels,
4658 window: &mut Window,
4659 cx: &mut Context<Self>,
4660 ) {
4661 let docks = self.all_docks();
4662 let active_dock = docks
4663 .into_iter()
4664 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4665
4666 if let Some(dock) = active_dock {
4667 let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
4668 return;
4669 };
4670 match dock.read(cx).position() {
4671 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4672 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4673 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4674 }
4675 } else {
4676 self.center
4677 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
4678 }
4679 cx.notify();
4680 }
4681
4682 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
4683 self.center.reset_pane_sizes(cx);
4684 cx.notify();
4685 }
4686
4687 fn handle_pane_focused(
4688 &mut self,
4689 pane: Entity<Pane>,
4690 window: &mut Window,
4691 cx: &mut Context<Self>,
4692 ) {
4693 // This is explicitly hoisted out of the following check for pane identity as
4694 // terminal panel panes are not registered as a center panes.
4695 self.status_bar.update(cx, |status_bar, cx| {
4696 status_bar.set_active_pane(&pane, window, cx);
4697 });
4698 if self.active_pane != pane {
4699 self.set_active_pane(&pane, window, cx);
4700 }
4701
4702 if self.last_active_center_pane.is_none() {
4703 self.last_active_center_pane = Some(pane.downgrade());
4704 }
4705
4706 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
4707 // This prevents the dock from closing when focus events fire during window activation.
4708 // We also preserve any dock whose active panel itself has focus — this covers
4709 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
4710 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
4711 let dock_read = dock.read(cx);
4712 if let Some(panel) = dock_read.active_panel() {
4713 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
4714 || panel.panel_focus_handle(cx).contains_focused(window, cx)
4715 {
4716 return Some(dock_read.position());
4717 }
4718 }
4719 None
4720 });
4721
4722 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
4723 if pane.read(cx).is_zoomed() {
4724 self.zoomed = Some(pane.downgrade().into());
4725 } else {
4726 self.zoomed = None;
4727 }
4728 self.zoomed_position = None;
4729 cx.emit(Event::ZoomChanged);
4730 self.update_active_view_for_followers(window, cx);
4731 pane.update(cx, |pane, _| {
4732 pane.track_alternate_file_items();
4733 });
4734
4735 cx.notify();
4736 }
4737
4738 fn set_active_pane(
4739 &mut self,
4740 pane: &Entity<Pane>,
4741 window: &mut Window,
4742 cx: &mut Context<Self>,
4743 ) {
4744 self.active_pane = pane.clone();
4745 self.active_item_path_changed(true, window, cx);
4746 self.last_active_center_pane = Some(pane.downgrade());
4747 }
4748
4749 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4750 self.update_active_view_for_followers(window, cx);
4751 }
4752
4753 fn handle_pane_event(
4754 &mut self,
4755 pane: &Entity<Pane>,
4756 event: &pane::Event,
4757 window: &mut Window,
4758 cx: &mut Context<Self>,
4759 ) {
4760 let mut serialize_workspace = true;
4761 match event {
4762 pane::Event::AddItem { item } => {
4763 item.added_to_pane(self, pane.clone(), window, cx);
4764 cx.emit(Event::ItemAdded {
4765 item: item.boxed_clone(),
4766 });
4767 }
4768 pane::Event::Split { direction, mode } => {
4769 match mode {
4770 SplitMode::ClonePane => {
4771 self.split_and_clone(pane.clone(), *direction, window, cx)
4772 .detach();
4773 }
4774 SplitMode::EmptyPane => {
4775 self.split_pane(pane.clone(), *direction, window, cx);
4776 }
4777 SplitMode::MovePane => {
4778 self.split_and_move(pane.clone(), *direction, window, cx);
4779 }
4780 };
4781 }
4782 pane::Event::JoinIntoNext => {
4783 self.join_pane_into_next(pane.clone(), window, cx);
4784 }
4785 pane::Event::JoinAll => {
4786 self.join_all_panes(window, cx);
4787 }
4788 pane::Event::Remove { focus_on_pane } => {
4789 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
4790 }
4791 pane::Event::ActivateItem {
4792 local,
4793 focus_changed,
4794 } => {
4795 window.invalidate_character_coordinates();
4796
4797 pane.update(cx, |pane, _| {
4798 pane.track_alternate_file_items();
4799 });
4800 if *local {
4801 self.unfollow_in_pane(pane, window, cx);
4802 }
4803 serialize_workspace = *focus_changed || pane != self.active_pane();
4804 if pane == self.active_pane() {
4805 self.active_item_path_changed(*focus_changed, window, cx);
4806 self.update_active_view_for_followers(window, cx);
4807 } else if *local {
4808 self.set_active_pane(pane, window, cx);
4809 }
4810 }
4811 pane::Event::UserSavedItem { item, save_intent } => {
4812 cx.emit(Event::UserSavedItem {
4813 pane: pane.downgrade(),
4814 item: item.boxed_clone(),
4815 save_intent: *save_intent,
4816 });
4817 serialize_workspace = false;
4818 }
4819 pane::Event::ChangeItemTitle => {
4820 if *pane == self.active_pane {
4821 self.active_item_path_changed(false, window, cx);
4822 }
4823 serialize_workspace = false;
4824 }
4825 pane::Event::RemovedItem { item } => {
4826 cx.emit(Event::ActiveItemChanged);
4827 self.update_window_edited(window, cx);
4828 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
4829 && entry.get().entity_id() == pane.entity_id()
4830 {
4831 entry.remove();
4832 }
4833 cx.emit(Event::ItemRemoved {
4834 item_id: item.item_id(),
4835 });
4836 }
4837 pane::Event::Focus => {
4838 window.invalidate_character_coordinates();
4839 self.handle_pane_focused(pane.clone(), window, cx);
4840 }
4841 pane::Event::ZoomIn => {
4842 if *pane == self.active_pane {
4843 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
4844 if pane.read(cx).has_focus(window, cx) {
4845 self.zoomed = Some(pane.downgrade().into());
4846 self.zoomed_position = None;
4847 cx.emit(Event::ZoomChanged);
4848 }
4849 cx.notify();
4850 }
4851 }
4852 pane::Event::ZoomOut => {
4853 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4854 if self.zoomed_position.is_none() {
4855 self.zoomed = None;
4856 cx.emit(Event::ZoomChanged);
4857 }
4858 cx.notify();
4859 }
4860 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
4861 }
4862
4863 if serialize_workspace {
4864 self.serialize_workspace(window, cx);
4865 }
4866 }
4867
4868 pub fn unfollow_in_pane(
4869 &mut self,
4870 pane: &Entity<Pane>,
4871 window: &mut Window,
4872 cx: &mut Context<Workspace>,
4873 ) -> Option<CollaboratorId> {
4874 let leader_id = self.leader_for_pane(pane)?;
4875 self.unfollow(leader_id, window, cx);
4876 Some(leader_id)
4877 }
4878
4879 pub fn split_pane(
4880 &mut self,
4881 pane_to_split: Entity<Pane>,
4882 split_direction: SplitDirection,
4883 window: &mut Window,
4884 cx: &mut Context<Self>,
4885 ) -> Entity<Pane> {
4886 let new_pane = self.add_pane(window, cx);
4887 self.center
4888 .split(&pane_to_split, &new_pane, split_direction, cx);
4889 cx.notify();
4890 new_pane
4891 }
4892
4893 pub fn split_and_move(
4894 &mut self,
4895 pane: Entity<Pane>,
4896 direction: SplitDirection,
4897 window: &mut Window,
4898 cx: &mut Context<Self>,
4899 ) {
4900 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
4901 return;
4902 };
4903 let new_pane = self.add_pane(window, cx);
4904 new_pane.update(cx, |pane, cx| {
4905 pane.add_item(item, true, true, None, window, cx)
4906 });
4907 self.center.split(&pane, &new_pane, direction, cx);
4908 cx.notify();
4909 }
4910
4911 pub fn split_and_clone(
4912 &mut self,
4913 pane: Entity<Pane>,
4914 direction: SplitDirection,
4915 window: &mut Window,
4916 cx: &mut Context<Self>,
4917 ) -> Task<Option<Entity<Pane>>> {
4918 let Some(item) = pane.read(cx).active_item() else {
4919 return Task::ready(None);
4920 };
4921 if !item.can_split(cx) {
4922 return Task::ready(None);
4923 }
4924 let task = item.clone_on_split(self.database_id(), window, cx);
4925 cx.spawn_in(window, async move |this, cx| {
4926 if let Some(clone) = task.await {
4927 this.update_in(cx, |this, window, cx| {
4928 let new_pane = this.add_pane(window, cx);
4929 let nav_history = pane.read(cx).fork_nav_history();
4930 new_pane.update(cx, |pane, cx| {
4931 pane.set_nav_history(nav_history, cx);
4932 pane.add_item(clone, true, true, None, window, cx)
4933 });
4934 this.center.split(&pane, &new_pane, direction, cx);
4935 cx.notify();
4936 new_pane
4937 })
4938 .ok()
4939 } else {
4940 None
4941 }
4942 })
4943 }
4944
4945 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4946 let active_item = self.active_pane.read(cx).active_item();
4947 for pane in &self.panes {
4948 join_pane_into_active(&self.active_pane, pane, window, cx);
4949 }
4950 if let Some(active_item) = active_item {
4951 self.activate_item(active_item.as_ref(), true, true, window, cx);
4952 }
4953 cx.notify();
4954 }
4955
4956 pub fn join_pane_into_next(
4957 &mut self,
4958 pane: Entity<Pane>,
4959 window: &mut Window,
4960 cx: &mut Context<Self>,
4961 ) {
4962 let next_pane = self
4963 .find_pane_in_direction(SplitDirection::Right, cx)
4964 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
4965 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
4966 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
4967 let Some(next_pane) = next_pane else {
4968 return;
4969 };
4970 move_all_items(&pane, &next_pane, window, cx);
4971 cx.notify();
4972 }
4973
4974 fn remove_pane(
4975 &mut self,
4976 pane: Entity<Pane>,
4977 focus_on: Option<Entity<Pane>>,
4978 window: &mut Window,
4979 cx: &mut Context<Self>,
4980 ) {
4981 if self.center.remove(&pane, cx).unwrap() {
4982 self.force_remove_pane(&pane, &focus_on, window, cx);
4983 self.unfollow_in_pane(&pane, window, cx);
4984 self.last_leaders_by_pane.remove(&pane.downgrade());
4985 for removed_item in pane.read(cx).items() {
4986 self.panes_by_item.remove(&removed_item.item_id());
4987 }
4988
4989 cx.notify();
4990 } else {
4991 self.active_item_path_changed(true, window, cx);
4992 }
4993 cx.emit(Event::PaneRemoved);
4994 }
4995
4996 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
4997 &mut self.panes
4998 }
4999
5000 pub fn panes(&self) -> &[Entity<Pane>] {
5001 &self.panes
5002 }
5003
5004 pub fn active_pane(&self) -> &Entity<Pane> {
5005 &self.active_pane
5006 }
5007
5008 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5009 for dock in self.all_docks() {
5010 if dock.focus_handle(cx).contains_focused(window, cx)
5011 && let Some(pane) = dock
5012 .read(cx)
5013 .active_panel()
5014 .and_then(|panel| panel.pane(cx))
5015 {
5016 return pane;
5017 }
5018 }
5019 self.active_pane().clone()
5020 }
5021
5022 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5023 self.find_pane_in_direction(SplitDirection::Right, cx)
5024 .unwrap_or_else(|| {
5025 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5026 })
5027 }
5028
5029 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5030 self.pane_for_item_id(handle.item_id())
5031 }
5032
5033 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5034 let weak_pane = self.panes_by_item.get(&item_id)?;
5035 weak_pane.upgrade()
5036 }
5037
5038 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5039 self.panes
5040 .iter()
5041 .find(|pane| pane.entity_id() == entity_id)
5042 .cloned()
5043 }
5044
5045 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5046 self.follower_states.retain(|leader_id, state| {
5047 if *leader_id == CollaboratorId::PeerId(peer_id) {
5048 for item in state.items_by_leader_view_id.values() {
5049 item.view.set_leader_id(None, window, cx);
5050 }
5051 false
5052 } else {
5053 true
5054 }
5055 });
5056 cx.notify();
5057 }
5058
5059 pub fn start_following(
5060 &mut self,
5061 leader_id: impl Into<CollaboratorId>,
5062 window: &mut Window,
5063 cx: &mut Context<Self>,
5064 ) -> Option<Task<Result<()>>> {
5065 let leader_id = leader_id.into();
5066 let pane = self.active_pane().clone();
5067
5068 self.last_leaders_by_pane
5069 .insert(pane.downgrade(), leader_id);
5070 self.unfollow(leader_id, window, cx);
5071 self.unfollow_in_pane(&pane, window, cx);
5072 self.follower_states.insert(
5073 leader_id,
5074 FollowerState {
5075 center_pane: pane.clone(),
5076 dock_pane: None,
5077 active_view_id: None,
5078 items_by_leader_view_id: Default::default(),
5079 },
5080 );
5081 cx.notify();
5082
5083 match leader_id {
5084 CollaboratorId::PeerId(leader_peer_id) => {
5085 let room_id = self.active_call()?.room_id(cx)?;
5086 let project_id = self.project.read(cx).remote_id();
5087 let request = self.app_state.client.request(proto::Follow {
5088 room_id,
5089 project_id,
5090 leader_id: Some(leader_peer_id),
5091 });
5092
5093 Some(cx.spawn_in(window, async move |this, cx| {
5094 let response = request.await?;
5095 this.update(cx, |this, _| {
5096 let state = this
5097 .follower_states
5098 .get_mut(&leader_id)
5099 .context("following interrupted")?;
5100 state.active_view_id = response
5101 .active_view
5102 .as_ref()
5103 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5104 anyhow::Ok(())
5105 })??;
5106 if let Some(view) = response.active_view {
5107 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5108 }
5109 this.update_in(cx, |this, window, cx| {
5110 this.leader_updated(leader_id, window, cx)
5111 })?;
5112 Ok(())
5113 }))
5114 }
5115 CollaboratorId::Agent => {
5116 self.leader_updated(leader_id, window, cx)?;
5117 Some(Task::ready(Ok(())))
5118 }
5119 }
5120 }
5121
5122 pub fn follow_next_collaborator(
5123 &mut self,
5124 _: &FollowNextCollaborator,
5125 window: &mut Window,
5126 cx: &mut Context<Self>,
5127 ) {
5128 let collaborators = self.project.read(cx).collaborators();
5129 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5130 let mut collaborators = collaborators.keys().copied();
5131 for peer_id in collaborators.by_ref() {
5132 if CollaboratorId::PeerId(peer_id) == leader_id {
5133 break;
5134 }
5135 }
5136 collaborators.next().map(CollaboratorId::PeerId)
5137 } else if let Some(last_leader_id) =
5138 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5139 {
5140 match last_leader_id {
5141 CollaboratorId::PeerId(peer_id) => {
5142 if collaborators.contains_key(peer_id) {
5143 Some(*last_leader_id)
5144 } else {
5145 None
5146 }
5147 }
5148 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5149 }
5150 } else {
5151 None
5152 };
5153
5154 let pane = self.active_pane.clone();
5155 let Some(leader_id) = next_leader_id.or_else(|| {
5156 Some(CollaboratorId::PeerId(
5157 collaborators.keys().copied().next()?,
5158 ))
5159 }) else {
5160 return;
5161 };
5162 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5163 return;
5164 }
5165 if let Some(task) = self.start_following(leader_id, window, cx) {
5166 task.detach_and_log_err(cx)
5167 }
5168 }
5169
5170 pub fn follow(
5171 &mut self,
5172 leader_id: impl Into<CollaboratorId>,
5173 window: &mut Window,
5174 cx: &mut Context<Self>,
5175 ) {
5176 let leader_id = leader_id.into();
5177
5178 if let CollaboratorId::PeerId(peer_id) = leader_id {
5179 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5180 return;
5181 };
5182 let Some(remote_participant) =
5183 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5184 else {
5185 return;
5186 };
5187
5188 let project = self.project.read(cx);
5189
5190 let other_project_id = match remote_participant.location {
5191 ParticipantLocation::External => None,
5192 ParticipantLocation::UnsharedProject => None,
5193 ParticipantLocation::SharedProject { project_id } => {
5194 if Some(project_id) == project.remote_id() {
5195 None
5196 } else {
5197 Some(project_id)
5198 }
5199 }
5200 };
5201
5202 // if they are active in another project, follow there.
5203 if let Some(project_id) = other_project_id {
5204 let app_state = self.app_state.clone();
5205 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5206 .detach_and_log_err(cx);
5207 }
5208 }
5209
5210 // if you're already following, find the right pane and focus it.
5211 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5212 window.focus(&follower_state.pane().focus_handle(cx), cx);
5213
5214 return;
5215 }
5216
5217 // Otherwise, follow.
5218 if let Some(task) = self.start_following(leader_id, window, cx) {
5219 task.detach_and_log_err(cx)
5220 }
5221 }
5222
5223 pub fn unfollow(
5224 &mut self,
5225 leader_id: impl Into<CollaboratorId>,
5226 window: &mut Window,
5227 cx: &mut Context<Self>,
5228 ) -> Option<()> {
5229 cx.notify();
5230
5231 let leader_id = leader_id.into();
5232 let state = self.follower_states.remove(&leader_id)?;
5233 for (_, item) in state.items_by_leader_view_id {
5234 item.view.set_leader_id(None, window, cx);
5235 }
5236
5237 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5238 let project_id = self.project.read(cx).remote_id();
5239 let room_id = self.active_call()?.room_id(cx)?;
5240 self.app_state
5241 .client
5242 .send(proto::Unfollow {
5243 room_id,
5244 project_id,
5245 leader_id: Some(leader_peer_id),
5246 })
5247 .log_err();
5248 }
5249
5250 Some(())
5251 }
5252
5253 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5254 self.follower_states.contains_key(&id.into())
5255 }
5256
5257 fn active_item_path_changed(
5258 &mut self,
5259 focus_changed: bool,
5260 window: &mut Window,
5261 cx: &mut Context<Self>,
5262 ) {
5263 cx.emit(Event::ActiveItemChanged);
5264 let active_entry = self.active_project_path(cx);
5265 self.project.update(cx, |project, cx| {
5266 project.set_active_path(active_entry.clone(), cx)
5267 });
5268
5269 if focus_changed && let Some(project_path) = &active_entry {
5270 let git_store_entity = self.project.read(cx).git_store().clone();
5271 git_store_entity.update(cx, |git_store, cx| {
5272 git_store.set_active_repo_for_path(project_path, cx);
5273 });
5274 }
5275
5276 self.update_window_title(window, cx);
5277 }
5278
5279 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5280 let project = self.project().read(cx);
5281 let mut title = String::new();
5282
5283 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5284 let name = {
5285 let settings_location = SettingsLocation {
5286 worktree_id: worktree.read(cx).id(),
5287 path: RelPath::empty(),
5288 };
5289
5290 let settings = WorktreeSettings::get(Some(settings_location), cx);
5291 match &settings.project_name {
5292 Some(name) => name.as_str(),
5293 None => worktree.read(cx).root_name_str(),
5294 }
5295 };
5296 if i > 0 {
5297 title.push_str(", ");
5298 }
5299 title.push_str(name);
5300 }
5301
5302 if title.is_empty() {
5303 title = "empty project".to_string();
5304 }
5305
5306 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5307 let filename = path.path.file_name().or_else(|| {
5308 Some(
5309 project
5310 .worktree_for_id(path.worktree_id, cx)?
5311 .read(cx)
5312 .root_name_str(),
5313 )
5314 });
5315
5316 if let Some(filename) = filename {
5317 title.push_str(" — ");
5318 title.push_str(filename.as_ref());
5319 }
5320 }
5321
5322 if project.is_via_collab() {
5323 title.push_str(" ↙");
5324 } else if project.is_shared() {
5325 title.push_str(" ↗");
5326 }
5327
5328 if let Some(last_title) = self.last_window_title.as_ref()
5329 && &title == last_title
5330 {
5331 return;
5332 }
5333 window.set_window_title(&title);
5334 SystemWindowTabController::update_tab_title(
5335 cx,
5336 window.window_handle().window_id(),
5337 SharedString::from(&title),
5338 );
5339 self.last_window_title = Some(title);
5340 }
5341
5342 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5343 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5344 if is_edited != self.window_edited {
5345 self.window_edited = is_edited;
5346 window.set_window_edited(self.window_edited)
5347 }
5348 }
5349
5350 fn update_item_dirty_state(
5351 &mut self,
5352 item: &dyn ItemHandle,
5353 window: &mut Window,
5354 cx: &mut App,
5355 ) {
5356 let is_dirty = item.is_dirty(cx);
5357 let item_id = item.item_id();
5358 let was_dirty = self.dirty_items.contains_key(&item_id);
5359 if is_dirty == was_dirty {
5360 return;
5361 }
5362 if was_dirty {
5363 self.dirty_items.remove(&item_id);
5364 self.update_window_edited(window, cx);
5365 return;
5366 }
5367
5368 let workspace = self.weak_handle();
5369 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5370 return;
5371 };
5372 let on_release_callback = Box::new(move |cx: &mut App| {
5373 window_handle
5374 .update(cx, |_, window, cx| {
5375 workspace
5376 .update(cx, |workspace, cx| {
5377 workspace.dirty_items.remove(&item_id);
5378 workspace.update_window_edited(window, cx)
5379 })
5380 .ok();
5381 })
5382 .ok();
5383 });
5384
5385 let s = item.on_release(cx, on_release_callback);
5386 self.dirty_items.insert(item_id, s);
5387 self.update_window_edited(window, cx);
5388 }
5389
5390 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5391 if self.notifications.is_empty() {
5392 None
5393 } else {
5394 Some(
5395 div()
5396 .absolute()
5397 .right_3()
5398 .bottom_3()
5399 .w_112()
5400 .h_full()
5401 .flex()
5402 .flex_col()
5403 .justify_end()
5404 .gap_2()
5405 .children(
5406 self.notifications
5407 .iter()
5408 .map(|(_, notification)| notification.clone().into_any()),
5409 ),
5410 )
5411 }
5412 }
5413
5414 // RPC handlers
5415
5416 fn active_view_for_follower(
5417 &self,
5418 follower_project_id: Option<u64>,
5419 window: &mut Window,
5420 cx: &mut Context<Self>,
5421 ) -> Option<proto::View> {
5422 let (item, panel_id) = self.active_item_for_followers(window, cx);
5423 let item = item?;
5424 let leader_id = self
5425 .pane_for(&*item)
5426 .and_then(|pane| self.leader_for_pane(&pane));
5427 let leader_peer_id = match leader_id {
5428 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5429 Some(CollaboratorId::Agent) | None => None,
5430 };
5431
5432 let item_handle = item.to_followable_item_handle(cx)?;
5433 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5434 let variant = item_handle.to_state_proto(window, cx)?;
5435
5436 if item_handle.is_project_item(window, cx)
5437 && (follower_project_id.is_none()
5438 || follower_project_id != self.project.read(cx).remote_id())
5439 {
5440 return None;
5441 }
5442
5443 Some(proto::View {
5444 id: id.to_proto(),
5445 leader_id: leader_peer_id,
5446 variant: Some(variant),
5447 panel_id: panel_id.map(|id| id as i32),
5448 })
5449 }
5450
5451 fn handle_follow(
5452 &mut self,
5453 follower_project_id: Option<u64>,
5454 window: &mut Window,
5455 cx: &mut Context<Self>,
5456 ) -> proto::FollowResponse {
5457 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5458
5459 cx.notify();
5460 proto::FollowResponse {
5461 views: active_view.iter().cloned().collect(),
5462 active_view,
5463 }
5464 }
5465
5466 fn handle_update_followers(
5467 &mut self,
5468 leader_id: PeerId,
5469 message: proto::UpdateFollowers,
5470 _window: &mut Window,
5471 _cx: &mut Context<Self>,
5472 ) {
5473 self.leader_updates_tx
5474 .unbounded_send((leader_id, message))
5475 .ok();
5476 }
5477
5478 async fn process_leader_update(
5479 this: &WeakEntity<Self>,
5480 leader_id: PeerId,
5481 update: proto::UpdateFollowers,
5482 cx: &mut AsyncWindowContext,
5483 ) -> Result<()> {
5484 match update.variant.context("invalid update")? {
5485 proto::update_followers::Variant::CreateView(view) => {
5486 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5487 let should_add_view = this.update(cx, |this, _| {
5488 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5489 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5490 } else {
5491 anyhow::Ok(false)
5492 }
5493 })??;
5494
5495 if should_add_view {
5496 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5497 }
5498 }
5499 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5500 let should_add_view = this.update(cx, |this, _| {
5501 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5502 state.active_view_id = update_active_view
5503 .view
5504 .as_ref()
5505 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5506
5507 if state.active_view_id.is_some_and(|view_id| {
5508 !state.items_by_leader_view_id.contains_key(&view_id)
5509 }) {
5510 anyhow::Ok(true)
5511 } else {
5512 anyhow::Ok(false)
5513 }
5514 } else {
5515 anyhow::Ok(false)
5516 }
5517 })??;
5518
5519 if should_add_view && let Some(view) = update_active_view.view {
5520 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5521 }
5522 }
5523 proto::update_followers::Variant::UpdateView(update_view) => {
5524 let variant = update_view.variant.context("missing update view variant")?;
5525 let id = update_view.id.context("missing update view id")?;
5526 let mut tasks = Vec::new();
5527 this.update_in(cx, |this, window, cx| {
5528 let project = this.project.clone();
5529 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5530 let view_id = ViewId::from_proto(id.clone())?;
5531 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5532 tasks.push(item.view.apply_update_proto(
5533 &project,
5534 variant.clone(),
5535 window,
5536 cx,
5537 ));
5538 }
5539 }
5540 anyhow::Ok(())
5541 })??;
5542 try_join_all(tasks).await.log_err();
5543 }
5544 }
5545 this.update_in(cx, |this, window, cx| {
5546 this.leader_updated(leader_id, window, cx)
5547 })?;
5548 Ok(())
5549 }
5550
5551 async fn add_view_from_leader(
5552 this: WeakEntity<Self>,
5553 leader_id: PeerId,
5554 view: &proto::View,
5555 cx: &mut AsyncWindowContext,
5556 ) -> Result<()> {
5557 let this = this.upgrade().context("workspace dropped")?;
5558
5559 let Some(id) = view.id.clone() else {
5560 anyhow::bail!("no id for view");
5561 };
5562 let id = ViewId::from_proto(id)?;
5563 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5564
5565 let pane = this.update(cx, |this, _cx| {
5566 let state = this
5567 .follower_states
5568 .get(&leader_id.into())
5569 .context("stopped following")?;
5570 anyhow::Ok(state.pane().clone())
5571 })?;
5572 let existing_item = pane.update_in(cx, |pane, window, cx| {
5573 let client = this.read(cx).client().clone();
5574 pane.items().find_map(|item| {
5575 let item = item.to_followable_item_handle(cx)?;
5576 if item.remote_id(&client, window, cx) == Some(id) {
5577 Some(item)
5578 } else {
5579 None
5580 }
5581 })
5582 })?;
5583 let item = if let Some(existing_item) = existing_item {
5584 existing_item
5585 } else {
5586 let variant = view.variant.clone();
5587 anyhow::ensure!(variant.is_some(), "missing view variant");
5588
5589 let task = cx.update(|window, cx| {
5590 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5591 })?;
5592
5593 let Some(task) = task else {
5594 anyhow::bail!(
5595 "failed to construct view from leader (maybe from a different version of zed?)"
5596 );
5597 };
5598
5599 let mut new_item = task.await?;
5600 pane.update_in(cx, |pane, window, cx| {
5601 let mut item_to_remove = None;
5602 for (ix, item) in pane.items().enumerate() {
5603 if let Some(item) = item.to_followable_item_handle(cx) {
5604 match new_item.dedup(item.as_ref(), window, cx) {
5605 Some(item::Dedup::KeepExisting) => {
5606 new_item =
5607 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5608 break;
5609 }
5610 Some(item::Dedup::ReplaceExisting) => {
5611 item_to_remove = Some((ix, item.item_id()));
5612 break;
5613 }
5614 None => {}
5615 }
5616 }
5617 }
5618
5619 if let Some((ix, id)) = item_to_remove {
5620 pane.remove_item(id, false, false, window, cx);
5621 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5622 }
5623 })?;
5624
5625 new_item
5626 };
5627
5628 this.update_in(cx, |this, window, cx| {
5629 let state = this.follower_states.get_mut(&leader_id.into())?;
5630 item.set_leader_id(Some(leader_id.into()), window, cx);
5631 state.items_by_leader_view_id.insert(
5632 id,
5633 FollowerView {
5634 view: item,
5635 location: panel_id,
5636 },
5637 );
5638
5639 Some(())
5640 })
5641 .context("no follower state")?;
5642
5643 Ok(())
5644 }
5645
5646 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5647 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5648 return;
5649 };
5650
5651 if let Some(agent_location) = self.project.read(cx).agent_location() {
5652 let buffer_entity_id = agent_location.buffer.entity_id();
5653 let view_id = ViewId {
5654 creator: CollaboratorId::Agent,
5655 id: buffer_entity_id.as_u64(),
5656 };
5657 follower_state.active_view_id = Some(view_id);
5658
5659 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5660 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5661 hash_map::Entry::Vacant(entry) => {
5662 let existing_view =
5663 follower_state
5664 .center_pane
5665 .read(cx)
5666 .items()
5667 .find_map(|item| {
5668 let item = item.to_followable_item_handle(cx)?;
5669 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5670 && item.project_item_model_ids(cx).as_slice()
5671 == [buffer_entity_id]
5672 {
5673 Some(item)
5674 } else {
5675 None
5676 }
5677 });
5678 let view = existing_view.or_else(|| {
5679 agent_location.buffer.upgrade().and_then(|buffer| {
5680 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
5681 registry.build_item(buffer, self.project.clone(), None, window, cx)
5682 })?
5683 .to_followable_item_handle(cx)
5684 })
5685 });
5686
5687 view.map(|view| {
5688 entry.insert(FollowerView {
5689 view,
5690 location: None,
5691 })
5692 })
5693 }
5694 };
5695
5696 if let Some(item) = item {
5697 item.view
5698 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
5699 item.view
5700 .update_agent_location(agent_location.position, window, cx);
5701 }
5702 } else {
5703 follower_state.active_view_id = None;
5704 }
5705
5706 self.leader_updated(CollaboratorId::Agent, window, cx);
5707 }
5708
5709 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
5710 let mut is_project_item = true;
5711 let mut update = proto::UpdateActiveView::default();
5712 if window.is_window_active() {
5713 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
5714
5715 if let Some(item) = active_item
5716 && item.item_focus_handle(cx).contains_focused(window, cx)
5717 {
5718 let leader_id = self
5719 .pane_for(&*item)
5720 .and_then(|pane| self.leader_for_pane(&pane));
5721 let leader_peer_id = match leader_id {
5722 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5723 Some(CollaboratorId::Agent) | None => None,
5724 };
5725
5726 if let Some(item) = item.to_followable_item_handle(cx) {
5727 let id = item
5728 .remote_id(&self.app_state.client, window, cx)
5729 .map(|id| id.to_proto());
5730
5731 if let Some(id) = id
5732 && let Some(variant) = item.to_state_proto(window, cx)
5733 {
5734 let view = Some(proto::View {
5735 id,
5736 leader_id: leader_peer_id,
5737 variant: Some(variant),
5738 panel_id: panel_id.map(|id| id as i32),
5739 });
5740
5741 is_project_item = item.is_project_item(window, cx);
5742 update = proto::UpdateActiveView { view };
5743 };
5744 }
5745 }
5746 }
5747
5748 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
5749 if active_view_id != self.last_active_view_id.as_ref() {
5750 self.last_active_view_id = active_view_id.cloned();
5751 self.update_followers(
5752 is_project_item,
5753 proto::update_followers::Variant::UpdateActiveView(update),
5754 window,
5755 cx,
5756 );
5757 }
5758 }
5759
5760 fn active_item_for_followers(
5761 &self,
5762 window: &mut Window,
5763 cx: &mut App,
5764 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
5765 let mut active_item = None;
5766 let mut panel_id = None;
5767 for dock in self.all_docks() {
5768 if dock.focus_handle(cx).contains_focused(window, cx)
5769 && let Some(panel) = dock.read(cx).active_panel()
5770 && let Some(pane) = panel.pane(cx)
5771 && let Some(item) = pane.read(cx).active_item()
5772 {
5773 active_item = Some(item);
5774 panel_id = panel.remote_id();
5775 break;
5776 }
5777 }
5778
5779 if active_item.is_none() {
5780 active_item = self.active_pane().read(cx).active_item();
5781 }
5782 (active_item, panel_id)
5783 }
5784
5785 fn update_followers(
5786 &self,
5787 project_only: bool,
5788 update: proto::update_followers::Variant,
5789 _: &mut Window,
5790 cx: &mut App,
5791 ) -> Option<()> {
5792 // If this update only applies to for followers in the current project,
5793 // then skip it unless this project is shared. If it applies to all
5794 // followers, regardless of project, then set `project_id` to none,
5795 // indicating that it goes to all followers.
5796 let project_id = if project_only {
5797 Some(self.project.read(cx).remote_id()?)
5798 } else {
5799 None
5800 };
5801 self.app_state().workspace_store.update(cx, |store, cx| {
5802 store.update_followers(project_id, update, cx)
5803 })
5804 }
5805
5806 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
5807 self.follower_states.iter().find_map(|(leader_id, state)| {
5808 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
5809 Some(*leader_id)
5810 } else {
5811 None
5812 }
5813 })
5814 }
5815
5816 fn leader_updated(
5817 &mut self,
5818 leader_id: impl Into<CollaboratorId>,
5819 window: &mut Window,
5820 cx: &mut Context<Self>,
5821 ) -> Option<Box<dyn ItemHandle>> {
5822 cx.notify();
5823
5824 let leader_id = leader_id.into();
5825 let (panel_id, item) = match leader_id {
5826 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
5827 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
5828 };
5829
5830 let state = self.follower_states.get(&leader_id)?;
5831 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
5832 let pane;
5833 if let Some(panel_id) = panel_id {
5834 pane = self
5835 .activate_panel_for_proto_id(panel_id, window, cx)?
5836 .pane(cx)?;
5837 let state = self.follower_states.get_mut(&leader_id)?;
5838 state.dock_pane = Some(pane.clone());
5839 } else {
5840 pane = state.center_pane.clone();
5841 let state = self.follower_states.get_mut(&leader_id)?;
5842 if let Some(dock_pane) = state.dock_pane.take() {
5843 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
5844 }
5845 }
5846
5847 pane.update(cx, |pane, cx| {
5848 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
5849 if let Some(index) = pane.index_for_item(item.as_ref()) {
5850 pane.activate_item(index, false, false, window, cx);
5851 } else {
5852 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
5853 }
5854
5855 if focus_active_item {
5856 pane.focus_active_item(window, cx)
5857 }
5858 });
5859
5860 Some(item)
5861 }
5862
5863 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
5864 let state = self.follower_states.get(&CollaboratorId::Agent)?;
5865 let active_view_id = state.active_view_id?;
5866 Some(
5867 state
5868 .items_by_leader_view_id
5869 .get(&active_view_id)?
5870 .view
5871 .boxed_clone(),
5872 )
5873 }
5874
5875 fn active_item_for_peer(
5876 &self,
5877 peer_id: PeerId,
5878 window: &mut Window,
5879 cx: &mut Context<Self>,
5880 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
5881 let call = self.active_call()?;
5882 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
5883 let leader_in_this_app;
5884 let leader_in_this_project;
5885 match participant.location {
5886 ParticipantLocation::SharedProject { project_id } => {
5887 leader_in_this_app = true;
5888 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
5889 }
5890 ParticipantLocation::UnsharedProject => {
5891 leader_in_this_app = true;
5892 leader_in_this_project = false;
5893 }
5894 ParticipantLocation::External => {
5895 leader_in_this_app = false;
5896 leader_in_this_project = false;
5897 }
5898 };
5899 let state = self.follower_states.get(&peer_id.into())?;
5900 let mut item_to_activate = None;
5901 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
5902 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
5903 && (leader_in_this_project || !item.view.is_project_item(window, cx))
5904 {
5905 item_to_activate = Some((item.location, item.view.boxed_clone()));
5906 }
5907 } else if let Some(shared_screen) =
5908 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
5909 {
5910 item_to_activate = Some((None, Box::new(shared_screen)));
5911 }
5912 item_to_activate
5913 }
5914
5915 fn shared_screen_for_peer(
5916 &self,
5917 peer_id: PeerId,
5918 pane: &Entity<Pane>,
5919 window: &mut Window,
5920 cx: &mut App,
5921 ) -> Option<Entity<SharedScreen>> {
5922 self.active_call()?
5923 .create_shared_screen(peer_id, pane, window, cx)
5924 }
5925
5926 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5927 if window.is_window_active() {
5928 self.update_active_view_for_followers(window, cx);
5929
5930 if let Some(database_id) = self.database_id {
5931 cx.background_spawn(persistence::DB.update_timestamp(database_id))
5932 .detach();
5933 }
5934 } else {
5935 for pane in &self.panes {
5936 pane.update(cx, |pane, cx| {
5937 if let Some(item) = pane.active_item() {
5938 item.workspace_deactivated(window, cx);
5939 }
5940 for item in pane.items() {
5941 if matches!(
5942 item.workspace_settings(cx).autosave,
5943 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
5944 ) {
5945 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
5946 .detach_and_log_err(cx);
5947 }
5948 }
5949 });
5950 }
5951 }
5952 }
5953
5954 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
5955 self.active_call.as_ref().map(|(call, _)| &*call.0)
5956 }
5957
5958 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
5959 self.active_call.as_ref().map(|(call, _)| call.clone())
5960 }
5961
5962 fn on_active_call_event(
5963 &mut self,
5964 event: &ActiveCallEvent,
5965 window: &mut Window,
5966 cx: &mut Context<Self>,
5967 ) {
5968 match event {
5969 ActiveCallEvent::ParticipantLocationChanged { participant_id }
5970 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
5971 self.leader_updated(participant_id, window, cx);
5972 }
5973 }
5974 }
5975
5976 pub fn database_id(&self) -> Option<WorkspaceId> {
5977 self.database_id
5978 }
5979
5980 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
5981 self.database_id = Some(id);
5982 }
5983
5984 pub fn session_id(&self) -> Option<String> {
5985 self.session_id.clone()
5986 }
5987
5988 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
5989 let Some(display) = window.display(cx) else {
5990 return Task::ready(());
5991 };
5992 let Ok(display_uuid) = display.uuid() else {
5993 return Task::ready(());
5994 };
5995
5996 let window_bounds = window.inner_window_bounds();
5997 let database_id = self.database_id;
5998 let has_paths = !self.root_paths(cx).is_empty();
5999
6000 cx.background_executor().spawn(async move {
6001 if !has_paths {
6002 persistence::write_default_window_bounds(window_bounds, display_uuid)
6003 .await
6004 .log_err();
6005 }
6006 if let Some(database_id) = database_id {
6007 DB.set_window_open_status(
6008 database_id,
6009 SerializedWindowBounds(window_bounds),
6010 display_uuid,
6011 )
6012 .await
6013 .log_err();
6014 } else {
6015 persistence::write_default_window_bounds(window_bounds, display_uuid)
6016 .await
6017 .log_err();
6018 }
6019 })
6020 }
6021
6022 /// Bypass the 200ms serialization throttle and write workspace state to
6023 /// the DB immediately. Returns a task the caller can await to ensure the
6024 /// write completes. Used by the quit handler so the most recent state
6025 /// isn't lost to a pending throttle timer when the process exits.
6026 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6027 self._schedule_serialize_workspace.take();
6028 self._serialize_workspace_task.take();
6029 self.bounds_save_task_queued.take();
6030
6031 let bounds_task = self.save_window_bounds(window, cx);
6032 let serialize_task = self.serialize_workspace_internal(window, cx);
6033 cx.spawn(async move |_| {
6034 bounds_task.await;
6035 serialize_task.await;
6036 })
6037 }
6038
6039 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6040 let project = self.project().read(cx);
6041 project
6042 .visible_worktrees(cx)
6043 .map(|worktree| worktree.read(cx).abs_path())
6044 .collect::<Vec<_>>()
6045 }
6046
6047 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6048 match member {
6049 Member::Axis(PaneAxis { members, .. }) => {
6050 for child in members.iter() {
6051 self.remove_panes(child.clone(), window, cx)
6052 }
6053 }
6054 Member::Pane(pane) => {
6055 self.force_remove_pane(&pane, &None, window, cx);
6056 }
6057 }
6058 }
6059
6060 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6061 self.session_id.take();
6062 self.serialize_workspace_internal(window, cx)
6063 }
6064
6065 fn force_remove_pane(
6066 &mut self,
6067 pane: &Entity<Pane>,
6068 focus_on: &Option<Entity<Pane>>,
6069 window: &mut Window,
6070 cx: &mut Context<Workspace>,
6071 ) {
6072 self.panes.retain(|p| p != pane);
6073 if let Some(focus_on) = focus_on {
6074 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6075 } else if self.active_pane() == pane {
6076 self.panes
6077 .last()
6078 .unwrap()
6079 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6080 }
6081 if self.last_active_center_pane == Some(pane.downgrade()) {
6082 self.last_active_center_pane = None;
6083 }
6084 cx.notify();
6085 }
6086
6087 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6088 if self._schedule_serialize_workspace.is_none() {
6089 self._schedule_serialize_workspace =
6090 Some(cx.spawn_in(window, async move |this, cx| {
6091 cx.background_executor()
6092 .timer(SERIALIZATION_THROTTLE_TIME)
6093 .await;
6094 this.update_in(cx, |this, window, cx| {
6095 this._serialize_workspace_task =
6096 Some(this.serialize_workspace_internal(window, cx));
6097 this._schedule_serialize_workspace.take();
6098 })
6099 .log_err();
6100 }));
6101 }
6102 }
6103
6104 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6105 let Some(database_id) = self.database_id() else {
6106 return Task::ready(());
6107 };
6108
6109 fn serialize_pane_handle(
6110 pane_handle: &Entity<Pane>,
6111 window: &mut Window,
6112 cx: &mut App,
6113 ) -> SerializedPane {
6114 let (items, active, pinned_count) = {
6115 let pane = pane_handle.read(cx);
6116 let active_item_id = pane.active_item().map(|item| item.item_id());
6117 (
6118 pane.items()
6119 .filter_map(|handle| {
6120 let handle = handle.to_serializable_item_handle(cx)?;
6121
6122 Some(SerializedItem {
6123 kind: Arc::from(handle.serialized_item_kind()),
6124 item_id: handle.item_id().as_u64(),
6125 active: Some(handle.item_id()) == active_item_id,
6126 preview: pane.is_active_preview_item(handle.item_id()),
6127 })
6128 })
6129 .collect::<Vec<_>>(),
6130 pane.has_focus(window, cx),
6131 pane.pinned_count(),
6132 )
6133 };
6134
6135 SerializedPane::new(items, active, pinned_count)
6136 }
6137
6138 fn build_serialized_pane_group(
6139 pane_group: &Member,
6140 window: &mut Window,
6141 cx: &mut App,
6142 ) -> SerializedPaneGroup {
6143 match pane_group {
6144 Member::Axis(PaneAxis {
6145 axis,
6146 members,
6147 flexes,
6148 bounding_boxes: _,
6149 }) => SerializedPaneGroup::Group {
6150 axis: SerializedAxis(*axis),
6151 children: members
6152 .iter()
6153 .map(|member| build_serialized_pane_group(member, window, cx))
6154 .collect::<Vec<_>>(),
6155 flexes: Some(flexes.lock().clone()),
6156 },
6157 Member::Pane(pane_handle) => {
6158 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6159 }
6160 }
6161 }
6162
6163 fn build_serialized_docks(
6164 this: &Workspace,
6165 window: &mut Window,
6166 cx: &mut App,
6167 ) -> DockStructure {
6168 this.capture_dock_state(window, cx)
6169 }
6170
6171 match self.workspace_location(cx) {
6172 WorkspaceLocation::Location(location, paths) => {
6173 let breakpoints = self.project.update(cx, |project, cx| {
6174 project
6175 .breakpoint_store()
6176 .read(cx)
6177 .all_source_breakpoints(cx)
6178 });
6179 let user_toolchains = self
6180 .project
6181 .read(cx)
6182 .user_toolchains(cx)
6183 .unwrap_or_default();
6184
6185 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6186 let docks = build_serialized_docks(self, window, cx);
6187 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6188
6189 let serialized_workspace = SerializedWorkspace {
6190 id: database_id,
6191 location,
6192 paths,
6193 center_group,
6194 window_bounds,
6195 display: Default::default(),
6196 docks,
6197 centered_layout: self.centered_layout,
6198 session_id: self.session_id.clone(),
6199 breakpoints,
6200 window_id: Some(window.window_handle().window_id().as_u64()),
6201 user_toolchains,
6202 };
6203
6204 window.spawn(cx, async move |_| {
6205 persistence::DB.save_workspace(serialized_workspace).await;
6206 })
6207 }
6208 WorkspaceLocation::DetachFromSession => {
6209 let window_bounds = SerializedWindowBounds(window.window_bounds());
6210 let display = window.display(cx).and_then(|d| d.uuid().ok());
6211 // Save dock state for empty local workspaces
6212 let docks = build_serialized_docks(self, window, cx);
6213 window.spawn(cx, async move |_| {
6214 persistence::DB
6215 .set_window_open_status(
6216 database_id,
6217 window_bounds,
6218 display.unwrap_or_default(),
6219 )
6220 .await
6221 .log_err();
6222 persistence::DB
6223 .set_session_id(database_id, None)
6224 .await
6225 .log_err();
6226 persistence::write_default_dock_state(docks).await.log_err();
6227 })
6228 }
6229 WorkspaceLocation::None => {
6230 // Save dock state for empty non-local workspaces
6231 let docks = build_serialized_docks(self, window, cx);
6232 window.spawn(cx, async move |_| {
6233 persistence::write_default_dock_state(docks).await.log_err();
6234 })
6235 }
6236 }
6237 }
6238
6239 fn has_any_items_open(&self, cx: &App) -> bool {
6240 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6241 }
6242
6243 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6244 let paths = PathList::new(&self.root_paths(cx));
6245 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6246 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6247 } else if self.project.read(cx).is_local() {
6248 if !paths.is_empty() || self.has_any_items_open(cx) {
6249 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6250 } else {
6251 WorkspaceLocation::DetachFromSession
6252 }
6253 } else {
6254 WorkspaceLocation::None
6255 }
6256 }
6257
6258 fn update_history(&self, cx: &mut App) {
6259 let Some(id) = self.database_id() else {
6260 return;
6261 };
6262 if !self.project.read(cx).is_local() {
6263 return;
6264 }
6265 if let Some(manager) = HistoryManager::global(cx) {
6266 let paths = PathList::new(&self.root_paths(cx));
6267 manager.update(cx, |this, cx| {
6268 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6269 });
6270 }
6271 }
6272
6273 async fn serialize_items(
6274 this: &WeakEntity<Self>,
6275 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6276 cx: &mut AsyncWindowContext,
6277 ) -> Result<()> {
6278 const CHUNK_SIZE: usize = 200;
6279
6280 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6281
6282 while let Some(items_received) = serializable_items.next().await {
6283 let unique_items =
6284 items_received
6285 .into_iter()
6286 .fold(HashMap::default(), |mut acc, item| {
6287 acc.entry(item.item_id()).or_insert(item);
6288 acc
6289 });
6290
6291 // We use into_iter() here so that the references to the items are moved into
6292 // the tasks and not kept alive while we're sleeping.
6293 for (_, item) in unique_items.into_iter() {
6294 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6295 item.serialize(workspace, false, window, cx)
6296 }) {
6297 cx.background_spawn(async move { task.await.log_err() })
6298 .detach();
6299 }
6300 }
6301
6302 cx.background_executor()
6303 .timer(SERIALIZATION_THROTTLE_TIME)
6304 .await;
6305 }
6306
6307 Ok(())
6308 }
6309
6310 pub(crate) fn enqueue_item_serialization(
6311 &mut self,
6312 item: Box<dyn SerializableItemHandle>,
6313 ) -> Result<()> {
6314 self.serializable_items_tx
6315 .unbounded_send(item)
6316 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6317 }
6318
6319 pub(crate) fn load_workspace(
6320 serialized_workspace: SerializedWorkspace,
6321 paths_to_open: Vec<Option<ProjectPath>>,
6322 window: &mut Window,
6323 cx: &mut Context<Workspace>,
6324 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6325 cx.spawn_in(window, async move |workspace, cx| {
6326 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6327
6328 let mut center_group = None;
6329 let mut center_items = None;
6330
6331 // Traverse the splits tree and add to things
6332 if let Some((group, active_pane, items)) = serialized_workspace
6333 .center_group
6334 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6335 .await
6336 {
6337 center_items = Some(items);
6338 center_group = Some((group, active_pane))
6339 }
6340
6341 let mut items_by_project_path = HashMap::default();
6342 let mut item_ids_by_kind = HashMap::default();
6343 let mut all_deserialized_items = Vec::default();
6344 cx.update(|_, cx| {
6345 for item in center_items.unwrap_or_default().into_iter().flatten() {
6346 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6347 item_ids_by_kind
6348 .entry(serializable_item_handle.serialized_item_kind())
6349 .or_insert(Vec::new())
6350 .push(item.item_id().as_u64() as ItemId);
6351 }
6352
6353 if let Some(project_path) = item.project_path(cx) {
6354 items_by_project_path.insert(project_path, item.clone());
6355 }
6356 all_deserialized_items.push(item);
6357 }
6358 })?;
6359
6360 let opened_items = paths_to_open
6361 .into_iter()
6362 .map(|path_to_open| {
6363 path_to_open
6364 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6365 })
6366 .collect::<Vec<_>>();
6367
6368 // Remove old panes from workspace panes list
6369 workspace.update_in(cx, |workspace, window, cx| {
6370 if let Some((center_group, active_pane)) = center_group {
6371 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6372
6373 // Swap workspace center group
6374 workspace.center = PaneGroup::with_root(center_group);
6375 workspace.center.set_is_center(true);
6376 workspace.center.mark_positions(cx);
6377
6378 if let Some(active_pane) = active_pane {
6379 workspace.set_active_pane(&active_pane, window, cx);
6380 cx.focus_self(window);
6381 } else {
6382 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6383 }
6384 }
6385
6386 let docks = serialized_workspace.docks;
6387
6388 for (dock, serialized_dock) in [
6389 (&mut workspace.right_dock, docks.right),
6390 (&mut workspace.left_dock, docks.left),
6391 (&mut workspace.bottom_dock, docks.bottom),
6392 ]
6393 .iter_mut()
6394 {
6395 dock.update(cx, |dock, cx| {
6396 dock.serialized_dock = Some(serialized_dock.clone());
6397 dock.restore_state(window, cx);
6398 });
6399 }
6400
6401 cx.notify();
6402 })?;
6403
6404 let _ = project
6405 .update(cx, |project, cx| {
6406 project
6407 .breakpoint_store()
6408 .update(cx, |breakpoint_store, cx| {
6409 breakpoint_store
6410 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6411 })
6412 })
6413 .await;
6414
6415 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6416 // after loading the items, we might have different items and in order to avoid
6417 // the database filling up, we delete items that haven't been loaded now.
6418 //
6419 // The items that have been loaded, have been saved after they've been added to the workspace.
6420 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6421 item_ids_by_kind
6422 .into_iter()
6423 .map(|(item_kind, loaded_items)| {
6424 SerializableItemRegistry::cleanup(
6425 item_kind,
6426 serialized_workspace.id,
6427 loaded_items,
6428 window,
6429 cx,
6430 )
6431 .log_err()
6432 })
6433 .collect::<Vec<_>>()
6434 })?;
6435
6436 futures::future::join_all(clean_up_tasks).await;
6437
6438 workspace
6439 .update_in(cx, |workspace, window, cx| {
6440 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6441 workspace.serialize_workspace_internal(window, cx).detach();
6442
6443 // Ensure that we mark the window as edited if we did load dirty items
6444 workspace.update_window_edited(window, cx);
6445 })
6446 .ok();
6447
6448 Ok(opened_items)
6449 })
6450 }
6451
6452 pub fn key_context(&self, cx: &App) -> KeyContext {
6453 let mut context = KeyContext::new_with_defaults();
6454 context.add("Workspace");
6455 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6456 if let Some(status) = self
6457 .debugger_provider
6458 .as_ref()
6459 .and_then(|provider| provider.active_thread_state(cx))
6460 {
6461 match status {
6462 ThreadStatus::Running | ThreadStatus::Stepping => {
6463 context.add("debugger_running");
6464 }
6465 ThreadStatus::Stopped => context.add("debugger_stopped"),
6466 ThreadStatus::Exited | ThreadStatus::Ended => {}
6467 }
6468 }
6469
6470 if self.left_dock.read(cx).is_open() {
6471 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6472 context.set("left_dock", active_panel.panel_key());
6473 }
6474 }
6475
6476 if self.right_dock.read(cx).is_open() {
6477 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6478 context.set("right_dock", active_panel.panel_key());
6479 }
6480 }
6481
6482 if self.bottom_dock.read(cx).is_open() {
6483 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6484 context.set("bottom_dock", active_panel.panel_key());
6485 }
6486 }
6487
6488 context
6489 }
6490
6491 /// Multiworkspace uses this to add workspace action handling to itself
6492 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6493 self.add_workspace_actions_listeners(div, window, cx)
6494 .on_action(cx.listener(
6495 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6496 for action in &action_sequence.0 {
6497 window.dispatch_action(action.boxed_clone(), cx);
6498 }
6499 },
6500 ))
6501 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6502 .on_action(cx.listener(Self::close_all_items_and_panes))
6503 .on_action(cx.listener(Self::close_item_in_all_panes))
6504 .on_action(cx.listener(Self::save_all))
6505 .on_action(cx.listener(Self::send_keystrokes))
6506 .on_action(cx.listener(Self::add_folder_to_project))
6507 .on_action(cx.listener(Self::follow_next_collaborator))
6508 .on_action(cx.listener(Self::activate_pane_at_index))
6509 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6510 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6511 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6512 .on_action(cx.listener(Self::toggle_theme_mode))
6513 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6514 let pane = workspace.active_pane().clone();
6515 workspace.unfollow_in_pane(&pane, window, cx);
6516 }))
6517 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6518 workspace
6519 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6520 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6521 }))
6522 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6523 workspace
6524 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6525 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6526 }))
6527 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6528 workspace
6529 .save_active_item(SaveIntent::SaveAs, window, cx)
6530 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6531 }))
6532 .on_action(
6533 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6534 workspace.activate_previous_pane(window, cx)
6535 }),
6536 )
6537 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6538 workspace.activate_next_pane(window, cx)
6539 }))
6540 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6541 workspace.activate_last_pane(window, cx)
6542 }))
6543 .on_action(
6544 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6545 workspace.activate_next_window(cx)
6546 }),
6547 )
6548 .on_action(
6549 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6550 workspace.activate_previous_window(cx)
6551 }),
6552 )
6553 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6554 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6555 }))
6556 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6557 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6558 }))
6559 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6560 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6561 }))
6562 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6563 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6564 }))
6565 .on_action(cx.listener(
6566 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6567 workspace.move_item_to_pane_in_direction(action, window, cx)
6568 },
6569 ))
6570 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6571 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6572 }))
6573 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6574 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6575 }))
6576 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6577 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6578 }))
6579 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6580 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6581 }))
6582 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6583 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6584 SplitDirection::Down,
6585 SplitDirection::Up,
6586 SplitDirection::Right,
6587 SplitDirection::Left,
6588 ];
6589 for dir in DIRECTION_PRIORITY {
6590 if workspace.find_pane_in_direction(dir, cx).is_some() {
6591 workspace.swap_pane_in_direction(dir, cx);
6592 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6593 break;
6594 }
6595 }
6596 }))
6597 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6598 workspace.move_pane_to_border(SplitDirection::Left, cx)
6599 }))
6600 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6601 workspace.move_pane_to_border(SplitDirection::Right, cx)
6602 }))
6603 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6604 workspace.move_pane_to_border(SplitDirection::Up, cx)
6605 }))
6606 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6607 workspace.move_pane_to_border(SplitDirection::Down, cx)
6608 }))
6609 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6610 this.toggle_dock(DockPosition::Left, window, cx);
6611 }))
6612 .on_action(cx.listener(
6613 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6614 workspace.toggle_dock(DockPosition::Right, window, cx);
6615 },
6616 ))
6617 .on_action(cx.listener(
6618 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6619 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6620 },
6621 ))
6622 .on_action(cx.listener(
6623 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6624 if !workspace.close_active_dock(window, cx) {
6625 cx.propagate();
6626 }
6627 },
6628 ))
6629 .on_action(
6630 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6631 workspace.close_all_docks(window, cx);
6632 }),
6633 )
6634 .on_action(cx.listener(Self::toggle_all_docks))
6635 .on_action(cx.listener(
6636 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6637 workspace.clear_all_notifications(cx);
6638 },
6639 ))
6640 .on_action(cx.listener(
6641 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6642 workspace.clear_navigation_history(window, cx);
6643 },
6644 ))
6645 .on_action(cx.listener(
6646 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6647 if let Some((notification_id, _)) = workspace.notifications.pop() {
6648 workspace.suppress_notification(¬ification_id, cx);
6649 }
6650 },
6651 ))
6652 .on_action(cx.listener(
6653 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6654 workspace.show_worktree_trust_security_modal(true, window, cx);
6655 },
6656 ))
6657 .on_action(
6658 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6659 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6660 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6661 trusted_worktrees.clear_trusted_paths()
6662 });
6663 let clear_task = persistence::DB.clear_trusted_worktrees();
6664 cx.spawn(async move |_, cx| {
6665 if clear_task.await.log_err().is_some() {
6666 cx.update(|cx| reload(cx));
6667 }
6668 })
6669 .detach();
6670 }
6671 }),
6672 )
6673 .on_action(cx.listener(
6674 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
6675 workspace.reopen_closed_item(window, cx).detach();
6676 },
6677 ))
6678 .on_action(cx.listener(
6679 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
6680 for dock in workspace.all_docks() {
6681 if dock.focus_handle(cx).contains_focused(window, cx) {
6682 let Some(panel) = dock.read(cx).active_panel() else {
6683 return;
6684 };
6685
6686 // Set to `None`, then the size will fall back to the default.
6687 panel.clone().set_size(None, window, cx);
6688
6689 return;
6690 }
6691 }
6692 },
6693 ))
6694 .on_action(cx.listener(
6695 |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
6696 for dock in workspace.all_docks() {
6697 if let Some(panel) = dock.read(cx).visible_panel() {
6698 // Set to `None`, then the size will fall back to the default.
6699 panel.clone().set_size(None, window, cx);
6700 }
6701 }
6702 },
6703 ))
6704 .on_action(cx.listener(
6705 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
6706 adjust_active_dock_size_by_px(
6707 px_with_ui_font_fallback(act.px, cx),
6708 workspace,
6709 window,
6710 cx,
6711 );
6712 },
6713 ))
6714 .on_action(cx.listener(
6715 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
6716 adjust_active_dock_size_by_px(
6717 px_with_ui_font_fallback(act.px, cx) * -1.,
6718 workspace,
6719 window,
6720 cx,
6721 );
6722 },
6723 ))
6724 .on_action(cx.listener(
6725 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
6726 adjust_open_docks_size_by_px(
6727 px_with_ui_font_fallback(act.px, cx),
6728 workspace,
6729 window,
6730 cx,
6731 );
6732 },
6733 ))
6734 .on_action(cx.listener(
6735 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
6736 adjust_open_docks_size_by_px(
6737 px_with_ui_font_fallback(act.px, cx) * -1.,
6738 workspace,
6739 window,
6740 cx,
6741 );
6742 },
6743 ))
6744 .on_action(cx.listener(Workspace::toggle_centered_layout))
6745 .on_action(cx.listener(
6746 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
6747 if let Some(active_dock) = workspace.active_dock(window, cx) {
6748 let dock = active_dock.read(cx);
6749 if let Some(active_panel) = dock.active_panel() {
6750 if active_panel.pane(cx).is_none() {
6751 let mut recent_pane: Option<Entity<Pane>> = None;
6752 let mut recent_timestamp = 0;
6753 for pane_handle in workspace.panes() {
6754 let pane = pane_handle.read(cx);
6755 for entry in pane.activation_history() {
6756 if entry.timestamp > recent_timestamp {
6757 recent_timestamp = entry.timestamp;
6758 recent_pane = Some(pane_handle.clone());
6759 }
6760 }
6761 }
6762
6763 if let Some(pane) = recent_pane {
6764 pane.update(cx, |pane, cx| {
6765 let current_index = pane.active_item_index();
6766 let items_len = pane.items_len();
6767 if items_len > 0 {
6768 let next_index = if current_index + 1 < items_len {
6769 current_index + 1
6770 } else {
6771 0
6772 };
6773 pane.activate_item(
6774 next_index, false, false, window, cx,
6775 );
6776 }
6777 });
6778 return;
6779 }
6780 }
6781 }
6782 }
6783 cx.propagate();
6784 },
6785 ))
6786 .on_action(cx.listener(
6787 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
6788 if let Some(active_dock) = workspace.active_dock(window, cx) {
6789 let dock = active_dock.read(cx);
6790 if let Some(active_panel) = dock.active_panel() {
6791 if active_panel.pane(cx).is_none() {
6792 let mut recent_pane: Option<Entity<Pane>> = None;
6793 let mut recent_timestamp = 0;
6794 for pane_handle in workspace.panes() {
6795 let pane = pane_handle.read(cx);
6796 for entry in pane.activation_history() {
6797 if entry.timestamp > recent_timestamp {
6798 recent_timestamp = entry.timestamp;
6799 recent_pane = Some(pane_handle.clone());
6800 }
6801 }
6802 }
6803
6804 if let Some(pane) = recent_pane {
6805 pane.update(cx, |pane, cx| {
6806 let current_index = pane.active_item_index();
6807 let items_len = pane.items_len();
6808 if items_len > 0 {
6809 let prev_index = if current_index > 0 {
6810 current_index - 1
6811 } else {
6812 items_len.saturating_sub(1)
6813 };
6814 pane.activate_item(
6815 prev_index, false, false, window, cx,
6816 );
6817 }
6818 });
6819 return;
6820 }
6821 }
6822 }
6823 }
6824 cx.propagate();
6825 },
6826 ))
6827 .on_action(cx.listener(
6828 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
6829 if let Some(active_dock) = workspace.active_dock(window, cx) {
6830 let dock = active_dock.read(cx);
6831 if let Some(active_panel) = dock.active_panel() {
6832 if active_panel.pane(cx).is_none() {
6833 let active_pane = workspace.active_pane().clone();
6834 active_pane.update(cx, |pane, cx| {
6835 pane.close_active_item(action, window, cx)
6836 .detach_and_log_err(cx);
6837 });
6838 return;
6839 }
6840 }
6841 }
6842 cx.propagate();
6843 },
6844 ))
6845 .on_action(
6846 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
6847 let pane = workspace.active_pane().clone();
6848 if let Some(item) = pane.read(cx).active_item() {
6849 item.toggle_read_only(window, cx);
6850 }
6851 }),
6852 )
6853 .on_action(cx.listener(Workspace::cancel))
6854 }
6855
6856 #[cfg(any(test, feature = "test-support"))]
6857 pub fn set_random_database_id(&mut self) {
6858 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
6859 }
6860
6861 #[cfg(any(test, feature = "test-support"))]
6862 pub(crate) fn test_new(
6863 project: Entity<Project>,
6864 window: &mut Window,
6865 cx: &mut Context<Self>,
6866 ) -> Self {
6867 use node_runtime::NodeRuntime;
6868 use session::Session;
6869
6870 let client = project.read(cx).client();
6871 let user_store = project.read(cx).user_store();
6872 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
6873 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
6874 window.activate_window();
6875 let app_state = Arc::new(AppState {
6876 languages: project.read(cx).languages().clone(),
6877 workspace_store,
6878 client,
6879 user_store,
6880 fs: project.read(cx).fs().clone(),
6881 build_window_options: |_, _| Default::default(),
6882 node_runtime: NodeRuntime::unavailable(),
6883 session,
6884 });
6885 let workspace = Self::new(Default::default(), project, app_state, window, cx);
6886 workspace
6887 .active_pane
6888 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6889 workspace
6890 }
6891
6892 pub fn register_action<A: Action>(
6893 &mut self,
6894 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
6895 ) -> &mut Self {
6896 let callback = Arc::new(callback);
6897
6898 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
6899 let callback = callback.clone();
6900 div.on_action(cx.listener(move |workspace, event, window, cx| {
6901 (callback)(workspace, event, window, cx)
6902 }))
6903 }));
6904 self
6905 }
6906 pub fn register_action_renderer(
6907 &mut self,
6908 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
6909 ) -> &mut Self {
6910 self.workspace_actions.push(Box::new(callback));
6911 self
6912 }
6913
6914 fn add_workspace_actions_listeners(
6915 &self,
6916 mut div: Div,
6917 window: &mut Window,
6918 cx: &mut Context<Self>,
6919 ) -> Div {
6920 for action in self.workspace_actions.iter() {
6921 div = (action)(div, self, window, cx)
6922 }
6923 div
6924 }
6925
6926 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
6927 self.modal_layer.read(cx).has_active_modal()
6928 }
6929
6930 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
6931 self.modal_layer.read(cx).active_modal()
6932 }
6933
6934 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
6935 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
6936 /// If no modal is active, the new modal will be shown.
6937 ///
6938 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
6939 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
6940 /// will not be shown.
6941 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
6942 where
6943 B: FnOnce(&mut Window, &mut Context<V>) -> V,
6944 {
6945 self.modal_layer.update(cx, |modal_layer, cx| {
6946 modal_layer.toggle_modal(window, cx, build)
6947 })
6948 }
6949
6950 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
6951 self.modal_layer
6952 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
6953 }
6954
6955 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
6956 self.toast_layer
6957 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
6958 }
6959
6960 pub fn toggle_centered_layout(
6961 &mut self,
6962 _: &ToggleCenteredLayout,
6963 _: &mut Window,
6964 cx: &mut Context<Self>,
6965 ) {
6966 self.centered_layout = !self.centered_layout;
6967 if let Some(database_id) = self.database_id() {
6968 cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
6969 .detach_and_log_err(cx);
6970 }
6971 cx.notify();
6972 }
6973
6974 fn adjust_padding(padding: Option<f32>) -> f32 {
6975 padding
6976 .unwrap_or(CenteredPaddingSettings::default().0)
6977 .clamp(
6978 CenteredPaddingSettings::MIN_PADDING,
6979 CenteredPaddingSettings::MAX_PADDING,
6980 )
6981 }
6982
6983 fn render_dock(
6984 &self,
6985 position: DockPosition,
6986 dock: &Entity<Dock>,
6987 window: &mut Window,
6988 cx: &mut App,
6989 ) -> Option<Div> {
6990 if self.zoomed_position == Some(position) {
6991 return None;
6992 }
6993
6994 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
6995 let pane = panel.pane(cx)?;
6996 let follower_states = &self.follower_states;
6997 leader_border_for_pane(follower_states, &pane, window, cx)
6998 });
6999
7000 Some(
7001 div()
7002 .flex()
7003 .flex_none()
7004 .overflow_hidden()
7005 .child(dock.clone())
7006 .children(leader_border),
7007 )
7008 }
7009
7010 pub fn set_left_drawer<V: Render + Focusable + 'static>(
7011 &mut self,
7012 view: Entity<V>,
7013 cx: &mut Context<Self>,
7014 ) {
7015 self.left_drawer = Some(Drawer::new(view));
7016 cx.notify();
7017 }
7018
7019 pub fn set_right_drawer<V: Render + Focusable + 'static>(
7020 &mut self,
7021 view: Entity<V>,
7022 cx: &mut Context<Self>,
7023 ) {
7024 self.right_drawer = Some(Drawer::new(view));
7025 cx.notify();
7026 }
7027
7028 fn drawer_mut<T: 'static>(&mut self) -> Option<(Entity<T>, &mut Drawer)> {
7029 if let Some(left) = self.left_drawer.as_mut() {
7030 if let Some(drawer) = left.view.clone().downcast().ok() {
7031 return Some((drawer, left));
7032 }
7033 }
7034 if let Some(right) = self.right_drawer.as_mut() {
7035 if let Some(drawer) = right.view.clone().downcast().ok() {
7036 return Some((drawer, right));
7037 }
7038 }
7039 None
7040 }
7041
7042 fn drawer_ref<T: 'static>(&self) -> Option<(Entity<T>, &Drawer)> {
7043 if let Some(left) = self.left_drawer.as_ref() {
7044 if let Some(drawer) = left.view.clone().downcast().ok() {
7045 return Some((drawer, left));
7046 }
7047 }
7048 if let Some(right) = self.right_drawer.as_ref() {
7049 if let Some(drawer) = right.view.clone().downcast().ok() {
7050 return Some((drawer, right));
7051 }
7052 }
7053 None
7054 }
7055
7056 pub fn drawer<T: 'static>(&self) -> Option<Entity<T>> {
7057 if let Some(left) = self.left_drawer.as_ref() {
7058 if let Some(drawer) = left.view.clone().downcast().ok() {
7059 return Some(drawer);
7060 }
7061 }
7062 if let Some(right) = self.right_drawer.as_ref() {
7063 if let Some(drawer) = right.view.clone().downcast().ok() {
7064 return Some(drawer);
7065 }
7066 }
7067 None
7068 }
7069
7070 pub fn focus_drawer<T: Focusable>(
7071 &mut self,
7072 window: &mut Window,
7073 cx: &mut Context<Self>,
7074 ) -> Option<Entity<T>> {
7075 if let Some((view, drawer)) = self.drawer_mut::<T>() {
7076 drawer.open = true;
7077 view.focus_handle(cx).focus(window, cx);
7078 return Some(view);
7079 }
7080 None
7081 }
7082
7083 pub fn toggle_drawer_focus<T: Focusable>(
7084 &mut self,
7085 window: &mut Window,
7086 cx: &mut Context<Self>,
7087 ) -> bool {
7088 if let Some((view, drawer)) = self.drawer_mut::<T>() {
7089 if view.focus_handle(cx).contains_focused(window, cx) {
7090 self.active_pane
7091 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
7092 false
7093 } else {
7094 drawer.open = true;
7095 view.focus_handle(cx).focus(window, cx);
7096 cx.notify();
7097 true
7098 }
7099 } else {
7100 false
7101 }
7102 }
7103
7104 pub fn toggle_drawer<T: Focusable>(&mut self, cx: &mut Context<Self>) -> bool {
7105 if let Some((_, drawer)) = self.drawer_mut::<T>() {
7106 if drawer.open {
7107 drawer.open = false;
7108 cx.notify();
7109 false
7110 } else {
7111 drawer.open = true;
7112 cx.notify();
7113 true
7114 }
7115 } else {
7116 false
7117 }
7118 }
7119
7120 pub fn open_drawer<T: Focusable>(&mut self, cx: &mut Context<Self>) {
7121 if let Some((_, drawer)) = self.drawer_mut::<T>() {
7122 drawer.open = true;
7123 cx.notify();
7124 }
7125 }
7126
7127 pub fn close_drawer<T: Focusable>(&mut self, cx: &mut Context<Self>) {
7128 if let Some((_, drawer)) = self.drawer_mut::<T>() {
7129 drawer.open = false;
7130 cx.notify();
7131 }
7132 }
7133
7134 pub fn drawer_is_open<T: 'static>(&self) -> bool {
7135 if let Some((_, drawer)) = self.drawer_ref::<T>() {
7136 drawer.open
7137 } else {
7138 false
7139 }
7140 }
7141
7142 pub fn remove_drawer<T: Focusable>(&mut self, cx: &mut Context<Self>) {
7143 if let Some(left) = self.left_drawer.as_mut() {
7144 if left.view.clone().downcast::<T>().is_ok() {
7145 self.left_drawer = None;
7146 cx.notify();
7147 return;
7148 }
7149 }
7150 if let Some(right) = self.right_drawer.as_mut() {
7151 if right.view.clone().downcast::<T>().is_ok() {
7152 self.right_drawer = None;
7153 cx.notify();
7154 return;
7155 }
7156 }
7157 }
7158
7159 pub fn left_drawer_view(&self) -> Option<&AnyView> {
7160 self.left_drawer.as_ref().map(|d| &d.view)
7161 }
7162
7163 pub fn right_drawer_view(&self) -> Option<&AnyView> {
7164 self.right_drawer.as_ref().map(|d| &d.view)
7165 }
7166
7167 pub fn is_left_drawer_open(&self) -> bool {
7168 self.left_drawer.as_ref().is_some_and(|d| d.open)
7169 }
7170
7171 pub fn is_right_drawer_open(&self) -> bool {
7172 self.right_drawer.as_ref().is_some_and(|d| d.open)
7173 }
7174
7175 pub fn remove_left_drawer(&mut self, cx: &mut Context<Self>) {
7176 self.left_drawer = None;
7177 cx.notify();
7178 }
7179
7180 pub fn remove_right_drawer(&mut self, cx: &mut Context<Self>) {
7181 self.right_drawer = None;
7182 cx.notify();
7183 }
7184
7185 fn resize_left_drawer(
7186 &mut self,
7187 cursor_offset_from_left: Pixels,
7188 window: &mut Window,
7189 cx: &mut Context<Self>,
7190 ) {
7191 let left_dock_width = self
7192 .left_dock
7193 .read(cx)
7194 .active_panel_size(window, cx)
7195 .unwrap_or(Pixels::ZERO);
7196 let drawer_width = cursor_offset_from_left - left_dock_width;
7197 let max_width = self.bounds.size.width * 0.8;
7198 let width = drawer_width.max(px(100.)).min(max_width);
7199 if let Some(drawer) = &mut self.left_drawer {
7200 drawer.custom_width = Some(width);
7201 cx.notify();
7202 }
7203 }
7204
7205 fn resize_right_drawer(
7206 &mut self,
7207 cursor_offset_from_right: Pixels,
7208 window: &mut Window,
7209 cx: &mut Context<Self>,
7210 ) {
7211 let right_dock_width = self
7212 .right_dock
7213 .read(cx)
7214 .active_panel_size(window, cx)
7215 .unwrap_or(Pixels::ZERO);
7216 let drawer_width = cursor_offset_from_right - right_dock_width;
7217 let max_width = self.bounds.size.width * 0.8;
7218 let width = drawer_width.max(px(100.)).min(max_width);
7219 if let Some(drawer) = &mut self.right_drawer {
7220 drawer.custom_width = Some(width);
7221 cx.notify();
7222 }
7223 }
7224
7225 fn render_drawer(&self, position: DrawerPosition, cx: &mut Context<Self>) -> Option<Div> {
7226 let drawer = match position {
7227 DrawerPosition::Left => self.left_drawer.as_ref()?,
7228 DrawerPosition::Right => self.right_drawer.as_ref()?,
7229 };
7230 if !drawer.open {
7231 return None;
7232 }
7233
7234 let colors = cx.theme().colors();
7235 let create_resize_handle = |position: DrawerPosition| {
7236 let handle = div()
7237 .id(match position {
7238 DrawerPosition::Left => "left-drawer-resize-handle",
7239 DrawerPosition::Right => "right-drawer-resize-handle",
7240 })
7241 .on_drag(DraggedDrawer(position), |drawer, _, _, cx| {
7242 cx.stop_propagation();
7243 cx.new(|_| drawer.clone())
7244 })
7245 .on_mouse_down(MouseButton::Left, |_, _, cx| {
7246 cx.stop_propagation();
7247 })
7248 .on_mouse_up(
7249 MouseButton::Left,
7250 cx.listener(move |workspace, _: &MouseUpEvent, _, cx| {
7251 let drawer = match position {
7252 DrawerPosition::Left => &mut workspace.left_drawer,
7253 DrawerPosition::Right => &mut workspace.right_drawer,
7254 };
7255 if let Some(drawer) = drawer {
7256 drawer.custom_width = None;
7257 cx.notify();
7258 }
7259 }),
7260 )
7261 .occlude();
7262 match position {
7263 DrawerPosition::Left => deferred(
7264 handle
7265 .absolute()
7266 .right(-RESIZE_HANDLE_SIZE / 2.)
7267 .top(px(0.))
7268 .h_full()
7269 .w(RESIZE_HANDLE_SIZE)
7270 .cursor_col_resize(),
7271 ),
7272 DrawerPosition::Right => deferred(
7273 handle
7274 .absolute()
7275 .top(px(0.))
7276 .left(-RESIZE_HANDLE_SIZE / 2.)
7277 .h_full()
7278 .w(RESIZE_HANDLE_SIZE)
7279 .cursor_col_resize(),
7280 ),
7281 }
7282 };
7283
7284 let focus_handle = drawer.focus_handle(cx);
7285 let base = div()
7286 .track_focus(&focus_handle)
7287 .flex()
7288 .flex_col()
7289 .overflow_hidden()
7290 .border_color(colors.border)
7291 .map(|this| match position {
7292 DrawerPosition::Left => this.border_r_1(),
7293 DrawerPosition::Right => this.border_l_1(),
7294 });
7295
7296 let element = if let Some(width) = drawer.custom_width {
7297 base.flex_none().w(width)
7298 } else {
7299 base.flex_1()
7300 };
7301
7302 Some(
7303 element
7304 .child(drawer.view.clone())
7305 .child(create_resize_handle(position)),
7306 )
7307 }
7308
7309 fn render_center_with_drawers(
7310 &self,
7311 paddings: (Option<Div>, Option<Div>),
7312 window: &mut Window,
7313 cx: &mut Context<Self>,
7314 ) -> Div {
7315 let center_element = div().flex().flex_col().flex_1().overflow_hidden().child(
7316 h_flex()
7317 .flex_1()
7318 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7319 .child(self.center.render(
7320 self.zoomed.as_ref(),
7321 &PaneRenderContext {
7322 follower_states: &self.follower_states,
7323 active_call: self.active_call(),
7324 active_pane: &self.active_pane,
7325 app_state: &self.app_state,
7326 project: &self.project,
7327 workspace: &self.weak_self,
7328 },
7329 window,
7330 cx,
7331 ))
7332 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7333 );
7334
7335 let left_drawer = self.render_drawer(DrawerPosition::Left, cx);
7336 let right_drawer = self.render_drawer(DrawerPosition::Right, cx);
7337
7338 let has_drawers = left_drawer.is_some() || right_drawer.is_some();
7339
7340 if has_drawers {
7341 div()
7342 .flex()
7343 .flex_row()
7344 .flex_1()
7345 .overflow_hidden()
7346 .children(left_drawer)
7347 .child(center_element)
7348 .children(right_drawer)
7349 } else {
7350 center_element
7351 }
7352 }
7353
7354 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7355 window
7356 .root::<MultiWorkspace>()
7357 .flatten()
7358 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7359 }
7360
7361 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7362 self.zoomed.as_ref()
7363 }
7364
7365 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7366 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7367 return;
7368 };
7369 let windows = cx.windows();
7370 let next_window =
7371 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7372 || {
7373 windows
7374 .iter()
7375 .cycle()
7376 .skip_while(|window| window.window_id() != current_window_id)
7377 .nth(1)
7378 },
7379 );
7380
7381 if let Some(window) = next_window {
7382 window
7383 .update(cx, |_, window, _| window.activate_window())
7384 .ok();
7385 }
7386 }
7387
7388 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7389 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7390 return;
7391 };
7392 let windows = cx.windows();
7393 let prev_window =
7394 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7395 || {
7396 windows
7397 .iter()
7398 .rev()
7399 .cycle()
7400 .skip_while(|window| window.window_id() != current_window_id)
7401 .nth(1)
7402 },
7403 );
7404
7405 if let Some(window) = prev_window {
7406 window
7407 .update(cx, |_, window, _| window.activate_window())
7408 .ok();
7409 }
7410 }
7411
7412 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7413 if cx.stop_active_drag(window) {
7414 } else if let Some((notification_id, _)) = self.notifications.pop() {
7415 dismiss_app_notification(¬ification_id, cx);
7416 } else {
7417 cx.propagate();
7418 }
7419 }
7420
7421 fn adjust_dock_size_by_px(
7422 &mut self,
7423 panel_size: Pixels,
7424 dock_pos: DockPosition,
7425 px: Pixels,
7426 window: &mut Window,
7427 cx: &mut Context<Self>,
7428 ) {
7429 match dock_pos {
7430 DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
7431 DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
7432 DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
7433 }
7434 }
7435
7436 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7437 let workspace_width = self.bounds.size.width;
7438 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7439
7440 self.right_dock.read_with(cx, |right_dock, cx| {
7441 let right_dock_size = right_dock
7442 .active_panel_size(window, cx)
7443 .unwrap_or(Pixels::ZERO);
7444 if right_dock_size + size > workspace_width {
7445 size = workspace_width - right_dock_size
7446 }
7447 });
7448
7449 self.left_dock.update(cx, |left_dock, cx| {
7450 if WorkspaceSettings::get_global(cx)
7451 .resize_all_panels_in_dock
7452 .contains(&DockPosition::Left)
7453 {
7454 left_dock.resize_all_panels(Some(size), window, cx);
7455 } else {
7456 left_dock.resize_active_panel(Some(size), window, cx);
7457 }
7458 });
7459 }
7460
7461 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7462 let workspace_width = self.bounds.size.width;
7463 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7464 self.left_dock.read_with(cx, |left_dock, cx| {
7465 let left_dock_size = left_dock
7466 .active_panel_size(window, cx)
7467 .unwrap_or(Pixels::ZERO);
7468 if left_dock_size + size > workspace_width {
7469 size = workspace_width - left_dock_size
7470 }
7471 });
7472 self.right_dock.update(cx, |right_dock, cx| {
7473 if WorkspaceSettings::get_global(cx)
7474 .resize_all_panels_in_dock
7475 .contains(&DockPosition::Right)
7476 {
7477 right_dock.resize_all_panels(Some(size), window, cx);
7478 } else {
7479 right_dock.resize_active_panel(Some(size), window, cx);
7480 }
7481 });
7482 }
7483
7484 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7485 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7486 self.bottom_dock.update(cx, |bottom_dock, cx| {
7487 if WorkspaceSettings::get_global(cx)
7488 .resize_all_panels_in_dock
7489 .contains(&DockPosition::Bottom)
7490 {
7491 bottom_dock.resize_all_panels(Some(size), window, cx);
7492 } else {
7493 bottom_dock.resize_active_panel(Some(size), window, cx);
7494 }
7495 });
7496 }
7497
7498 fn toggle_edit_predictions_all_files(
7499 &mut self,
7500 _: &ToggleEditPrediction,
7501 _window: &mut Window,
7502 cx: &mut Context<Self>,
7503 ) {
7504 let fs = self.project().read(cx).fs().clone();
7505 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7506 update_settings_file(fs, cx, move |file, _| {
7507 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7508 });
7509 }
7510
7511 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7512 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7513 let next_mode = match current_mode {
7514 Some(theme::ThemeAppearanceMode::Light) => theme::ThemeAppearanceMode::Dark,
7515 Some(theme::ThemeAppearanceMode::Dark) => theme::ThemeAppearanceMode::Light,
7516 Some(theme::ThemeAppearanceMode::System) | None => match cx.theme().appearance() {
7517 theme::Appearance::Light => theme::ThemeAppearanceMode::Dark,
7518 theme::Appearance::Dark => theme::ThemeAppearanceMode::Light,
7519 },
7520 };
7521
7522 let fs = self.project().read(cx).fs().clone();
7523 settings::update_settings_file(fs, cx, move |settings, _cx| {
7524 theme::set_mode(settings, next_mode);
7525 });
7526 }
7527
7528 pub fn show_worktree_trust_security_modal(
7529 &mut self,
7530 toggle: bool,
7531 window: &mut Window,
7532 cx: &mut Context<Self>,
7533 ) {
7534 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7535 if toggle {
7536 security_modal.update(cx, |security_modal, cx| {
7537 security_modal.dismiss(cx);
7538 })
7539 } else {
7540 security_modal.update(cx, |security_modal, cx| {
7541 security_modal.refresh_restricted_paths(cx);
7542 });
7543 }
7544 } else {
7545 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7546 .map(|trusted_worktrees| {
7547 trusted_worktrees
7548 .read(cx)
7549 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7550 })
7551 .unwrap_or(false);
7552 if has_restricted_worktrees {
7553 let project = self.project().read(cx);
7554 let remote_host = project
7555 .remote_connection_options(cx)
7556 .map(RemoteHostLocation::from);
7557 let worktree_store = project.worktree_store().downgrade();
7558 self.toggle_modal(window, cx, |_, cx| {
7559 SecurityModal::new(worktree_store, remote_host, cx)
7560 });
7561 }
7562 }
7563 }
7564}
7565
7566pub trait AnyActiveCall {
7567 fn entity(&self) -> AnyEntity;
7568 fn is_in_room(&self, _: &App) -> bool;
7569 fn room_id(&self, _: &App) -> Option<u64>;
7570 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7571 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7572 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7573 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7574 fn is_sharing_project(&self, _: &App) -> bool;
7575 fn has_remote_participants(&self, _: &App) -> bool;
7576 fn local_participant_is_guest(&self, _: &App) -> bool;
7577 fn client(&self, _: &App) -> Arc<Client>;
7578 fn share_on_join(&self, _: &App) -> bool;
7579 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7580 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7581 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7582 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7583 fn join_project(
7584 &self,
7585 _: u64,
7586 _: Arc<LanguageRegistry>,
7587 _: Arc<dyn Fs>,
7588 _: &mut App,
7589 ) -> Task<Result<Entity<Project>>>;
7590 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7591 fn subscribe(
7592 &self,
7593 _: &mut Window,
7594 _: &mut Context<Workspace>,
7595 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7596 ) -> Subscription;
7597 fn create_shared_screen(
7598 &self,
7599 _: PeerId,
7600 _: &Entity<Pane>,
7601 _: &mut Window,
7602 _: &mut App,
7603 ) -> Option<Entity<SharedScreen>>;
7604}
7605
7606#[derive(Clone)]
7607pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7608impl Global for GlobalAnyActiveCall {}
7609
7610impl GlobalAnyActiveCall {
7611 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7612 cx.try_global()
7613 }
7614
7615 pub(crate) fn global(cx: &App) -> &Self {
7616 cx.global()
7617 }
7618}
7619
7620pub fn merge_conflict_notification_id() -> NotificationId {
7621 struct MergeConflictNotification;
7622 NotificationId::unique::<MergeConflictNotification>()
7623}
7624
7625/// Workspace-local view of a remote participant's location.
7626#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7627pub enum ParticipantLocation {
7628 SharedProject { project_id: u64 },
7629 UnsharedProject,
7630 External,
7631}
7632
7633impl ParticipantLocation {
7634 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7635 match location
7636 .and_then(|l| l.variant)
7637 .context("participant location was not provided")?
7638 {
7639 proto::participant_location::Variant::SharedProject(project) => {
7640 Ok(Self::SharedProject {
7641 project_id: project.id,
7642 })
7643 }
7644 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7645 proto::participant_location::Variant::External(_) => Ok(Self::External),
7646 }
7647 }
7648}
7649/// Workspace-local view of a remote collaborator's state.
7650/// This is the subset of `call::RemoteParticipant` that workspace needs.
7651#[derive(Clone)]
7652pub struct RemoteCollaborator {
7653 pub user: Arc<User>,
7654 pub peer_id: PeerId,
7655 pub location: ParticipantLocation,
7656 pub participant_index: ParticipantIndex,
7657}
7658
7659pub enum ActiveCallEvent {
7660 ParticipantLocationChanged { participant_id: PeerId },
7661 RemoteVideoTracksChanged { participant_id: PeerId },
7662}
7663
7664fn leader_border_for_pane(
7665 follower_states: &HashMap<CollaboratorId, FollowerState>,
7666 pane: &Entity<Pane>,
7667 _: &Window,
7668 cx: &App,
7669) -> Option<Div> {
7670 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7671 if state.pane() == pane {
7672 Some((*leader_id, state))
7673 } else {
7674 None
7675 }
7676 })?;
7677
7678 let mut leader_color = match leader_id {
7679 CollaboratorId::PeerId(leader_peer_id) => {
7680 let leader = GlobalAnyActiveCall::try_global(cx)?
7681 .0
7682 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7683
7684 cx.theme()
7685 .players()
7686 .color_for_participant(leader.participant_index.0)
7687 .cursor
7688 }
7689 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7690 };
7691 leader_color.fade_out(0.3);
7692 Some(
7693 div()
7694 .absolute()
7695 .size_full()
7696 .left_0()
7697 .top_0()
7698 .border_2()
7699 .border_color(leader_color),
7700 )
7701}
7702
7703fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7704 ZED_WINDOW_POSITION
7705 .zip(*ZED_WINDOW_SIZE)
7706 .map(|(position, size)| Bounds {
7707 origin: position,
7708 size,
7709 })
7710}
7711
7712fn open_items(
7713 serialized_workspace: Option<SerializedWorkspace>,
7714 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7715 window: &mut Window,
7716 cx: &mut Context<Workspace>,
7717) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7718 let restored_items = serialized_workspace.map(|serialized_workspace| {
7719 Workspace::load_workspace(
7720 serialized_workspace,
7721 project_paths_to_open
7722 .iter()
7723 .map(|(_, project_path)| project_path)
7724 .cloned()
7725 .collect(),
7726 window,
7727 cx,
7728 )
7729 });
7730
7731 cx.spawn_in(window, async move |workspace, cx| {
7732 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7733
7734 if let Some(restored_items) = restored_items {
7735 let restored_items = restored_items.await?;
7736
7737 let restored_project_paths = restored_items
7738 .iter()
7739 .filter_map(|item| {
7740 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7741 .ok()
7742 .flatten()
7743 })
7744 .collect::<HashSet<_>>();
7745
7746 for restored_item in restored_items {
7747 opened_items.push(restored_item.map(Ok));
7748 }
7749
7750 project_paths_to_open
7751 .iter_mut()
7752 .for_each(|(_, project_path)| {
7753 if let Some(project_path_to_open) = project_path
7754 && restored_project_paths.contains(project_path_to_open)
7755 {
7756 *project_path = None;
7757 }
7758 });
7759 } else {
7760 for _ in 0..project_paths_to_open.len() {
7761 opened_items.push(None);
7762 }
7763 }
7764 assert!(opened_items.len() == project_paths_to_open.len());
7765
7766 let tasks =
7767 project_paths_to_open
7768 .into_iter()
7769 .enumerate()
7770 .map(|(ix, (abs_path, project_path))| {
7771 let workspace = workspace.clone();
7772 cx.spawn(async move |cx| {
7773 let file_project_path = project_path?;
7774 let abs_path_task = workspace.update(cx, |workspace, cx| {
7775 workspace.project().update(cx, |project, cx| {
7776 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7777 })
7778 });
7779
7780 // We only want to open file paths here. If one of the items
7781 // here is a directory, it was already opened further above
7782 // with a `find_or_create_worktree`.
7783 if let Ok(task) = abs_path_task
7784 && task.await.is_none_or(|p| p.is_file())
7785 {
7786 return Some((
7787 ix,
7788 workspace
7789 .update_in(cx, |workspace, window, cx| {
7790 workspace.open_path(
7791 file_project_path,
7792 None,
7793 true,
7794 window,
7795 cx,
7796 )
7797 })
7798 .log_err()?
7799 .await,
7800 ));
7801 }
7802 None
7803 })
7804 });
7805
7806 let tasks = tasks.collect::<Vec<_>>();
7807
7808 let tasks = futures::future::join_all(tasks);
7809 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7810 opened_items[ix] = Some(path_open_result);
7811 }
7812
7813 Ok(opened_items)
7814 })
7815}
7816
7817enum ActivateInDirectionTarget {
7818 Pane(Entity<Pane>),
7819 Dock(Entity<Dock>),
7820}
7821
7822fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7823 window
7824 .update(cx, |multi_workspace, _, cx| {
7825 let workspace = multi_workspace.workspace().clone();
7826 workspace.update(cx, |workspace, cx| {
7827 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7828 struct DatabaseFailedNotification;
7829
7830 workspace.show_notification(
7831 NotificationId::unique::<DatabaseFailedNotification>(),
7832 cx,
7833 |cx| {
7834 cx.new(|cx| {
7835 MessageNotification::new("Failed to load the database file.", cx)
7836 .primary_message("File an Issue")
7837 .primary_icon(IconName::Plus)
7838 .primary_on_click(|window, cx| {
7839 window.dispatch_action(Box::new(FileBugReport), cx)
7840 })
7841 })
7842 },
7843 );
7844 }
7845 });
7846 })
7847 .log_err();
7848}
7849
7850fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7851 if val == 0 {
7852 ThemeSettings::get_global(cx).ui_font_size(cx)
7853 } else {
7854 px(val as f32)
7855 }
7856}
7857
7858fn adjust_active_dock_size_by_px(
7859 px: Pixels,
7860 workspace: &mut Workspace,
7861 window: &mut Window,
7862 cx: &mut Context<Workspace>,
7863) {
7864 let Some(active_dock) = workspace
7865 .all_docks()
7866 .into_iter()
7867 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7868 else {
7869 return;
7870 };
7871 let dock = active_dock.read(cx);
7872 let Some(panel_size) = dock.active_panel_size(window, cx) else {
7873 return;
7874 };
7875 let dock_pos = dock.position();
7876 workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
7877}
7878
7879fn adjust_open_docks_size_by_px(
7880 px: Pixels,
7881 workspace: &mut Workspace,
7882 window: &mut Window,
7883 cx: &mut Context<Workspace>,
7884) {
7885 let docks = workspace
7886 .all_docks()
7887 .into_iter()
7888 .filter_map(|dock| {
7889 if dock.read(cx).is_open() {
7890 let dock = dock.read(cx);
7891 let panel_size = dock.active_panel_size(window, cx)?;
7892 let dock_pos = dock.position();
7893 Some((panel_size, dock_pos, px))
7894 } else {
7895 None
7896 }
7897 })
7898 .collect::<Vec<_>>();
7899
7900 docks
7901 .into_iter()
7902 .for_each(|(panel_size, dock_pos, offset)| {
7903 workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
7904 });
7905}
7906
7907impl Focusable for Workspace {
7908 fn focus_handle(&self, cx: &App) -> FocusHandle {
7909 self.active_pane.focus_handle(cx)
7910 }
7911}
7912
7913#[derive(Clone)]
7914struct DraggedDock(DockPosition);
7915
7916impl Render for DraggedDock {
7917 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7918 gpui::Empty
7919 }
7920}
7921
7922#[derive(Copy, Clone, Debug, PartialEq, Eq)]
7923pub enum DrawerPosition {
7924 Left,
7925 Right,
7926}
7927
7928pub struct Drawer {
7929 view: AnyView,
7930 focus_handle_fn: Box<dyn Fn(&App) -> FocusHandle>,
7931 open: bool,
7932 custom_width: Option<Pixels>,
7933}
7934
7935impl Drawer {
7936 fn new<V: Render + Focusable + 'static>(view: Entity<V>) -> Self {
7937 let entity = view.clone();
7938 Self {
7939 view: view.into(),
7940 focus_handle_fn: Box::new(move |cx| entity.focus_handle(cx)),
7941 open: true,
7942 custom_width: None,
7943 }
7944 }
7945
7946 fn focus_handle(&self, cx: &App) -> FocusHandle {
7947 (self.focus_handle_fn)(cx)
7948 }
7949}
7950
7951#[derive(Clone)]
7952struct DraggedDrawer(DrawerPosition);
7953
7954impl Render for DraggedDrawer {
7955 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7956 gpui::Empty
7957 }
7958}
7959
7960impl Render for Workspace {
7961 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7962 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7963 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7964 log::info!("Rendered first frame");
7965 }
7966
7967 let centered_layout = self.centered_layout
7968 && self.center.panes().len() == 1
7969 && self.active_item(cx).is_some();
7970 let render_padding = |size| {
7971 (size > 0.0).then(|| {
7972 div()
7973 .h_full()
7974 .w(relative(size))
7975 .bg(cx.theme().colors().editor_background)
7976 .border_color(cx.theme().colors().pane_group_border)
7977 })
7978 };
7979 let paddings = if centered_layout {
7980 let settings = WorkspaceSettings::get_global(cx).centered_layout;
7981 (
7982 render_padding(Self::adjust_padding(
7983 settings.left_padding.map(|padding| padding.0),
7984 )),
7985 render_padding(Self::adjust_padding(
7986 settings.right_padding.map(|padding| padding.0),
7987 )),
7988 )
7989 } else {
7990 (None, None)
7991 };
7992 let ui_font = theme::setup_ui_font(window, cx);
7993
7994 let theme = cx.theme().clone();
7995 let colors = theme.colors();
7996 let notification_entities = self
7997 .notifications
7998 .iter()
7999 .map(|(_, notification)| notification.entity_id())
8000 .collect::<Vec<_>>();
8001 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
8002
8003 div()
8004 .relative()
8005 .size_full()
8006 .flex()
8007 .flex_col()
8008 .font(ui_font)
8009 .gap_0()
8010 .justify_start()
8011 .items_start()
8012 .text_color(colors.text)
8013 .overflow_hidden()
8014 .children(self.titlebar_item.clone())
8015 .on_modifiers_changed(move |_, _, cx| {
8016 for &id in ¬ification_entities {
8017 cx.notify(id);
8018 }
8019 })
8020 .child(
8021 div()
8022 .size_full()
8023 .relative()
8024 .flex_1()
8025 .flex()
8026 .flex_col()
8027 .child(
8028 div()
8029 .id("workspace")
8030 .bg(colors.background)
8031 .relative()
8032 .flex_1()
8033 .w_full()
8034 .flex()
8035 .flex_col()
8036 .overflow_hidden()
8037 .border_t_1()
8038 .border_b_1()
8039 .border_color(colors.border)
8040 .child({
8041 let this = cx.entity();
8042 canvas(
8043 move |bounds, window, cx| {
8044 this.update(cx, |this, cx| {
8045 let bounds_changed = this.bounds != bounds;
8046 this.bounds = bounds;
8047
8048 if bounds_changed {
8049 this.left_dock.update(cx, |dock, cx| {
8050 dock.clamp_panel_size(
8051 bounds.size.width,
8052 window,
8053 cx,
8054 )
8055 });
8056
8057 this.right_dock.update(cx, |dock, cx| {
8058 dock.clamp_panel_size(
8059 bounds.size.width,
8060 window,
8061 cx,
8062 )
8063 });
8064
8065 this.bottom_dock.update(cx, |dock, cx| {
8066 dock.clamp_panel_size(
8067 bounds.size.height,
8068 window,
8069 cx,
8070 )
8071 });
8072 }
8073 })
8074 },
8075 |_, _, _, _| {},
8076 )
8077 .absolute()
8078 .size_full()
8079 })
8080 .when(self.zoomed.is_none(), |this| {
8081 this.on_drag_move(cx.listener(
8082 move |workspace, e: &DragMoveEvent<DraggedDock>, window, cx| {
8083 if workspace.previous_dock_drag_coordinates
8084 != Some(e.event.position)
8085 {
8086 workspace.previous_dock_drag_coordinates =
8087 Some(e.event.position);
8088
8089 match e.drag(cx).0 {
8090 DockPosition::Left => {
8091 workspace.resize_left_dock(
8092 e.event.position.x
8093 - workspace.bounds.left(),
8094 window,
8095 cx,
8096 );
8097 }
8098 DockPosition::Right => {
8099 workspace.resize_right_dock(
8100 workspace.bounds.right()
8101 - e.event.position.x,
8102 window,
8103 cx,
8104 );
8105 }
8106 DockPosition::Bottom => {
8107 workspace.resize_bottom_dock(
8108 workspace.bounds.bottom()
8109 - e.event.position.y,
8110 window,
8111 cx,
8112 );
8113 }
8114 };
8115 workspace.serialize_workspace(window, cx);
8116 }
8117 },
8118 ))
8119 .on_drag_move(cx.listener(
8120 move |workspace,
8121 e: &DragMoveEvent<DraggedDrawer>,
8122 window,
8123 cx| {
8124 match e.drag(cx).0 {
8125 DrawerPosition::Left => {
8126 workspace.resize_left_drawer(
8127 e.event.position.x - workspace.bounds.left(),
8128 window,
8129 cx,
8130 );
8131 }
8132 DrawerPosition::Right => {
8133 workspace.resize_right_drawer(
8134 workspace.bounds.right() - e.event.position.x,
8135 window,
8136 cx,
8137 );
8138 }
8139 }
8140 },
8141 ))
8142 })
8143 .child({
8144 match bottom_dock_layout {
8145 BottomDockLayout::Full => div()
8146 .flex()
8147 .flex_col()
8148 .h_full()
8149 .child(
8150 div()
8151 .flex()
8152 .flex_row()
8153 .flex_1()
8154 .overflow_hidden()
8155 .children(self.render_dock(
8156 DockPosition::Left,
8157 &self.left_dock,
8158 window,
8159 cx,
8160 ))
8161 .child(self.render_center_with_drawers(
8162 paddings, window, cx,
8163 ))
8164 .children(self.render_dock(
8165 DockPosition::Right,
8166 &self.right_dock,
8167 window,
8168 cx,
8169 )),
8170 )
8171 .child(div().w_full().children(self.render_dock(
8172 DockPosition::Bottom,
8173 &self.bottom_dock,
8174 window,
8175 cx,
8176 ))),
8177
8178 BottomDockLayout::LeftAligned => div()
8179 .flex()
8180 .flex_row()
8181 .h_full()
8182 .child(
8183 div()
8184 .flex()
8185 .flex_col()
8186 .flex_1()
8187 .h_full()
8188 .child(
8189 div()
8190 .flex()
8191 .flex_row()
8192 .flex_1()
8193 .children(self.render_dock(
8194 DockPosition::Left,
8195 &self.left_dock,
8196 window,
8197 cx,
8198 ))
8199 .child(self.render_center_with_drawers(
8200 paddings, window, cx,
8201 )),
8202 )
8203 .child(div().w_full().children(self.render_dock(
8204 DockPosition::Bottom,
8205 &self.bottom_dock,
8206 window,
8207 cx,
8208 ))),
8209 )
8210 .children(self.render_dock(
8211 DockPosition::Right,
8212 &self.right_dock,
8213 window,
8214 cx,
8215 )),
8216
8217 BottomDockLayout::RightAligned => div()
8218 .flex()
8219 .flex_row()
8220 .h_full()
8221 .children(self.render_dock(
8222 DockPosition::Left,
8223 &self.left_dock,
8224 window,
8225 cx,
8226 ))
8227 .child(
8228 div()
8229 .flex()
8230 .flex_col()
8231 .flex_1()
8232 .h_full()
8233 .child(
8234 div()
8235 .flex()
8236 .flex_row()
8237 .flex_1()
8238 .child(self.render_center_with_drawers(
8239 paddings, window, cx,
8240 ))
8241 .children(self.render_dock(
8242 DockPosition::Right,
8243 &self.right_dock,
8244 window,
8245 cx,
8246 )),
8247 )
8248 .child(div().w_full().children(self.render_dock(
8249 DockPosition::Bottom,
8250 &self.bottom_dock,
8251 window,
8252 cx,
8253 ))),
8254 ),
8255
8256 BottomDockLayout::Contained => div()
8257 .flex()
8258 .flex_row()
8259 .h_full()
8260 .children(self.render_dock(
8261 DockPosition::Left,
8262 &self.left_dock,
8263 window,
8264 cx,
8265 ))
8266 .child(
8267 div()
8268 .flex()
8269 .flex_col()
8270 .flex_1()
8271 .overflow_hidden()
8272 .child(self.render_center_with_drawers(
8273 paddings, window, cx,
8274 ))
8275 .children(self.render_dock(
8276 DockPosition::Bottom,
8277 &self.bottom_dock,
8278 window,
8279 cx,
8280 )),
8281 )
8282 .children(self.render_dock(
8283 DockPosition::Right,
8284 &self.right_dock,
8285 window,
8286 cx,
8287 )),
8288 }
8289 })
8290 .children(self.zoomed.as_ref().and_then(|view| {
8291 let zoomed_view = view.upgrade()?;
8292 let div = div()
8293 .occlude()
8294 .absolute()
8295 .overflow_hidden()
8296 .border_color(colors.border)
8297 .bg(colors.background)
8298 .child(zoomed_view)
8299 .inset_0()
8300 .shadow_lg();
8301
8302 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8303 return Some(div);
8304 }
8305
8306 Some(match self.zoomed_position {
8307 Some(DockPosition::Left) => div.right_2().border_r_1(),
8308 Some(DockPosition::Right) => div.left_2().border_l_1(),
8309 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8310 None => div.top_2().bottom_2().left_2().right_2().border_1(),
8311 })
8312 }))
8313 .children(self.render_notifications(window, cx)),
8314 )
8315 .when(self.status_bar_visible(cx), |parent| {
8316 parent.child(self.status_bar.clone())
8317 })
8318 .child(self.toast_layer.clone()),
8319 )
8320 }
8321}
8322
8323impl WorkspaceStore {
8324 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8325 Self {
8326 workspaces: Default::default(),
8327 _subscriptions: vec![
8328 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8329 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8330 ],
8331 client,
8332 }
8333 }
8334
8335 pub fn update_followers(
8336 &self,
8337 project_id: Option<u64>,
8338 update: proto::update_followers::Variant,
8339 cx: &App,
8340 ) -> Option<()> {
8341 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8342 let room_id = active_call.0.room_id(cx)?;
8343 self.client
8344 .send(proto::UpdateFollowers {
8345 room_id,
8346 project_id,
8347 variant: Some(update),
8348 })
8349 .log_err()
8350 }
8351
8352 pub async fn handle_follow(
8353 this: Entity<Self>,
8354 envelope: TypedEnvelope<proto::Follow>,
8355 mut cx: AsyncApp,
8356 ) -> Result<proto::FollowResponse> {
8357 this.update(&mut cx, |this, cx| {
8358 let follower = Follower {
8359 project_id: envelope.payload.project_id,
8360 peer_id: envelope.original_sender_id()?,
8361 };
8362
8363 let mut response = proto::FollowResponse::default();
8364
8365 this.workspaces.retain(|(window_handle, weak_workspace)| {
8366 let Some(workspace) = weak_workspace.upgrade() else {
8367 return false;
8368 };
8369 window_handle
8370 .update(cx, |_, window, cx| {
8371 workspace.update(cx, |workspace, cx| {
8372 let handler_response =
8373 workspace.handle_follow(follower.project_id, window, cx);
8374 if let Some(active_view) = handler_response.active_view
8375 && workspace.project.read(cx).remote_id() == follower.project_id
8376 {
8377 response.active_view = Some(active_view)
8378 }
8379 });
8380 })
8381 .is_ok()
8382 });
8383
8384 Ok(response)
8385 })
8386 }
8387
8388 async fn handle_update_followers(
8389 this: Entity<Self>,
8390 envelope: TypedEnvelope<proto::UpdateFollowers>,
8391 mut cx: AsyncApp,
8392 ) -> Result<()> {
8393 let leader_id = envelope.original_sender_id()?;
8394 let update = envelope.payload;
8395
8396 this.update(&mut cx, |this, cx| {
8397 this.workspaces.retain(|(window_handle, weak_workspace)| {
8398 let Some(workspace) = weak_workspace.upgrade() else {
8399 return false;
8400 };
8401 window_handle
8402 .update(cx, |_, window, cx| {
8403 workspace.update(cx, |workspace, cx| {
8404 let project_id = workspace.project.read(cx).remote_id();
8405 if update.project_id != project_id && update.project_id.is_some() {
8406 return;
8407 }
8408 workspace.handle_update_followers(
8409 leader_id,
8410 update.clone(),
8411 window,
8412 cx,
8413 );
8414 });
8415 })
8416 .is_ok()
8417 });
8418 Ok(())
8419 })
8420 }
8421
8422 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8423 self.workspaces.iter().map(|(_, weak)| weak)
8424 }
8425
8426 pub fn workspaces_with_windows(
8427 &self,
8428 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8429 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8430 }
8431}
8432
8433impl ViewId {
8434 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8435 Ok(Self {
8436 creator: message
8437 .creator
8438 .map(CollaboratorId::PeerId)
8439 .context("creator is missing")?,
8440 id: message.id,
8441 })
8442 }
8443
8444 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8445 if let CollaboratorId::PeerId(peer_id) = self.creator {
8446 Some(proto::ViewId {
8447 creator: Some(peer_id),
8448 id: self.id,
8449 })
8450 } else {
8451 None
8452 }
8453 }
8454}
8455
8456impl FollowerState {
8457 fn pane(&self) -> &Entity<Pane> {
8458 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8459 }
8460}
8461
8462pub trait WorkspaceHandle {
8463 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8464}
8465
8466impl WorkspaceHandle for Entity<Workspace> {
8467 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8468 self.read(cx)
8469 .worktrees(cx)
8470 .flat_map(|worktree| {
8471 let worktree_id = worktree.read(cx).id();
8472 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8473 worktree_id,
8474 path: f.path.clone(),
8475 })
8476 })
8477 .collect::<Vec<_>>()
8478 }
8479}
8480
8481pub async fn last_opened_workspace_location(
8482 fs: &dyn fs::Fs,
8483) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8484 DB.last_workspace(fs)
8485 .await
8486 .log_err()
8487 .flatten()
8488 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8489}
8490
8491pub async fn last_session_workspace_locations(
8492 last_session_id: &str,
8493 last_session_window_stack: Option<Vec<WindowId>>,
8494 fs: &dyn fs::Fs,
8495) -> Option<Vec<SessionWorkspace>> {
8496 DB.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8497 .await
8498 .log_err()
8499}
8500
8501pub struct MultiWorkspaceRestoreResult {
8502 pub window_handle: WindowHandle<MultiWorkspace>,
8503 pub errors: Vec<anyhow::Error>,
8504}
8505
8506pub async fn restore_multiworkspace(
8507 multi_workspace: SerializedMultiWorkspace,
8508 app_state: Arc<AppState>,
8509 cx: &mut AsyncApp,
8510) -> anyhow::Result<MultiWorkspaceRestoreResult> {
8511 let SerializedMultiWorkspace {
8512 workspaces,
8513 state,
8514 id: window_id,
8515 } = multi_workspace;
8516 let mut group_iter = workspaces.into_iter();
8517 let first = group_iter
8518 .next()
8519 .context("window group must not be empty")?;
8520
8521 let window_handle = if first.paths.is_empty() {
8522 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
8523 .await?
8524 } else {
8525 let OpenResult { window, .. } = cx
8526 .update(|cx| {
8527 Workspace::new_local(
8528 first.paths.paths().to_vec(),
8529 app_state.clone(),
8530 None,
8531 None,
8532 None,
8533 true,
8534 cx,
8535 )
8536 })
8537 .await?;
8538 window
8539 };
8540
8541 let mut errors = Vec::new();
8542
8543 for session_workspace in group_iter {
8544 let error = if session_workspace.paths.is_empty() {
8545 cx.update(|cx| {
8546 open_workspace_by_id(
8547 session_workspace.workspace_id,
8548 app_state.clone(),
8549 Some(window_handle),
8550 cx,
8551 )
8552 })
8553 .await
8554 .err()
8555 } else {
8556 cx.update(|cx| {
8557 Workspace::new_local(
8558 session_workspace.paths.paths().to_vec(),
8559 app_state.clone(),
8560 Some(window_handle),
8561 None,
8562 None,
8563 true,
8564 cx,
8565 )
8566 })
8567 .await
8568 .err()
8569 };
8570
8571 if let Some(error) = error {
8572 errors.push(error);
8573 }
8574 }
8575
8576 if let Some(target_id) = state.active_workspace_id {
8577 window_handle
8578 .update(cx, |multi_workspace, window, cx| {
8579 multi_workspace.set_database_id(window_id);
8580 let target_index = multi_workspace
8581 .workspaces()
8582 .iter()
8583 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8584 if let Some(index) = target_index {
8585 multi_workspace.activate_index(index, window, cx);
8586 } else if !multi_workspace.workspaces().is_empty() {
8587 multi_workspace.activate_index(0, window, cx);
8588 }
8589 })
8590 .ok();
8591 } else {
8592 window_handle
8593 .update(cx, |multi_workspace, window, cx| {
8594 if !multi_workspace.workspaces().is_empty() {
8595 multi_workspace.activate_index(0, window, cx);
8596 }
8597 })
8598 .ok();
8599 }
8600
8601 window_handle
8602 .update(cx, |_, window, _cx| {
8603 window.activate_window();
8604 })
8605 .ok();
8606
8607 Ok(MultiWorkspaceRestoreResult {
8608 window_handle,
8609 errors,
8610 })
8611}
8612
8613actions!(
8614 collab,
8615 [
8616 /// Opens the channel notes for the current call.
8617 ///
8618 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8619 /// channel in the collab panel.
8620 ///
8621 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8622 /// can be copied via "Copy link to section" in the context menu of the channel notes
8623 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8624 OpenChannelNotes,
8625 /// Mutes your microphone.
8626 Mute,
8627 /// Deafens yourself (mute both microphone and speakers).
8628 Deafen,
8629 /// Leaves the current call.
8630 LeaveCall,
8631 /// Shares the current project with collaborators.
8632 ShareProject,
8633 /// Shares your screen with collaborators.
8634 ScreenShare,
8635 /// Copies the current room name and session id for debugging purposes.
8636 CopyRoomId,
8637 ]
8638);
8639
8640/// Opens the channel notes for a specific channel by its ID.
8641#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8642#[action(namespace = collab)]
8643#[serde(deny_unknown_fields)]
8644pub struct OpenChannelNotesById {
8645 pub channel_id: u64,
8646}
8647
8648actions!(
8649 zed,
8650 [
8651 /// Opens the Zed log file.
8652 OpenLog,
8653 /// Reveals the Zed log file in the system file manager.
8654 RevealLogInFileManager
8655 ]
8656);
8657
8658async fn join_channel_internal(
8659 channel_id: ChannelId,
8660 app_state: &Arc<AppState>,
8661 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8662 requesting_workspace: Option<WeakEntity<Workspace>>,
8663 active_call: &dyn AnyActiveCall,
8664 cx: &mut AsyncApp,
8665) -> Result<bool> {
8666 let (should_prompt, already_in_channel) = cx.update(|cx| {
8667 if !active_call.is_in_room(cx) {
8668 return (false, false);
8669 }
8670
8671 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8672 let should_prompt = active_call.is_sharing_project(cx)
8673 && active_call.has_remote_participants(cx)
8674 && !already_in_channel;
8675 (should_prompt, already_in_channel)
8676 });
8677
8678 if already_in_channel {
8679 let task = cx.update(|cx| {
8680 if let Some((project, host)) = active_call.most_active_project(cx) {
8681 Some(join_in_room_project(project, host, app_state.clone(), cx))
8682 } else {
8683 None
8684 }
8685 });
8686 if let Some(task) = task {
8687 task.await?;
8688 }
8689 return anyhow::Ok(true);
8690 }
8691
8692 if should_prompt {
8693 if let Some(multi_workspace) = requesting_window {
8694 let answer = multi_workspace
8695 .update(cx, |_, window, cx| {
8696 window.prompt(
8697 PromptLevel::Warning,
8698 "Do you want to switch channels?",
8699 Some("Leaving this call will unshare your current project."),
8700 &["Yes, Join Channel", "Cancel"],
8701 cx,
8702 )
8703 })?
8704 .await;
8705
8706 if answer == Ok(1) {
8707 return Ok(false);
8708 }
8709 } else {
8710 return Ok(false);
8711 }
8712 }
8713
8714 let client = cx.update(|cx| active_call.client(cx));
8715
8716 let mut client_status = client.status();
8717
8718 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8719 'outer: loop {
8720 let Some(status) = client_status.recv().await else {
8721 anyhow::bail!("error connecting");
8722 };
8723
8724 match status {
8725 Status::Connecting
8726 | Status::Authenticating
8727 | Status::Authenticated
8728 | Status::Reconnecting
8729 | Status::Reauthenticating
8730 | Status::Reauthenticated => continue,
8731 Status::Connected { .. } => break 'outer,
8732 Status::SignedOut | Status::AuthenticationError => {
8733 return Err(ErrorCode::SignedOut.into());
8734 }
8735 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8736 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8737 return Err(ErrorCode::Disconnected.into());
8738 }
8739 }
8740 }
8741
8742 let joined = cx
8743 .update(|cx| active_call.join_channel(channel_id, cx))
8744 .await?;
8745
8746 if !joined {
8747 return anyhow::Ok(true);
8748 }
8749
8750 cx.update(|cx| active_call.room_update_completed(cx)).await;
8751
8752 let task = cx.update(|cx| {
8753 if let Some((project, host)) = active_call.most_active_project(cx) {
8754 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8755 }
8756
8757 // If you are the first to join a channel, see if you should share your project.
8758 if !active_call.has_remote_participants(cx)
8759 && !active_call.local_participant_is_guest(cx)
8760 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8761 {
8762 let project = workspace.update(cx, |workspace, cx| {
8763 let project = workspace.project.read(cx);
8764
8765 if !active_call.share_on_join(cx) {
8766 return None;
8767 }
8768
8769 if (project.is_local() || project.is_via_remote_server())
8770 && project.visible_worktrees(cx).any(|tree| {
8771 tree.read(cx)
8772 .root_entry()
8773 .is_some_and(|entry| entry.is_dir())
8774 })
8775 {
8776 Some(workspace.project.clone())
8777 } else {
8778 None
8779 }
8780 });
8781 if let Some(project) = project {
8782 let share_task = active_call.share_project(project, cx);
8783 return Some(cx.spawn(async move |_cx| -> Result<()> {
8784 share_task.await?;
8785 Ok(())
8786 }));
8787 }
8788 }
8789
8790 None
8791 });
8792 if let Some(task) = task {
8793 task.await?;
8794 return anyhow::Ok(true);
8795 }
8796 anyhow::Ok(false)
8797}
8798
8799pub fn join_channel(
8800 channel_id: ChannelId,
8801 app_state: Arc<AppState>,
8802 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8803 requesting_workspace: Option<WeakEntity<Workspace>>,
8804 cx: &mut App,
8805) -> Task<Result<()>> {
8806 let active_call = GlobalAnyActiveCall::global(cx).clone();
8807 cx.spawn(async move |cx| {
8808 let result = join_channel_internal(
8809 channel_id,
8810 &app_state,
8811 requesting_window,
8812 requesting_workspace,
8813 &*active_call.0,
8814 cx,
8815 )
8816 .await;
8817
8818 // join channel succeeded, and opened a window
8819 if matches!(result, Ok(true)) {
8820 return anyhow::Ok(());
8821 }
8822
8823 // find an existing workspace to focus and show call controls
8824 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8825 if active_window.is_none() {
8826 // no open workspaces, make one to show the error in (blergh)
8827 let OpenResult {
8828 window: window_handle,
8829 ..
8830 } = cx
8831 .update(|cx| {
8832 Workspace::new_local(
8833 vec![],
8834 app_state.clone(),
8835 requesting_window,
8836 None,
8837 None,
8838 true,
8839 cx,
8840 )
8841 })
8842 .await?;
8843
8844 window_handle
8845 .update(cx, |_, window, _cx| {
8846 window.activate_window();
8847 })
8848 .ok();
8849
8850 if result.is_ok() {
8851 cx.update(|cx| {
8852 cx.dispatch_action(&OpenChannelNotes);
8853 });
8854 }
8855
8856 active_window = Some(window_handle);
8857 }
8858
8859 if let Err(err) = result {
8860 log::error!("failed to join channel: {}", err);
8861 if let Some(active_window) = active_window {
8862 active_window
8863 .update(cx, |_, window, cx| {
8864 let detail: SharedString = match err.error_code() {
8865 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8866 ErrorCode::UpgradeRequired => concat!(
8867 "Your are running an unsupported version of Zed. ",
8868 "Please update to continue."
8869 )
8870 .into(),
8871 ErrorCode::NoSuchChannel => concat!(
8872 "No matching channel was found. ",
8873 "Please check the link and try again."
8874 )
8875 .into(),
8876 ErrorCode::Forbidden => concat!(
8877 "This channel is private, and you do not have access. ",
8878 "Please ask someone to add you and try again."
8879 )
8880 .into(),
8881 ErrorCode::Disconnected => {
8882 "Please check your internet connection and try again.".into()
8883 }
8884 _ => format!("{}\n\nPlease try again.", err).into(),
8885 };
8886 window.prompt(
8887 PromptLevel::Critical,
8888 "Failed to join channel",
8889 Some(&detail),
8890 &["Ok"],
8891 cx,
8892 )
8893 })?
8894 .await
8895 .ok();
8896 }
8897 }
8898
8899 // return ok, we showed the error to the user.
8900 anyhow::Ok(())
8901 })
8902}
8903
8904pub async fn get_any_active_multi_workspace(
8905 app_state: Arc<AppState>,
8906 mut cx: AsyncApp,
8907) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8908 // find an existing workspace to focus and show call controls
8909 let active_window = activate_any_workspace_window(&mut cx);
8910 if active_window.is_none() {
8911 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
8912 .await?;
8913 }
8914 activate_any_workspace_window(&mut cx).context("could not open zed")
8915}
8916
8917fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
8918 cx.update(|cx| {
8919 if let Some(workspace_window) = cx
8920 .active_window()
8921 .and_then(|window| window.downcast::<MultiWorkspace>())
8922 {
8923 return Some(workspace_window);
8924 }
8925
8926 for window in cx.windows() {
8927 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
8928 workspace_window
8929 .update(cx, |_, window, _| window.activate_window())
8930 .ok();
8931 return Some(workspace_window);
8932 }
8933 }
8934 None
8935 })
8936}
8937
8938pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
8939 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
8940}
8941
8942pub fn workspace_windows_for_location(
8943 serialized_location: &SerializedWorkspaceLocation,
8944 cx: &App,
8945) -> Vec<WindowHandle<MultiWorkspace>> {
8946 cx.windows()
8947 .into_iter()
8948 .filter_map(|window| window.downcast::<MultiWorkspace>())
8949 .filter(|multi_workspace| {
8950 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
8951 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
8952 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
8953 }
8954 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
8955 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
8956 a.distro_name == b.distro_name
8957 }
8958 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
8959 a.container_id == b.container_id
8960 }
8961 #[cfg(any(test, feature = "test-support"))]
8962 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
8963 a.id == b.id
8964 }
8965 _ => false,
8966 };
8967
8968 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
8969 multi_workspace.workspaces().iter().any(|workspace| {
8970 match workspace.read(cx).workspace_location(cx) {
8971 WorkspaceLocation::Location(location, _) => {
8972 match (&location, serialized_location) {
8973 (
8974 SerializedWorkspaceLocation::Local,
8975 SerializedWorkspaceLocation::Local,
8976 ) => true,
8977 (
8978 SerializedWorkspaceLocation::Remote(a),
8979 SerializedWorkspaceLocation::Remote(b),
8980 ) => same_host(a, b),
8981 _ => false,
8982 }
8983 }
8984 _ => false,
8985 }
8986 })
8987 })
8988 })
8989 .collect()
8990}
8991
8992pub async fn find_existing_workspace(
8993 abs_paths: &[PathBuf],
8994 open_options: &OpenOptions,
8995 location: &SerializedWorkspaceLocation,
8996 cx: &mut AsyncApp,
8997) -> (
8998 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
8999 OpenVisible,
9000) {
9001 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
9002 let mut open_visible = OpenVisible::All;
9003 let mut best_match = None;
9004
9005 if open_options.open_new_workspace != Some(true) {
9006 cx.update(|cx| {
9007 for window in workspace_windows_for_location(location, cx) {
9008 if let Ok(multi_workspace) = window.read(cx) {
9009 for workspace in multi_workspace.workspaces() {
9010 let project = workspace.read(cx).project.read(cx);
9011 let m = project.visibility_for_paths(
9012 abs_paths,
9013 open_options.open_new_workspace == None,
9014 cx,
9015 );
9016 if m > best_match {
9017 existing = Some((window, workspace.clone()));
9018 best_match = m;
9019 } else if best_match.is_none()
9020 && open_options.open_new_workspace == Some(false)
9021 {
9022 existing = Some((window, workspace.clone()))
9023 }
9024 }
9025 }
9026 }
9027 });
9028
9029 let all_paths_are_files = existing
9030 .as_ref()
9031 .and_then(|(_, target_workspace)| {
9032 cx.update(|cx| {
9033 let workspace = target_workspace.read(cx);
9034 let project = workspace.project.read(cx);
9035 let path_style = workspace.path_style(cx);
9036 Some(!abs_paths.iter().any(|path| {
9037 let path = util::paths::SanitizedPath::new(path);
9038 project.worktrees(cx).any(|worktree| {
9039 let worktree = worktree.read(cx);
9040 let abs_path = worktree.abs_path();
9041 path_style
9042 .strip_prefix(path.as_ref(), abs_path.as_ref())
9043 .and_then(|rel| worktree.entry_for_path(&rel))
9044 .is_some_and(|e| e.is_dir())
9045 })
9046 }))
9047 })
9048 })
9049 .unwrap_or(false);
9050
9051 if open_options.open_new_workspace.is_none()
9052 && existing.is_some()
9053 && open_options.wait
9054 && all_paths_are_files
9055 {
9056 cx.update(|cx| {
9057 let windows = workspace_windows_for_location(location, cx);
9058 let window = cx
9059 .active_window()
9060 .and_then(|window| window.downcast::<MultiWorkspace>())
9061 .filter(|window| windows.contains(window))
9062 .or_else(|| windows.into_iter().next());
9063 if let Some(window) = window {
9064 if let Ok(multi_workspace) = window.read(cx) {
9065 let active_workspace = multi_workspace.workspace().clone();
9066 existing = Some((window, active_workspace));
9067 open_visible = OpenVisible::None;
9068 }
9069 }
9070 });
9071 }
9072 }
9073 (existing, open_visible)
9074}
9075
9076#[derive(Default, Clone)]
9077pub struct OpenOptions {
9078 pub visible: Option<OpenVisible>,
9079 pub focus: Option<bool>,
9080 pub open_new_workspace: Option<bool>,
9081 pub wait: bool,
9082 pub replace_window: Option<WindowHandle<MultiWorkspace>>,
9083 pub env: Option<HashMap<String, String>>,
9084}
9085
9086/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
9087/// or [`Workspace::open_workspace_for_paths`].
9088pub struct OpenResult {
9089 pub window: WindowHandle<MultiWorkspace>,
9090 pub workspace: Entity<Workspace>,
9091 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
9092}
9093
9094/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
9095pub fn open_workspace_by_id(
9096 workspace_id: WorkspaceId,
9097 app_state: Arc<AppState>,
9098 requesting_window: Option<WindowHandle<MultiWorkspace>>,
9099 cx: &mut App,
9100) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
9101 let project_handle = Project::local(
9102 app_state.client.clone(),
9103 app_state.node_runtime.clone(),
9104 app_state.user_store.clone(),
9105 app_state.languages.clone(),
9106 app_state.fs.clone(),
9107 None,
9108 project::LocalProjectFlags {
9109 init_worktree_trust: true,
9110 ..project::LocalProjectFlags::default()
9111 },
9112 cx,
9113 );
9114
9115 cx.spawn(async move |cx| {
9116 let serialized_workspace = persistence::DB
9117 .workspace_for_id(workspace_id)
9118 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
9119
9120 let centered_layout = serialized_workspace.centered_layout;
9121
9122 let (window, workspace) = if let Some(window) = requesting_window {
9123 let workspace = window.update(cx, |multi_workspace, window, cx| {
9124 let workspace = cx.new(|cx| {
9125 let mut workspace = Workspace::new(
9126 Some(workspace_id),
9127 project_handle.clone(),
9128 app_state.clone(),
9129 window,
9130 cx,
9131 );
9132 workspace.centered_layout = centered_layout;
9133 workspace
9134 });
9135 multi_workspace.add_workspace(workspace.clone(), cx);
9136 workspace
9137 })?;
9138 (window, workspace)
9139 } else {
9140 let window_bounds_override = window_bounds_env_override();
9141
9142 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
9143 (Some(WindowBounds::Windowed(bounds)), None)
9144 } else if let Some(display) = serialized_workspace.display
9145 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
9146 {
9147 (Some(bounds.0), Some(display))
9148 } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
9149 (Some(bounds), Some(display))
9150 } else {
9151 (None, None)
9152 };
9153
9154 let options = cx.update(|cx| {
9155 let mut options = (app_state.build_window_options)(display, cx);
9156 options.window_bounds = window_bounds;
9157 options
9158 });
9159
9160 let window = cx.open_window(options, {
9161 let app_state = app_state.clone();
9162 let project_handle = project_handle.clone();
9163 move |window, cx| {
9164 let workspace = cx.new(|cx| {
9165 let mut workspace = Workspace::new(
9166 Some(workspace_id),
9167 project_handle,
9168 app_state,
9169 window,
9170 cx,
9171 );
9172 workspace.centered_layout = centered_layout;
9173 workspace
9174 });
9175 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9176 }
9177 })?;
9178
9179 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
9180 multi_workspace.workspace().clone()
9181 })?;
9182
9183 (window, workspace)
9184 };
9185
9186 notify_if_database_failed(window, cx);
9187
9188 // Restore items from the serialized workspace
9189 window
9190 .update(cx, |_, window, cx| {
9191 workspace.update(cx, |_workspace, cx| {
9192 open_items(Some(serialized_workspace), vec![], window, cx)
9193 })
9194 })?
9195 .await?;
9196
9197 window.update(cx, |_, window, cx| {
9198 workspace.update(cx, |workspace, cx| {
9199 workspace.serialize_workspace(window, cx);
9200 });
9201 })?;
9202
9203 Ok(window)
9204 })
9205}
9206
9207#[allow(clippy::type_complexity)]
9208pub fn open_paths(
9209 abs_paths: &[PathBuf],
9210 app_state: Arc<AppState>,
9211 open_options: OpenOptions,
9212 cx: &mut App,
9213) -> Task<anyhow::Result<OpenResult>> {
9214 let abs_paths = abs_paths.to_vec();
9215 #[cfg(target_os = "windows")]
9216 let wsl_path = abs_paths
9217 .iter()
9218 .find_map(|p| util::paths::WslPath::from_path(p));
9219
9220 cx.spawn(async move |cx| {
9221 let (mut existing, mut open_visible) = find_existing_workspace(
9222 &abs_paths,
9223 &open_options,
9224 &SerializedWorkspaceLocation::Local,
9225 cx,
9226 )
9227 .await;
9228
9229 // Fallback: if no workspace contains the paths and all paths are files,
9230 // prefer an existing local workspace window (active window first).
9231 if open_options.open_new_workspace.is_none() && existing.is_none() {
9232 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9233 let all_metadatas = futures::future::join_all(all_paths)
9234 .await
9235 .into_iter()
9236 .filter_map(|result| result.ok().flatten())
9237 .collect::<Vec<_>>();
9238
9239 if all_metadatas.iter().all(|file| !file.is_dir) {
9240 cx.update(|cx| {
9241 let windows = workspace_windows_for_location(
9242 &SerializedWorkspaceLocation::Local,
9243 cx,
9244 );
9245 let window = cx
9246 .active_window()
9247 .and_then(|window| window.downcast::<MultiWorkspace>())
9248 .filter(|window| windows.contains(window))
9249 .or_else(|| windows.into_iter().next());
9250 if let Some(window) = window {
9251 if let Ok(multi_workspace) = window.read(cx) {
9252 let active_workspace = multi_workspace.workspace().clone();
9253 existing = Some((window, active_workspace));
9254 open_visible = OpenVisible::None;
9255 }
9256 }
9257 });
9258 }
9259 }
9260
9261 let result = if let Some((existing, target_workspace)) = existing {
9262 let open_task = existing
9263 .update(cx, |multi_workspace, window, cx| {
9264 window.activate_window();
9265 multi_workspace.activate(target_workspace.clone(), cx);
9266 target_workspace.update(cx, |workspace, cx| {
9267 workspace.open_paths(
9268 abs_paths,
9269 OpenOptions {
9270 visible: Some(open_visible),
9271 ..Default::default()
9272 },
9273 None,
9274 window,
9275 cx,
9276 )
9277 })
9278 })?
9279 .await;
9280
9281 _ = existing.update(cx, |multi_workspace, _, cx| {
9282 let workspace = multi_workspace.workspace().clone();
9283 workspace.update(cx, |workspace, cx| {
9284 for item in open_task.iter().flatten() {
9285 if let Err(e) = item {
9286 workspace.show_error(&e, cx);
9287 }
9288 }
9289 });
9290 });
9291
9292 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9293 } else {
9294 let result = cx
9295 .update(move |cx| {
9296 Workspace::new_local(
9297 abs_paths,
9298 app_state.clone(),
9299 open_options.replace_window,
9300 open_options.env,
9301 None,
9302 true,
9303 cx,
9304 )
9305 })
9306 .await;
9307
9308 if let Ok(ref result) = result {
9309 result.window
9310 .update(cx, |_, window, _cx| {
9311 window.activate_window();
9312 })
9313 .log_err();
9314 }
9315
9316 result
9317 };
9318
9319 #[cfg(target_os = "windows")]
9320 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9321 && let Ok(ref result) = result
9322 {
9323 result.window
9324 .update(cx, move |multi_workspace, _window, cx| {
9325 struct OpenInWsl;
9326 let workspace = multi_workspace.workspace().clone();
9327 workspace.update(cx, |workspace, cx| {
9328 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9329 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9330 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9331 cx.new(move |cx| {
9332 MessageNotification::new(msg, cx)
9333 .primary_message("Open in WSL")
9334 .primary_icon(IconName::FolderOpen)
9335 .primary_on_click(move |window, cx| {
9336 window.dispatch_action(Box::new(remote::OpenWslPath {
9337 distro: remote::WslConnectionOptions {
9338 distro_name: distro.clone(),
9339 user: None,
9340 },
9341 paths: vec![path.clone().into()],
9342 }), cx)
9343 })
9344 })
9345 });
9346 });
9347 })
9348 .unwrap();
9349 };
9350 result
9351 })
9352}
9353
9354pub fn open_new(
9355 open_options: OpenOptions,
9356 app_state: Arc<AppState>,
9357 cx: &mut App,
9358 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9359) -> Task<anyhow::Result<()>> {
9360 let task = Workspace::new_local(
9361 Vec::new(),
9362 app_state,
9363 open_options.replace_window,
9364 open_options.env,
9365 Some(Box::new(init)),
9366 true,
9367 cx,
9368 );
9369 cx.spawn(async move |cx| {
9370 let OpenResult { window, .. } = task.await?;
9371 window
9372 .update(cx, |_, window, _cx| {
9373 window.activate_window();
9374 })
9375 .ok();
9376 Ok(())
9377 })
9378}
9379
9380pub fn create_and_open_local_file(
9381 path: &'static Path,
9382 window: &mut Window,
9383 cx: &mut Context<Workspace>,
9384 default_content: impl 'static + Send + FnOnce() -> Rope,
9385) -> Task<Result<Box<dyn ItemHandle>>> {
9386 cx.spawn_in(window, async move |workspace, cx| {
9387 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9388 if !fs.is_file(path).await {
9389 fs.create_file(path, Default::default()).await?;
9390 fs.save(path, &default_content(), Default::default())
9391 .await?;
9392 }
9393
9394 workspace
9395 .update_in(cx, |workspace, window, cx| {
9396 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9397 let path = workspace
9398 .project
9399 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9400 cx.spawn_in(window, async move |workspace, cx| {
9401 let path = path.await?;
9402 let mut items = workspace
9403 .update_in(cx, |workspace, window, cx| {
9404 workspace.open_paths(
9405 vec![path.to_path_buf()],
9406 OpenOptions {
9407 visible: Some(OpenVisible::None),
9408 ..Default::default()
9409 },
9410 None,
9411 window,
9412 cx,
9413 )
9414 })?
9415 .await;
9416 let item = items.pop().flatten();
9417 item.with_context(|| format!("path {path:?} is not a file"))?
9418 })
9419 })
9420 })?
9421 .await?
9422 .await
9423 })
9424}
9425
9426pub fn open_remote_project_with_new_connection(
9427 window: WindowHandle<MultiWorkspace>,
9428 remote_connection: Arc<dyn RemoteConnection>,
9429 cancel_rx: oneshot::Receiver<()>,
9430 delegate: Arc<dyn RemoteClientDelegate>,
9431 app_state: Arc<AppState>,
9432 paths: Vec<PathBuf>,
9433 cx: &mut App,
9434) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9435 cx.spawn(async move |cx| {
9436 let (workspace_id, serialized_workspace) =
9437 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9438 .await?;
9439
9440 let session = match cx
9441 .update(|cx| {
9442 remote::RemoteClient::new(
9443 ConnectionIdentifier::Workspace(workspace_id.0),
9444 remote_connection,
9445 cancel_rx,
9446 delegate,
9447 cx,
9448 )
9449 })
9450 .await?
9451 {
9452 Some(result) => result,
9453 None => return Ok(Vec::new()),
9454 };
9455
9456 let project = cx.update(|cx| {
9457 project::Project::remote(
9458 session,
9459 app_state.client.clone(),
9460 app_state.node_runtime.clone(),
9461 app_state.user_store.clone(),
9462 app_state.languages.clone(),
9463 app_state.fs.clone(),
9464 true,
9465 cx,
9466 )
9467 });
9468
9469 open_remote_project_inner(
9470 project,
9471 paths,
9472 workspace_id,
9473 serialized_workspace,
9474 app_state,
9475 window,
9476 cx,
9477 )
9478 .await
9479 })
9480}
9481
9482pub fn open_remote_project_with_existing_connection(
9483 connection_options: RemoteConnectionOptions,
9484 project: Entity<Project>,
9485 paths: Vec<PathBuf>,
9486 app_state: Arc<AppState>,
9487 window: WindowHandle<MultiWorkspace>,
9488 cx: &mut AsyncApp,
9489) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9490 cx.spawn(async move |cx| {
9491 let (workspace_id, serialized_workspace) =
9492 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9493
9494 open_remote_project_inner(
9495 project,
9496 paths,
9497 workspace_id,
9498 serialized_workspace,
9499 app_state,
9500 window,
9501 cx,
9502 )
9503 .await
9504 })
9505}
9506
9507async fn open_remote_project_inner(
9508 project: Entity<Project>,
9509 paths: Vec<PathBuf>,
9510 workspace_id: WorkspaceId,
9511 serialized_workspace: Option<SerializedWorkspace>,
9512 app_state: Arc<AppState>,
9513 window: WindowHandle<MultiWorkspace>,
9514 cx: &mut AsyncApp,
9515) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9516 let toolchains = DB.toolchains(workspace_id).await?;
9517 for (toolchain, worktree_path, path) in toolchains {
9518 project
9519 .update(cx, |this, cx| {
9520 let Some(worktree_id) =
9521 this.find_worktree(&worktree_path, cx)
9522 .and_then(|(worktree, rel_path)| {
9523 if rel_path.is_empty() {
9524 Some(worktree.read(cx).id())
9525 } else {
9526 None
9527 }
9528 })
9529 else {
9530 return Task::ready(None);
9531 };
9532
9533 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9534 })
9535 .await;
9536 }
9537 let mut project_paths_to_open = vec![];
9538 let mut project_path_errors = vec![];
9539
9540 for path in paths {
9541 let result = cx
9542 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9543 .await;
9544 match result {
9545 Ok((_, project_path)) => {
9546 project_paths_to_open.push((path.clone(), Some(project_path)));
9547 }
9548 Err(error) => {
9549 project_path_errors.push(error);
9550 }
9551 };
9552 }
9553
9554 if project_paths_to_open.is_empty() {
9555 return Err(project_path_errors.pop().context("no paths given")?);
9556 }
9557
9558 let workspace = window.update(cx, |multi_workspace, window, cx| {
9559 telemetry::event!("SSH Project Opened");
9560
9561 let new_workspace = cx.new(|cx| {
9562 let mut workspace =
9563 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9564 workspace.update_history(cx);
9565
9566 if let Some(ref serialized) = serialized_workspace {
9567 workspace.centered_layout = serialized.centered_layout;
9568 }
9569
9570 workspace
9571 });
9572
9573 multi_workspace.activate(new_workspace.clone(), cx);
9574 new_workspace
9575 })?;
9576
9577 let items = window
9578 .update(cx, |_, window, cx| {
9579 window.activate_window();
9580 workspace.update(cx, |_workspace, cx| {
9581 open_items(serialized_workspace, project_paths_to_open, window, cx)
9582 })
9583 })?
9584 .await?;
9585
9586 workspace.update(cx, |workspace, cx| {
9587 for error in project_path_errors {
9588 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9589 if let Some(path) = error.error_tag("path") {
9590 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9591 }
9592 } else {
9593 workspace.show_error(&error, cx)
9594 }
9595 }
9596 });
9597
9598 Ok(items.into_iter().map(|item| item?.ok()).collect())
9599}
9600
9601fn deserialize_remote_project(
9602 connection_options: RemoteConnectionOptions,
9603 paths: Vec<PathBuf>,
9604 cx: &AsyncApp,
9605) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9606 cx.background_spawn(async move {
9607 let remote_connection_id = persistence::DB
9608 .get_or_create_remote_connection(connection_options)
9609 .await?;
9610
9611 let serialized_workspace =
9612 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
9613
9614 let workspace_id = if let Some(workspace_id) =
9615 serialized_workspace.as_ref().map(|workspace| workspace.id)
9616 {
9617 workspace_id
9618 } else {
9619 persistence::DB.next_id().await?
9620 };
9621
9622 Ok((workspace_id, serialized_workspace))
9623 })
9624}
9625
9626pub fn join_in_room_project(
9627 project_id: u64,
9628 follow_user_id: u64,
9629 app_state: Arc<AppState>,
9630 cx: &mut App,
9631) -> Task<Result<()>> {
9632 let windows = cx.windows();
9633 cx.spawn(async move |cx| {
9634 let existing_window_and_workspace: Option<(
9635 WindowHandle<MultiWorkspace>,
9636 Entity<Workspace>,
9637 )> = windows.into_iter().find_map(|window_handle| {
9638 window_handle
9639 .downcast::<MultiWorkspace>()
9640 .and_then(|window_handle| {
9641 window_handle
9642 .update(cx, |multi_workspace, _window, cx| {
9643 for workspace in multi_workspace.workspaces() {
9644 if workspace.read(cx).project().read(cx).remote_id()
9645 == Some(project_id)
9646 {
9647 return Some((window_handle, workspace.clone()));
9648 }
9649 }
9650 None
9651 })
9652 .unwrap_or(None)
9653 })
9654 });
9655
9656 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9657 existing_window_and_workspace
9658 {
9659 existing_window
9660 .update(cx, |multi_workspace, _, cx| {
9661 multi_workspace.activate(target_workspace, cx);
9662 })
9663 .ok();
9664 existing_window
9665 } else {
9666 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9667 let project = cx
9668 .update(|cx| {
9669 active_call.0.join_project(
9670 project_id,
9671 app_state.languages.clone(),
9672 app_state.fs.clone(),
9673 cx,
9674 )
9675 })
9676 .await?;
9677
9678 let window_bounds_override = window_bounds_env_override();
9679 cx.update(|cx| {
9680 let mut options = (app_state.build_window_options)(None, cx);
9681 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9682 cx.open_window(options, |window, cx| {
9683 let workspace = cx.new(|cx| {
9684 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9685 });
9686 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9687 })
9688 })?
9689 };
9690
9691 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9692 cx.activate(true);
9693 window.activate_window();
9694
9695 // We set the active workspace above, so this is the correct workspace.
9696 let workspace = multi_workspace.workspace().clone();
9697 workspace.update(cx, |workspace, cx| {
9698 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9699 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9700 .or_else(|| {
9701 // If we couldn't follow the given user, follow the host instead.
9702 let collaborator = workspace
9703 .project()
9704 .read(cx)
9705 .collaborators()
9706 .values()
9707 .find(|collaborator| collaborator.is_host)?;
9708 Some(collaborator.peer_id)
9709 });
9710
9711 if let Some(follow_peer_id) = follow_peer_id {
9712 workspace.follow(follow_peer_id, window, cx);
9713 }
9714 });
9715 })?;
9716
9717 anyhow::Ok(())
9718 })
9719}
9720
9721pub fn reload(cx: &mut App) {
9722 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9723 let mut workspace_windows = cx
9724 .windows()
9725 .into_iter()
9726 .filter_map(|window| window.downcast::<MultiWorkspace>())
9727 .collect::<Vec<_>>();
9728
9729 // If multiple windows have unsaved changes, and need a save prompt,
9730 // prompt in the active window before switching to a different window.
9731 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9732
9733 let mut prompt = None;
9734 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9735 prompt = window
9736 .update(cx, |_, window, cx| {
9737 window.prompt(
9738 PromptLevel::Info,
9739 "Are you sure you want to restart?",
9740 None,
9741 &["Restart", "Cancel"],
9742 cx,
9743 )
9744 })
9745 .ok();
9746 }
9747
9748 cx.spawn(async move |cx| {
9749 if let Some(prompt) = prompt {
9750 let answer = prompt.await?;
9751 if answer != 0 {
9752 return anyhow::Ok(());
9753 }
9754 }
9755
9756 // If the user cancels any save prompt, then keep the app open.
9757 for window in workspace_windows {
9758 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9759 let workspace = multi_workspace.workspace().clone();
9760 workspace.update(cx, |workspace, cx| {
9761 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9762 })
9763 }) && !should_close.await?
9764 {
9765 return anyhow::Ok(());
9766 }
9767 }
9768 cx.update(|cx| cx.restart());
9769 anyhow::Ok(())
9770 })
9771 .detach_and_log_err(cx);
9772}
9773
9774fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9775 let mut parts = value.split(',');
9776 let x: usize = parts.next()?.parse().ok()?;
9777 let y: usize = parts.next()?.parse().ok()?;
9778 Some(point(px(x as f32), px(y as f32)))
9779}
9780
9781fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9782 let mut parts = value.split(',');
9783 let width: usize = parts.next()?.parse().ok()?;
9784 let height: usize = parts.next()?.parse().ok()?;
9785 Some(size(px(width as f32), px(height as f32)))
9786}
9787
9788/// Add client-side decorations (rounded corners, shadows, resize handling) when
9789/// appropriate.
9790///
9791/// The `border_radius_tiling` parameter allows overriding which corners get
9792/// rounded, independently of the actual window tiling state. This is used
9793/// specifically for the workspace switcher sidebar: when the sidebar is open,
9794/// we want square corners on the left (so the sidebar appears flush with the
9795/// window edge) but we still need the shadow padding for proper visual
9796/// appearance. Unlike actual window tiling, this only affects border radius -
9797/// not padding or shadows.
9798pub fn client_side_decorations(
9799 element: impl IntoElement,
9800 window: &mut Window,
9801 cx: &mut App,
9802 border_radius_tiling: Tiling,
9803) -> Stateful<Div> {
9804 const BORDER_SIZE: Pixels = px(1.0);
9805 let decorations = window.window_decorations();
9806 let tiling = match decorations {
9807 Decorations::Server => Tiling::default(),
9808 Decorations::Client { tiling } => tiling,
9809 };
9810
9811 match decorations {
9812 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9813 Decorations::Server => window.set_client_inset(px(0.0)),
9814 }
9815
9816 struct GlobalResizeEdge(ResizeEdge);
9817 impl Global for GlobalResizeEdge {}
9818
9819 div()
9820 .id("window-backdrop")
9821 .bg(transparent_black())
9822 .map(|div| match decorations {
9823 Decorations::Server => div,
9824 Decorations::Client { .. } => div
9825 .when(
9826 !(tiling.top
9827 || tiling.right
9828 || border_radius_tiling.top
9829 || border_radius_tiling.right),
9830 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9831 )
9832 .when(
9833 !(tiling.top
9834 || tiling.left
9835 || border_radius_tiling.top
9836 || border_radius_tiling.left),
9837 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9838 )
9839 .when(
9840 !(tiling.bottom
9841 || tiling.right
9842 || border_radius_tiling.bottom
9843 || border_radius_tiling.right),
9844 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9845 )
9846 .when(
9847 !(tiling.bottom
9848 || tiling.left
9849 || border_radius_tiling.bottom
9850 || border_radius_tiling.left),
9851 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9852 )
9853 .when(!tiling.top, |div| {
9854 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9855 })
9856 .when(!tiling.bottom, |div| {
9857 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9858 })
9859 .when(!tiling.left, |div| {
9860 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9861 })
9862 .when(!tiling.right, |div| {
9863 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9864 })
9865 .on_mouse_move(move |e, window, cx| {
9866 let size = window.window_bounds().get_bounds().size;
9867 let pos = e.position;
9868
9869 let new_edge =
9870 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9871
9872 let edge = cx.try_global::<GlobalResizeEdge>();
9873 if new_edge != edge.map(|edge| edge.0) {
9874 window
9875 .window_handle()
9876 .update(cx, |workspace, _, cx| {
9877 cx.notify(workspace.entity_id());
9878 })
9879 .ok();
9880 }
9881 })
9882 .on_mouse_down(MouseButton::Left, move |e, window, _| {
9883 let size = window.window_bounds().get_bounds().size;
9884 let pos = e.position;
9885
9886 let edge = match resize_edge(
9887 pos,
9888 theme::CLIENT_SIDE_DECORATION_SHADOW,
9889 size,
9890 tiling,
9891 ) {
9892 Some(value) => value,
9893 None => return,
9894 };
9895
9896 window.start_window_resize(edge);
9897 }),
9898 })
9899 .size_full()
9900 .child(
9901 div()
9902 .cursor(CursorStyle::Arrow)
9903 .map(|div| match decorations {
9904 Decorations::Server => div,
9905 Decorations::Client { .. } => div
9906 .border_color(cx.theme().colors().border)
9907 .when(
9908 !(tiling.top
9909 || tiling.right
9910 || border_radius_tiling.top
9911 || border_radius_tiling.right),
9912 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9913 )
9914 .when(
9915 !(tiling.top
9916 || tiling.left
9917 || border_radius_tiling.top
9918 || border_radius_tiling.left),
9919 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9920 )
9921 .when(
9922 !(tiling.bottom
9923 || tiling.right
9924 || border_radius_tiling.bottom
9925 || border_radius_tiling.right),
9926 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9927 )
9928 .when(
9929 !(tiling.bottom
9930 || tiling.left
9931 || border_radius_tiling.bottom
9932 || border_radius_tiling.left),
9933 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9934 )
9935 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
9936 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
9937 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
9938 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
9939 .when(!tiling.is_tiled(), |div| {
9940 div.shadow(vec![gpui::BoxShadow {
9941 color: Hsla {
9942 h: 0.,
9943 s: 0.,
9944 l: 0.,
9945 a: 0.4,
9946 },
9947 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
9948 spread_radius: px(0.),
9949 offset: point(px(0.0), px(0.0)),
9950 }])
9951 }),
9952 })
9953 .on_mouse_move(|_e, _, cx| {
9954 cx.stop_propagation();
9955 })
9956 .size_full()
9957 .child(element),
9958 )
9959 .map(|div| match decorations {
9960 Decorations::Server => div,
9961 Decorations::Client { tiling, .. } => div.child(
9962 canvas(
9963 |_bounds, window, _| {
9964 window.insert_hitbox(
9965 Bounds::new(
9966 point(px(0.0), px(0.0)),
9967 window.window_bounds().get_bounds().size,
9968 ),
9969 HitboxBehavior::Normal,
9970 )
9971 },
9972 move |_bounds, hitbox, window, cx| {
9973 let mouse = window.mouse_position();
9974 let size = window.window_bounds().get_bounds().size;
9975 let Some(edge) =
9976 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
9977 else {
9978 return;
9979 };
9980 cx.set_global(GlobalResizeEdge(edge));
9981 window.set_cursor_style(
9982 match edge {
9983 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
9984 ResizeEdge::Left | ResizeEdge::Right => {
9985 CursorStyle::ResizeLeftRight
9986 }
9987 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
9988 CursorStyle::ResizeUpLeftDownRight
9989 }
9990 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
9991 CursorStyle::ResizeUpRightDownLeft
9992 }
9993 },
9994 &hitbox,
9995 );
9996 },
9997 )
9998 .size_full()
9999 .absolute(),
10000 ),
10001 })
10002}
10003
10004fn resize_edge(
10005 pos: Point<Pixels>,
10006 shadow_size: Pixels,
10007 window_size: Size<Pixels>,
10008 tiling: Tiling,
10009) -> Option<ResizeEdge> {
10010 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10011 if bounds.contains(&pos) {
10012 return None;
10013 }
10014
10015 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10016 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10017 if !tiling.top && top_left_bounds.contains(&pos) {
10018 return Some(ResizeEdge::TopLeft);
10019 }
10020
10021 let top_right_bounds = Bounds::new(
10022 Point::new(window_size.width - corner_size.width, px(0.)),
10023 corner_size,
10024 );
10025 if !tiling.top && top_right_bounds.contains(&pos) {
10026 return Some(ResizeEdge::TopRight);
10027 }
10028
10029 let bottom_left_bounds = Bounds::new(
10030 Point::new(px(0.), window_size.height - corner_size.height),
10031 corner_size,
10032 );
10033 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10034 return Some(ResizeEdge::BottomLeft);
10035 }
10036
10037 let bottom_right_bounds = Bounds::new(
10038 Point::new(
10039 window_size.width - corner_size.width,
10040 window_size.height - corner_size.height,
10041 ),
10042 corner_size,
10043 );
10044 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10045 return Some(ResizeEdge::BottomRight);
10046 }
10047
10048 if !tiling.top && pos.y < shadow_size {
10049 Some(ResizeEdge::Top)
10050 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10051 Some(ResizeEdge::Bottom)
10052 } else if !tiling.left && pos.x < shadow_size {
10053 Some(ResizeEdge::Left)
10054 } else if !tiling.right && pos.x > window_size.width - shadow_size {
10055 Some(ResizeEdge::Right)
10056 } else {
10057 None
10058 }
10059}
10060
10061fn join_pane_into_active(
10062 active_pane: &Entity<Pane>,
10063 pane: &Entity<Pane>,
10064 window: &mut Window,
10065 cx: &mut App,
10066) {
10067 if pane == active_pane {
10068 } else if pane.read(cx).items_len() == 0 {
10069 pane.update(cx, |_, cx| {
10070 cx.emit(pane::Event::Remove {
10071 focus_on_pane: None,
10072 });
10073 })
10074 } else {
10075 move_all_items(pane, active_pane, window, cx);
10076 }
10077}
10078
10079fn move_all_items(
10080 from_pane: &Entity<Pane>,
10081 to_pane: &Entity<Pane>,
10082 window: &mut Window,
10083 cx: &mut App,
10084) {
10085 let destination_is_different = from_pane != to_pane;
10086 let mut moved_items = 0;
10087 for (item_ix, item_handle) in from_pane
10088 .read(cx)
10089 .items()
10090 .enumerate()
10091 .map(|(ix, item)| (ix, item.clone()))
10092 .collect::<Vec<_>>()
10093 {
10094 let ix = item_ix - moved_items;
10095 if destination_is_different {
10096 // Close item from previous pane
10097 from_pane.update(cx, |source, cx| {
10098 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10099 });
10100 moved_items += 1;
10101 }
10102
10103 // This automatically removes duplicate items in the pane
10104 to_pane.update(cx, |destination, cx| {
10105 destination.add_item(item_handle, true, true, None, window, cx);
10106 window.focus(&destination.focus_handle(cx), cx)
10107 });
10108 }
10109}
10110
10111pub fn move_item(
10112 source: &Entity<Pane>,
10113 destination: &Entity<Pane>,
10114 item_id_to_move: EntityId,
10115 destination_index: usize,
10116 activate: bool,
10117 window: &mut Window,
10118 cx: &mut App,
10119) {
10120 let Some((item_ix, item_handle)) = source
10121 .read(cx)
10122 .items()
10123 .enumerate()
10124 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10125 .map(|(ix, item)| (ix, item.clone()))
10126 else {
10127 // Tab was closed during drag
10128 return;
10129 };
10130
10131 if source != destination {
10132 // Close item from previous pane
10133 source.update(cx, |source, cx| {
10134 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10135 });
10136 }
10137
10138 // This automatically removes duplicate items in the pane
10139 destination.update(cx, |destination, cx| {
10140 destination.add_item_inner(
10141 item_handle,
10142 activate,
10143 activate,
10144 activate,
10145 Some(destination_index),
10146 window,
10147 cx,
10148 );
10149 if activate {
10150 window.focus(&destination.focus_handle(cx), cx)
10151 }
10152 });
10153}
10154
10155pub fn move_active_item(
10156 source: &Entity<Pane>,
10157 destination: &Entity<Pane>,
10158 focus_destination: bool,
10159 close_if_empty: bool,
10160 window: &mut Window,
10161 cx: &mut App,
10162) {
10163 if source == destination {
10164 return;
10165 }
10166 let Some(active_item) = source.read(cx).active_item() else {
10167 return;
10168 };
10169 source.update(cx, |source_pane, cx| {
10170 let item_id = active_item.item_id();
10171 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10172 destination.update(cx, |target_pane, cx| {
10173 target_pane.add_item(
10174 active_item,
10175 focus_destination,
10176 focus_destination,
10177 Some(target_pane.items_len()),
10178 window,
10179 cx,
10180 );
10181 });
10182 });
10183}
10184
10185pub fn clone_active_item(
10186 workspace_id: Option<WorkspaceId>,
10187 source: &Entity<Pane>,
10188 destination: &Entity<Pane>,
10189 focus_destination: bool,
10190 window: &mut Window,
10191 cx: &mut App,
10192) {
10193 if source == destination {
10194 return;
10195 }
10196 let Some(active_item) = source.read(cx).active_item() else {
10197 return;
10198 };
10199 if !active_item.can_split(cx) {
10200 return;
10201 }
10202 let destination = destination.downgrade();
10203 let task = active_item.clone_on_split(workspace_id, window, cx);
10204 window
10205 .spawn(cx, async move |cx| {
10206 let Some(clone) = task.await else {
10207 return;
10208 };
10209 destination
10210 .update_in(cx, |target_pane, window, cx| {
10211 target_pane.add_item(
10212 clone,
10213 focus_destination,
10214 focus_destination,
10215 Some(target_pane.items_len()),
10216 window,
10217 cx,
10218 );
10219 })
10220 .log_err();
10221 })
10222 .detach();
10223}
10224
10225#[derive(Debug)]
10226pub struct WorkspacePosition {
10227 pub window_bounds: Option<WindowBounds>,
10228 pub display: Option<Uuid>,
10229 pub centered_layout: bool,
10230}
10231
10232pub fn remote_workspace_position_from_db(
10233 connection_options: RemoteConnectionOptions,
10234 paths_to_open: &[PathBuf],
10235 cx: &App,
10236) -> Task<Result<WorkspacePosition>> {
10237 let paths = paths_to_open.to_vec();
10238
10239 cx.background_spawn(async move {
10240 let remote_connection_id = persistence::DB
10241 .get_or_create_remote_connection(connection_options)
10242 .await
10243 .context("fetching serialized ssh project")?;
10244 let serialized_workspace =
10245 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
10246
10247 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10248 (Some(WindowBounds::Windowed(bounds)), None)
10249 } else {
10250 let restorable_bounds = serialized_workspace
10251 .as_ref()
10252 .and_then(|workspace| {
10253 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10254 })
10255 .or_else(|| persistence::read_default_window_bounds());
10256
10257 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10258 (Some(serialized_bounds), Some(serialized_display))
10259 } else {
10260 (None, None)
10261 }
10262 };
10263
10264 let centered_layout = serialized_workspace
10265 .as_ref()
10266 .map(|w| w.centered_layout)
10267 .unwrap_or(false);
10268
10269 Ok(WorkspacePosition {
10270 window_bounds,
10271 display,
10272 centered_layout,
10273 })
10274 })
10275}
10276
10277pub fn with_active_or_new_workspace(
10278 cx: &mut App,
10279 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10280) {
10281 match cx
10282 .active_window()
10283 .and_then(|w| w.downcast::<MultiWorkspace>())
10284 {
10285 Some(multi_workspace) => {
10286 cx.defer(move |cx| {
10287 multi_workspace
10288 .update(cx, |multi_workspace, window, cx| {
10289 let workspace = multi_workspace.workspace().clone();
10290 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10291 })
10292 .log_err();
10293 });
10294 }
10295 None => {
10296 let app_state = AppState::global(cx);
10297 if let Some(app_state) = app_state.upgrade() {
10298 open_new(
10299 OpenOptions::default(),
10300 app_state,
10301 cx,
10302 move |workspace, window, cx| f(workspace, window, cx),
10303 )
10304 .detach_and_log_err(cx);
10305 }
10306 }
10307 }
10308}
10309
10310#[cfg(test)]
10311mod tests {
10312 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10313
10314 use super::*;
10315 use crate::{
10316 dock::{PanelEvent, test::TestPanel},
10317 item::{
10318 ItemBufferKind, ItemEvent,
10319 test::{TestItem, TestProjectItem},
10320 },
10321 };
10322 use fs::FakeFs;
10323 use gpui::{
10324 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10325 UpdateGlobal, VisualTestContext, px,
10326 };
10327 use project::{Project, ProjectEntryId};
10328 use serde_json::json;
10329 use settings::SettingsStore;
10330 use util::path;
10331 use util::rel_path::rel_path;
10332
10333 #[gpui::test]
10334 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10335 init_test(cx);
10336
10337 let fs = FakeFs::new(cx.executor());
10338 let project = Project::test(fs, [], cx).await;
10339 let (workspace, cx) =
10340 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10341
10342 // Adding an item with no ambiguity renders the tab without detail.
10343 let item1 = cx.new(|cx| {
10344 let mut item = TestItem::new(cx);
10345 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10346 item
10347 });
10348 workspace.update_in(cx, |workspace, window, cx| {
10349 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10350 });
10351 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10352
10353 // Adding an item that creates ambiguity increases the level of detail on
10354 // both tabs.
10355 let item2 = cx.new_window_entity(|_window, cx| {
10356 let mut item = TestItem::new(cx);
10357 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10358 item
10359 });
10360 workspace.update_in(cx, |workspace, window, cx| {
10361 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10362 });
10363 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10364 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10365
10366 // Adding an item that creates ambiguity increases the level of detail only
10367 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10368 // we stop at the highest detail available.
10369 let item3 = cx.new(|cx| {
10370 let mut item = TestItem::new(cx);
10371 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10372 item
10373 });
10374 workspace.update_in(cx, |workspace, window, cx| {
10375 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10376 });
10377 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10378 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10379 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10380 }
10381
10382 #[gpui::test]
10383 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10384 init_test(cx);
10385
10386 let fs = FakeFs::new(cx.executor());
10387 fs.insert_tree(
10388 "/root1",
10389 json!({
10390 "one.txt": "",
10391 "two.txt": "",
10392 }),
10393 )
10394 .await;
10395 fs.insert_tree(
10396 "/root2",
10397 json!({
10398 "three.txt": "",
10399 }),
10400 )
10401 .await;
10402
10403 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10404 let (workspace, cx) =
10405 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10406 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10407 let worktree_id = project.update(cx, |project, cx| {
10408 project.worktrees(cx).next().unwrap().read(cx).id()
10409 });
10410
10411 let item1 = cx.new(|cx| {
10412 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10413 });
10414 let item2 = cx.new(|cx| {
10415 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10416 });
10417
10418 // Add an item to an empty pane
10419 workspace.update_in(cx, |workspace, window, cx| {
10420 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10421 });
10422 project.update(cx, |project, cx| {
10423 assert_eq!(
10424 project.active_entry(),
10425 project
10426 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10427 .map(|e| e.id)
10428 );
10429 });
10430 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10431
10432 // Add a second item to a non-empty pane
10433 workspace.update_in(cx, |workspace, window, cx| {
10434 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10435 });
10436 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10437 project.update(cx, |project, cx| {
10438 assert_eq!(
10439 project.active_entry(),
10440 project
10441 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10442 .map(|e| e.id)
10443 );
10444 });
10445
10446 // Close the active item
10447 pane.update_in(cx, |pane, window, cx| {
10448 pane.close_active_item(&Default::default(), window, cx)
10449 })
10450 .await
10451 .unwrap();
10452 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10453 project.update(cx, |project, cx| {
10454 assert_eq!(
10455 project.active_entry(),
10456 project
10457 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10458 .map(|e| e.id)
10459 );
10460 });
10461
10462 // Add a project folder
10463 project
10464 .update(cx, |project, cx| {
10465 project.find_or_create_worktree("root2", true, cx)
10466 })
10467 .await
10468 .unwrap();
10469 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10470
10471 // Remove a project folder
10472 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10473 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10474 }
10475
10476 #[gpui::test]
10477 async fn test_close_window(cx: &mut TestAppContext) {
10478 init_test(cx);
10479
10480 let fs = FakeFs::new(cx.executor());
10481 fs.insert_tree("/root", json!({ "one": "" })).await;
10482
10483 let project = Project::test(fs, ["root".as_ref()], cx).await;
10484 let (workspace, cx) =
10485 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10486
10487 // When there are no dirty items, there's nothing to do.
10488 let item1 = cx.new(TestItem::new);
10489 workspace.update_in(cx, |w, window, cx| {
10490 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10491 });
10492 let task = workspace.update_in(cx, |w, window, cx| {
10493 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10494 });
10495 assert!(task.await.unwrap());
10496
10497 // When there are dirty untitled items, prompt to save each one. If the user
10498 // cancels any prompt, then abort.
10499 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10500 let item3 = cx.new(|cx| {
10501 TestItem::new(cx)
10502 .with_dirty(true)
10503 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10504 });
10505 workspace.update_in(cx, |w, window, cx| {
10506 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10507 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10508 });
10509 let task = workspace.update_in(cx, |w, window, cx| {
10510 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10511 });
10512 cx.executor().run_until_parked();
10513 cx.simulate_prompt_answer("Cancel"); // cancel save all
10514 cx.executor().run_until_parked();
10515 assert!(!cx.has_pending_prompt());
10516 assert!(!task.await.unwrap());
10517 }
10518
10519 #[gpui::test]
10520 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10521 init_test(cx);
10522
10523 let fs = FakeFs::new(cx.executor());
10524 fs.insert_tree("/root", json!({ "one": "" })).await;
10525
10526 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10527 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10528 let multi_workspace_handle =
10529 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10530 cx.run_until_parked();
10531
10532 let workspace_a = multi_workspace_handle
10533 .read_with(cx, |mw, _| mw.workspace().clone())
10534 .unwrap();
10535
10536 let workspace_b = multi_workspace_handle
10537 .update(cx, |mw, window, cx| {
10538 mw.test_add_workspace(project_b, window, cx)
10539 })
10540 .unwrap();
10541
10542 // Activate workspace A
10543 multi_workspace_handle
10544 .update(cx, |mw, window, cx| {
10545 mw.activate_index(0, window, cx);
10546 })
10547 .unwrap();
10548
10549 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10550
10551 // Workspace A has a clean item
10552 let item_a = cx.new(TestItem::new);
10553 workspace_a.update_in(cx, |w, window, cx| {
10554 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10555 });
10556
10557 // Workspace B has a dirty item
10558 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10559 workspace_b.update_in(cx, |w, window, cx| {
10560 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10561 });
10562
10563 // Verify workspace A is active
10564 multi_workspace_handle
10565 .read_with(cx, |mw, _| {
10566 assert_eq!(mw.active_workspace_index(), 0);
10567 })
10568 .unwrap();
10569
10570 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10571 multi_workspace_handle
10572 .update(cx, |mw, window, cx| {
10573 mw.close_window(&CloseWindow, window, cx);
10574 })
10575 .unwrap();
10576 cx.run_until_parked();
10577
10578 // Workspace B should now be active since it has dirty items that need attention
10579 multi_workspace_handle
10580 .read_with(cx, |mw, _| {
10581 assert_eq!(
10582 mw.active_workspace_index(),
10583 1,
10584 "workspace B should be activated when it prompts"
10585 );
10586 })
10587 .unwrap();
10588
10589 // User cancels the save prompt from workspace B
10590 cx.simulate_prompt_answer("Cancel");
10591 cx.run_until_parked();
10592
10593 // Window should still exist because workspace B's close was cancelled
10594 assert!(
10595 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10596 "window should still exist after cancelling one workspace's close"
10597 );
10598 }
10599
10600 #[gpui::test]
10601 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10602 init_test(cx);
10603
10604 // Register TestItem as a serializable item
10605 cx.update(|cx| {
10606 register_serializable_item::<TestItem>(cx);
10607 });
10608
10609 let fs = FakeFs::new(cx.executor());
10610 fs.insert_tree("/root", json!({ "one": "" })).await;
10611
10612 let project = Project::test(fs, ["root".as_ref()], cx).await;
10613 let (workspace, cx) =
10614 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10615
10616 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10617 let item1 = cx.new(|cx| {
10618 TestItem::new(cx)
10619 .with_dirty(true)
10620 .with_serialize(|| Some(Task::ready(Ok(()))))
10621 });
10622 let item2 = cx.new(|cx| {
10623 TestItem::new(cx)
10624 .with_dirty(true)
10625 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10626 .with_serialize(|| Some(Task::ready(Ok(()))))
10627 });
10628 workspace.update_in(cx, |w, window, cx| {
10629 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10630 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10631 });
10632 let task = workspace.update_in(cx, |w, window, cx| {
10633 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10634 });
10635 assert!(task.await.unwrap());
10636 }
10637
10638 #[gpui::test]
10639 async fn test_close_pane_items(cx: &mut TestAppContext) {
10640 init_test(cx);
10641
10642 let fs = FakeFs::new(cx.executor());
10643
10644 let project = Project::test(fs, None, cx).await;
10645 let (workspace, cx) =
10646 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10647
10648 let item1 = cx.new(|cx| {
10649 TestItem::new(cx)
10650 .with_dirty(true)
10651 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10652 });
10653 let item2 = cx.new(|cx| {
10654 TestItem::new(cx)
10655 .with_dirty(true)
10656 .with_conflict(true)
10657 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10658 });
10659 let item3 = cx.new(|cx| {
10660 TestItem::new(cx)
10661 .with_dirty(true)
10662 .with_conflict(true)
10663 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10664 });
10665 let item4 = cx.new(|cx| {
10666 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10667 let project_item = TestProjectItem::new_untitled(cx);
10668 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10669 project_item
10670 }])
10671 });
10672 let pane = workspace.update_in(cx, |workspace, window, cx| {
10673 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10674 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10675 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10676 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10677 workspace.active_pane().clone()
10678 });
10679
10680 let close_items = pane.update_in(cx, |pane, window, cx| {
10681 pane.activate_item(1, true, true, window, cx);
10682 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10683 let item1_id = item1.item_id();
10684 let item3_id = item3.item_id();
10685 let item4_id = item4.item_id();
10686 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10687 [item1_id, item3_id, item4_id].contains(&id)
10688 })
10689 });
10690 cx.executor().run_until_parked();
10691
10692 assert!(cx.has_pending_prompt());
10693 cx.simulate_prompt_answer("Save all");
10694
10695 cx.executor().run_until_parked();
10696
10697 // Item 1 is saved. There's a prompt to save item 3.
10698 pane.update(cx, |pane, cx| {
10699 assert_eq!(item1.read(cx).save_count, 1);
10700 assert_eq!(item1.read(cx).save_as_count, 0);
10701 assert_eq!(item1.read(cx).reload_count, 0);
10702 assert_eq!(pane.items_len(), 3);
10703 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10704 });
10705 assert!(cx.has_pending_prompt());
10706
10707 // Cancel saving item 3.
10708 cx.simulate_prompt_answer("Discard");
10709 cx.executor().run_until_parked();
10710
10711 // Item 3 is reloaded. There's a prompt to save item 4.
10712 pane.update(cx, |pane, cx| {
10713 assert_eq!(item3.read(cx).save_count, 0);
10714 assert_eq!(item3.read(cx).save_as_count, 0);
10715 assert_eq!(item3.read(cx).reload_count, 1);
10716 assert_eq!(pane.items_len(), 2);
10717 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10718 });
10719
10720 // There's a prompt for a path for item 4.
10721 cx.simulate_new_path_selection(|_| Some(Default::default()));
10722 close_items.await.unwrap();
10723
10724 // The requested items are closed.
10725 pane.update(cx, |pane, cx| {
10726 assert_eq!(item4.read(cx).save_count, 0);
10727 assert_eq!(item4.read(cx).save_as_count, 1);
10728 assert_eq!(item4.read(cx).reload_count, 0);
10729 assert_eq!(pane.items_len(), 1);
10730 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10731 });
10732 }
10733
10734 #[gpui::test]
10735 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10736 init_test(cx);
10737
10738 let fs = FakeFs::new(cx.executor());
10739 let project = Project::test(fs, [], cx).await;
10740 let (workspace, cx) =
10741 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10742
10743 // Create several workspace items with single project entries, and two
10744 // workspace items with multiple project entries.
10745 let single_entry_items = (0..=4)
10746 .map(|project_entry_id| {
10747 cx.new(|cx| {
10748 TestItem::new(cx)
10749 .with_dirty(true)
10750 .with_project_items(&[dirty_project_item(
10751 project_entry_id,
10752 &format!("{project_entry_id}.txt"),
10753 cx,
10754 )])
10755 })
10756 })
10757 .collect::<Vec<_>>();
10758 let item_2_3 = cx.new(|cx| {
10759 TestItem::new(cx)
10760 .with_dirty(true)
10761 .with_buffer_kind(ItemBufferKind::Multibuffer)
10762 .with_project_items(&[
10763 single_entry_items[2].read(cx).project_items[0].clone(),
10764 single_entry_items[3].read(cx).project_items[0].clone(),
10765 ])
10766 });
10767 let item_3_4 = cx.new(|cx| {
10768 TestItem::new(cx)
10769 .with_dirty(true)
10770 .with_buffer_kind(ItemBufferKind::Multibuffer)
10771 .with_project_items(&[
10772 single_entry_items[3].read(cx).project_items[0].clone(),
10773 single_entry_items[4].read(cx).project_items[0].clone(),
10774 ])
10775 });
10776
10777 // Create two panes that contain the following project entries:
10778 // left pane:
10779 // multi-entry items: (2, 3)
10780 // single-entry items: 0, 2, 3, 4
10781 // right pane:
10782 // single-entry items: 4, 1
10783 // multi-entry items: (3, 4)
10784 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10785 let left_pane = workspace.active_pane().clone();
10786 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10787 workspace.add_item_to_active_pane(
10788 single_entry_items[0].boxed_clone(),
10789 None,
10790 true,
10791 window,
10792 cx,
10793 );
10794 workspace.add_item_to_active_pane(
10795 single_entry_items[2].boxed_clone(),
10796 None,
10797 true,
10798 window,
10799 cx,
10800 );
10801 workspace.add_item_to_active_pane(
10802 single_entry_items[3].boxed_clone(),
10803 None,
10804 true,
10805 window,
10806 cx,
10807 );
10808 workspace.add_item_to_active_pane(
10809 single_entry_items[4].boxed_clone(),
10810 None,
10811 true,
10812 window,
10813 cx,
10814 );
10815
10816 let right_pane =
10817 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10818
10819 let boxed_clone = single_entry_items[1].boxed_clone();
10820 let right_pane = window.spawn(cx, async move |cx| {
10821 right_pane.await.inspect(|right_pane| {
10822 right_pane
10823 .update_in(cx, |pane, window, cx| {
10824 pane.add_item(boxed_clone, true, true, None, window, cx);
10825 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10826 })
10827 .unwrap();
10828 })
10829 });
10830
10831 (left_pane, right_pane)
10832 });
10833 let right_pane = right_pane.await.unwrap();
10834 cx.focus(&right_pane);
10835
10836 let close = right_pane.update_in(cx, |pane, window, cx| {
10837 pane.close_all_items(&CloseAllItems::default(), window, cx)
10838 .unwrap()
10839 });
10840 cx.executor().run_until_parked();
10841
10842 let msg = cx.pending_prompt().unwrap().0;
10843 assert!(msg.contains("1.txt"));
10844 assert!(!msg.contains("2.txt"));
10845 assert!(!msg.contains("3.txt"));
10846 assert!(!msg.contains("4.txt"));
10847
10848 // With best-effort close, cancelling item 1 keeps it open but items 4
10849 // and (3,4) still close since their entries exist in left pane.
10850 cx.simulate_prompt_answer("Cancel");
10851 close.await;
10852
10853 right_pane.read_with(cx, |pane, _| {
10854 assert_eq!(pane.items_len(), 1);
10855 });
10856
10857 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10858 left_pane
10859 .update_in(cx, |left_pane, window, cx| {
10860 left_pane.close_item_by_id(
10861 single_entry_items[3].entity_id(),
10862 SaveIntent::Skip,
10863 window,
10864 cx,
10865 )
10866 })
10867 .await
10868 .unwrap();
10869
10870 let close = left_pane.update_in(cx, |pane, window, cx| {
10871 pane.close_all_items(&CloseAllItems::default(), window, cx)
10872 .unwrap()
10873 });
10874 cx.executor().run_until_parked();
10875
10876 let details = cx.pending_prompt().unwrap().1;
10877 assert!(details.contains("0.txt"));
10878 assert!(details.contains("3.txt"));
10879 assert!(details.contains("4.txt"));
10880 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10881 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10882 // assert!(!details.contains("2.txt"));
10883
10884 cx.simulate_prompt_answer("Save all");
10885 cx.executor().run_until_parked();
10886 close.await;
10887
10888 left_pane.read_with(cx, |pane, _| {
10889 assert_eq!(pane.items_len(), 0);
10890 });
10891 }
10892
10893 #[gpui::test]
10894 async fn test_autosave(cx: &mut gpui::TestAppContext) {
10895 init_test(cx);
10896
10897 let fs = FakeFs::new(cx.executor());
10898 let project = Project::test(fs, [], cx).await;
10899 let (workspace, cx) =
10900 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10901 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10902
10903 let item = cx.new(|cx| {
10904 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10905 });
10906 let item_id = item.entity_id();
10907 workspace.update_in(cx, |workspace, window, cx| {
10908 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10909 });
10910
10911 // Autosave on window change.
10912 item.update(cx, |item, cx| {
10913 SettingsStore::update_global(cx, |settings, cx| {
10914 settings.update_user_settings(cx, |settings| {
10915 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10916 })
10917 });
10918 item.is_dirty = true;
10919 });
10920
10921 // Deactivating the window saves the file.
10922 cx.deactivate_window();
10923 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10924
10925 // Re-activating the window doesn't save the file.
10926 cx.update(|window, _| window.activate_window());
10927 cx.executor().run_until_parked();
10928 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10929
10930 // Autosave on focus change.
10931 item.update_in(cx, |item, window, cx| {
10932 cx.focus_self(window);
10933 SettingsStore::update_global(cx, |settings, cx| {
10934 settings.update_user_settings(cx, |settings| {
10935 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10936 })
10937 });
10938 item.is_dirty = true;
10939 });
10940 // Blurring the item saves the file.
10941 item.update_in(cx, |_, window, _| window.blur());
10942 cx.executor().run_until_parked();
10943 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10944
10945 // Deactivating the window still saves the file.
10946 item.update_in(cx, |item, window, cx| {
10947 cx.focus_self(window);
10948 item.is_dirty = true;
10949 });
10950 cx.deactivate_window();
10951 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10952
10953 // Autosave after delay.
10954 item.update(cx, |item, cx| {
10955 SettingsStore::update_global(cx, |settings, cx| {
10956 settings.update_user_settings(cx, |settings| {
10957 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10958 milliseconds: 500.into(),
10959 });
10960 })
10961 });
10962 item.is_dirty = true;
10963 cx.emit(ItemEvent::Edit);
10964 });
10965
10966 // Delay hasn't fully expired, so the file is still dirty and unsaved.
10967 cx.executor().advance_clock(Duration::from_millis(250));
10968 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10969
10970 // After delay expires, the file is saved.
10971 cx.executor().advance_clock(Duration::from_millis(250));
10972 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10973
10974 // Autosave after delay, should save earlier than delay if tab is closed
10975 item.update(cx, |item, cx| {
10976 item.is_dirty = true;
10977 cx.emit(ItemEvent::Edit);
10978 });
10979 cx.executor().advance_clock(Duration::from_millis(250));
10980 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10981
10982 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10983 pane.update_in(cx, |pane, window, cx| {
10984 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10985 })
10986 .await
10987 .unwrap();
10988 assert!(!cx.has_pending_prompt());
10989 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10990
10991 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10992 workspace.update_in(cx, |workspace, window, cx| {
10993 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10994 });
10995 item.update_in(cx, |item, _window, cx| {
10996 item.is_dirty = true;
10997 for project_item in &mut item.project_items {
10998 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10999 }
11000 });
11001 cx.run_until_parked();
11002 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11003
11004 // Autosave on focus change, ensuring closing the tab counts as such.
11005 item.update(cx, |item, cx| {
11006 SettingsStore::update_global(cx, |settings, cx| {
11007 settings.update_user_settings(cx, |settings| {
11008 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11009 })
11010 });
11011 item.is_dirty = true;
11012 for project_item in &mut item.project_items {
11013 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11014 }
11015 });
11016
11017 pane.update_in(cx, |pane, window, cx| {
11018 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11019 })
11020 .await
11021 .unwrap();
11022 assert!(!cx.has_pending_prompt());
11023 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11024
11025 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11026 workspace.update_in(cx, |workspace, window, cx| {
11027 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11028 });
11029 item.update_in(cx, |item, window, cx| {
11030 item.project_items[0].update(cx, |item, _| {
11031 item.entry_id = None;
11032 });
11033 item.is_dirty = true;
11034 window.blur();
11035 });
11036 cx.run_until_parked();
11037 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11038
11039 // Ensure autosave is prevented for deleted files also when closing the buffer.
11040 let _close_items = pane.update_in(cx, |pane, window, cx| {
11041 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11042 });
11043 cx.run_until_parked();
11044 assert!(cx.has_pending_prompt());
11045 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11046 }
11047
11048 #[gpui::test]
11049 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11050 init_test(cx);
11051
11052 let fs = FakeFs::new(cx.executor());
11053 let project = Project::test(fs, [], cx).await;
11054 let (workspace, cx) =
11055 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11056
11057 // Create a multibuffer-like item with two child focus handles,
11058 // simulating individual buffer editors within a multibuffer.
11059 let item = cx.new(|cx| {
11060 TestItem::new(cx)
11061 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11062 .with_child_focus_handles(2, cx)
11063 });
11064 workspace.update_in(cx, |workspace, window, cx| {
11065 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11066 });
11067
11068 // Set autosave to OnFocusChange and focus the first child handle,
11069 // simulating the user's cursor being inside one of the multibuffer's excerpts.
11070 item.update_in(cx, |item, window, cx| {
11071 SettingsStore::update_global(cx, |settings, cx| {
11072 settings.update_user_settings(cx, |settings| {
11073 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11074 })
11075 });
11076 item.is_dirty = true;
11077 window.focus(&item.child_focus_handles[0], cx);
11078 });
11079 cx.executor().run_until_parked();
11080 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11081
11082 // Moving focus from one child to another within the same item should
11083 // NOT trigger autosave — focus is still within the item's focus hierarchy.
11084 item.update_in(cx, |item, window, cx| {
11085 window.focus(&item.child_focus_handles[1], cx);
11086 });
11087 cx.executor().run_until_parked();
11088 item.read_with(cx, |item, _| {
11089 assert_eq!(
11090 item.save_count, 0,
11091 "Switching focus between children within the same item should not autosave"
11092 );
11093 });
11094
11095 // Blurring the item saves the file. This is the core regression scenario:
11096 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11097 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11098 // the leaf is always a child focus handle, so `on_blur` never detected
11099 // focus leaving the item.
11100 item.update_in(cx, |_, window, _| window.blur());
11101 cx.executor().run_until_parked();
11102 item.read_with(cx, |item, _| {
11103 assert_eq!(
11104 item.save_count, 1,
11105 "Blurring should trigger autosave when focus was on a child of the item"
11106 );
11107 });
11108
11109 // Deactivating the window should also trigger autosave when a child of
11110 // the multibuffer item currently owns focus.
11111 item.update_in(cx, |item, window, cx| {
11112 item.is_dirty = true;
11113 window.focus(&item.child_focus_handles[0], cx);
11114 });
11115 cx.executor().run_until_parked();
11116 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11117
11118 cx.deactivate_window();
11119 item.read_with(cx, |item, _| {
11120 assert_eq!(
11121 item.save_count, 2,
11122 "Deactivating window should trigger autosave when focus was on a child"
11123 );
11124 });
11125 }
11126
11127 #[gpui::test]
11128 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11129 init_test(cx);
11130
11131 let fs = FakeFs::new(cx.executor());
11132
11133 let project = Project::test(fs, [], cx).await;
11134 let (workspace, cx) =
11135 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11136
11137 let item = cx.new(|cx| {
11138 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11139 });
11140 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11141 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11142 let toolbar_notify_count = Rc::new(RefCell::new(0));
11143
11144 workspace.update_in(cx, |workspace, window, cx| {
11145 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11146 let toolbar_notification_count = toolbar_notify_count.clone();
11147 cx.observe_in(&toolbar, window, move |_, _, _, _| {
11148 *toolbar_notification_count.borrow_mut() += 1
11149 })
11150 .detach();
11151 });
11152
11153 pane.read_with(cx, |pane, _| {
11154 assert!(!pane.can_navigate_backward());
11155 assert!(!pane.can_navigate_forward());
11156 });
11157
11158 item.update_in(cx, |item, _, cx| {
11159 item.set_state("one".to_string(), cx);
11160 });
11161
11162 // Toolbar must be notified to re-render the navigation buttons
11163 assert_eq!(*toolbar_notify_count.borrow(), 1);
11164
11165 pane.read_with(cx, |pane, _| {
11166 assert!(pane.can_navigate_backward());
11167 assert!(!pane.can_navigate_forward());
11168 });
11169
11170 workspace
11171 .update_in(cx, |workspace, window, cx| {
11172 workspace.go_back(pane.downgrade(), window, cx)
11173 })
11174 .await
11175 .unwrap();
11176
11177 assert_eq!(*toolbar_notify_count.borrow(), 2);
11178 pane.read_with(cx, |pane, _| {
11179 assert!(!pane.can_navigate_backward());
11180 assert!(pane.can_navigate_forward());
11181 });
11182 }
11183
11184 #[gpui::test]
11185 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11186 init_test(cx);
11187 let fs = FakeFs::new(cx.executor());
11188 let project = Project::test(fs, [], cx).await;
11189 let (multi_workspace, cx) =
11190 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11191 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11192
11193 workspace.update_in(cx, |workspace, window, cx| {
11194 let first_item = cx.new(|cx| {
11195 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11196 });
11197 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11198 workspace.split_pane(
11199 workspace.active_pane().clone(),
11200 SplitDirection::Right,
11201 window,
11202 cx,
11203 );
11204 workspace.split_pane(
11205 workspace.active_pane().clone(),
11206 SplitDirection::Right,
11207 window,
11208 cx,
11209 );
11210 });
11211
11212 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11213 let panes = workspace.center.panes();
11214 assert!(panes.len() >= 2);
11215 (
11216 panes.first().expect("at least one pane").entity_id(),
11217 panes.last().expect("at least one pane").entity_id(),
11218 )
11219 });
11220
11221 workspace.update_in(cx, |workspace, window, cx| {
11222 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11223 });
11224 workspace.update(cx, |workspace, _| {
11225 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11226 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11227 });
11228
11229 cx.dispatch_action(ActivateLastPane);
11230
11231 workspace.update(cx, |workspace, _| {
11232 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11233 });
11234 }
11235
11236 #[gpui::test]
11237 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11238 init_test(cx);
11239 let fs = FakeFs::new(cx.executor());
11240
11241 let project = Project::test(fs, [], cx).await;
11242 let (workspace, cx) =
11243 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11244
11245 let panel = workspace.update_in(cx, |workspace, window, cx| {
11246 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11247 workspace.add_panel(panel.clone(), window, cx);
11248
11249 workspace
11250 .right_dock()
11251 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11252
11253 panel
11254 });
11255
11256 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11257 pane.update_in(cx, |pane, window, cx| {
11258 let item = cx.new(TestItem::new);
11259 pane.add_item(Box::new(item), true, true, None, window, cx);
11260 });
11261
11262 // Transfer focus from center to panel
11263 workspace.update_in(cx, |workspace, window, cx| {
11264 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11265 });
11266
11267 workspace.update_in(cx, |workspace, window, cx| {
11268 assert!(workspace.right_dock().read(cx).is_open());
11269 assert!(!panel.is_zoomed(window, cx));
11270 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11271 });
11272
11273 // Transfer focus from panel to center
11274 workspace.update_in(cx, |workspace, window, cx| {
11275 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11276 });
11277
11278 workspace.update_in(cx, |workspace, window, cx| {
11279 assert!(workspace.right_dock().read(cx).is_open());
11280 assert!(!panel.is_zoomed(window, cx));
11281 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11282 });
11283
11284 // Close the dock
11285 workspace.update_in(cx, |workspace, window, cx| {
11286 workspace.toggle_dock(DockPosition::Right, window, cx);
11287 });
11288
11289 workspace.update_in(cx, |workspace, window, cx| {
11290 assert!(!workspace.right_dock().read(cx).is_open());
11291 assert!(!panel.is_zoomed(window, cx));
11292 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11293 });
11294
11295 // Open the dock
11296 workspace.update_in(cx, |workspace, window, cx| {
11297 workspace.toggle_dock(DockPosition::Right, window, cx);
11298 });
11299
11300 workspace.update_in(cx, |workspace, window, cx| {
11301 assert!(workspace.right_dock().read(cx).is_open());
11302 assert!(!panel.is_zoomed(window, cx));
11303 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11304 });
11305
11306 // Focus and zoom panel
11307 panel.update_in(cx, |panel, window, cx| {
11308 cx.focus_self(window);
11309 panel.set_zoomed(true, window, cx)
11310 });
11311
11312 workspace.update_in(cx, |workspace, window, cx| {
11313 assert!(workspace.right_dock().read(cx).is_open());
11314 assert!(panel.is_zoomed(window, cx));
11315 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11316 });
11317
11318 // Transfer focus to the center closes the dock
11319 workspace.update_in(cx, |workspace, window, cx| {
11320 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11321 });
11322
11323 workspace.update_in(cx, |workspace, window, cx| {
11324 assert!(!workspace.right_dock().read(cx).is_open());
11325 assert!(panel.is_zoomed(window, cx));
11326 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11327 });
11328
11329 // Transferring focus back to the panel keeps it zoomed
11330 workspace.update_in(cx, |workspace, window, cx| {
11331 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11332 });
11333
11334 workspace.update_in(cx, |workspace, window, cx| {
11335 assert!(workspace.right_dock().read(cx).is_open());
11336 assert!(panel.is_zoomed(window, cx));
11337 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11338 });
11339
11340 // Close the dock while it is zoomed
11341 workspace.update_in(cx, |workspace, window, cx| {
11342 workspace.toggle_dock(DockPosition::Right, window, cx)
11343 });
11344
11345 workspace.update_in(cx, |workspace, window, cx| {
11346 assert!(!workspace.right_dock().read(cx).is_open());
11347 assert!(panel.is_zoomed(window, cx));
11348 assert!(workspace.zoomed.is_none());
11349 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11350 });
11351
11352 // Opening the dock, when it's zoomed, retains focus
11353 workspace.update_in(cx, |workspace, window, cx| {
11354 workspace.toggle_dock(DockPosition::Right, window, cx)
11355 });
11356
11357 workspace.update_in(cx, |workspace, window, cx| {
11358 assert!(workspace.right_dock().read(cx).is_open());
11359 assert!(panel.is_zoomed(window, cx));
11360 assert!(workspace.zoomed.is_some());
11361 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11362 });
11363
11364 // Unzoom and close the panel, zoom the active pane.
11365 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11366 workspace.update_in(cx, |workspace, window, cx| {
11367 workspace.toggle_dock(DockPosition::Right, window, cx)
11368 });
11369 pane.update_in(cx, |pane, window, cx| {
11370 pane.toggle_zoom(&Default::default(), window, cx)
11371 });
11372
11373 // Opening a dock unzooms the pane.
11374 workspace.update_in(cx, |workspace, window, cx| {
11375 workspace.toggle_dock(DockPosition::Right, window, cx)
11376 });
11377 workspace.update_in(cx, |workspace, window, cx| {
11378 let pane = pane.read(cx);
11379 assert!(!pane.is_zoomed());
11380 assert!(!pane.focus_handle(cx).is_focused(window));
11381 assert!(workspace.right_dock().read(cx).is_open());
11382 assert!(workspace.zoomed.is_none());
11383 });
11384 }
11385
11386 #[gpui::test]
11387 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11388 init_test(cx);
11389 let fs = FakeFs::new(cx.executor());
11390
11391 let project = Project::test(fs, [], cx).await;
11392 let (workspace, cx) =
11393 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11394
11395 let panel = workspace.update_in(cx, |workspace, window, cx| {
11396 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11397 workspace.add_panel(panel.clone(), window, cx);
11398 panel
11399 });
11400
11401 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11402 pane.update_in(cx, |pane, window, cx| {
11403 let item = cx.new(TestItem::new);
11404 pane.add_item(Box::new(item), true, true, None, window, cx);
11405 });
11406
11407 // Enable close_panel_on_toggle
11408 cx.update_global(|store: &mut SettingsStore, cx| {
11409 store.update_user_settings(cx, |settings| {
11410 settings.workspace.close_panel_on_toggle = Some(true);
11411 });
11412 });
11413
11414 // Panel starts closed. Toggling should open and focus it.
11415 workspace.update_in(cx, |workspace, window, cx| {
11416 assert!(!workspace.right_dock().read(cx).is_open());
11417 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11418 });
11419
11420 workspace.update_in(cx, |workspace, window, cx| {
11421 assert!(
11422 workspace.right_dock().read(cx).is_open(),
11423 "Dock should be open after toggling from center"
11424 );
11425 assert!(
11426 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11427 "Panel should be focused after toggling from center"
11428 );
11429 });
11430
11431 // Panel is open and focused. Toggling should close the panel and
11432 // return focus to the center.
11433 workspace.update_in(cx, |workspace, window, cx| {
11434 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11435 });
11436
11437 workspace.update_in(cx, |workspace, window, cx| {
11438 assert!(
11439 !workspace.right_dock().read(cx).is_open(),
11440 "Dock should be closed after toggling from focused panel"
11441 );
11442 assert!(
11443 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11444 "Panel should not be focused after toggling from focused panel"
11445 );
11446 });
11447
11448 // Open the dock and focus something else so the panel is open but not
11449 // focused. Toggling should focus the panel (not close it).
11450 workspace.update_in(cx, |workspace, window, cx| {
11451 workspace
11452 .right_dock()
11453 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11454 window.focus(&pane.read(cx).focus_handle(cx), cx);
11455 });
11456
11457 workspace.update_in(cx, |workspace, window, cx| {
11458 assert!(workspace.right_dock().read(cx).is_open());
11459 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11460 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11461 });
11462
11463 workspace.update_in(cx, |workspace, window, cx| {
11464 assert!(
11465 workspace.right_dock().read(cx).is_open(),
11466 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11467 );
11468 assert!(
11469 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11470 "Panel should be focused after toggling an open-but-unfocused panel"
11471 );
11472 });
11473
11474 // Now disable the setting and verify the original behavior: toggling
11475 // from a focused panel moves focus to center but leaves the dock open.
11476 cx.update_global(|store: &mut SettingsStore, cx| {
11477 store.update_user_settings(cx, |settings| {
11478 settings.workspace.close_panel_on_toggle = Some(false);
11479 });
11480 });
11481
11482 workspace.update_in(cx, |workspace, window, cx| {
11483 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11484 });
11485
11486 workspace.update_in(cx, |workspace, window, cx| {
11487 assert!(
11488 workspace.right_dock().read(cx).is_open(),
11489 "Dock should remain open when setting is disabled"
11490 );
11491 assert!(
11492 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11493 "Panel should not be focused after toggling with setting disabled"
11494 );
11495 });
11496 }
11497
11498 #[gpui::test]
11499 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11500 init_test(cx);
11501 let fs = FakeFs::new(cx.executor());
11502
11503 let project = Project::test(fs, [], cx).await;
11504 let (workspace, cx) =
11505 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11506
11507 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11508 workspace.active_pane().clone()
11509 });
11510
11511 // Add an item to the pane so it can be zoomed
11512 workspace.update_in(cx, |workspace, window, cx| {
11513 let item = cx.new(TestItem::new);
11514 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11515 });
11516
11517 // Initially not zoomed
11518 workspace.update_in(cx, |workspace, _window, cx| {
11519 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11520 assert!(
11521 workspace.zoomed.is_none(),
11522 "Workspace should track no zoomed pane"
11523 );
11524 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11525 });
11526
11527 // Zoom In
11528 pane.update_in(cx, |pane, window, cx| {
11529 pane.zoom_in(&crate::ZoomIn, window, cx);
11530 });
11531
11532 workspace.update_in(cx, |workspace, window, cx| {
11533 assert!(
11534 pane.read(cx).is_zoomed(),
11535 "Pane should be zoomed after ZoomIn"
11536 );
11537 assert!(
11538 workspace.zoomed.is_some(),
11539 "Workspace should track the zoomed pane"
11540 );
11541 assert!(
11542 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11543 "ZoomIn should focus the pane"
11544 );
11545 });
11546
11547 // Zoom In again is a no-op
11548 pane.update_in(cx, |pane, window, cx| {
11549 pane.zoom_in(&crate::ZoomIn, window, cx);
11550 });
11551
11552 workspace.update_in(cx, |workspace, window, cx| {
11553 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11554 assert!(
11555 workspace.zoomed.is_some(),
11556 "Workspace still tracks zoomed pane"
11557 );
11558 assert!(
11559 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11560 "Pane remains focused after repeated ZoomIn"
11561 );
11562 });
11563
11564 // Zoom Out
11565 pane.update_in(cx, |pane, window, cx| {
11566 pane.zoom_out(&crate::ZoomOut, window, cx);
11567 });
11568
11569 workspace.update_in(cx, |workspace, _window, cx| {
11570 assert!(
11571 !pane.read(cx).is_zoomed(),
11572 "Pane should unzoom after ZoomOut"
11573 );
11574 assert!(
11575 workspace.zoomed.is_none(),
11576 "Workspace clears zoom tracking after ZoomOut"
11577 );
11578 });
11579
11580 // Zoom Out again is a no-op
11581 pane.update_in(cx, |pane, window, cx| {
11582 pane.zoom_out(&crate::ZoomOut, window, cx);
11583 });
11584
11585 workspace.update_in(cx, |workspace, _window, cx| {
11586 assert!(
11587 !pane.read(cx).is_zoomed(),
11588 "Second ZoomOut keeps pane unzoomed"
11589 );
11590 assert!(
11591 workspace.zoomed.is_none(),
11592 "Workspace remains without zoomed pane"
11593 );
11594 });
11595 }
11596
11597 #[gpui::test]
11598 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11599 init_test(cx);
11600 let fs = FakeFs::new(cx.executor());
11601
11602 let project = Project::test(fs, [], cx).await;
11603 let (workspace, cx) =
11604 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11605 workspace.update_in(cx, |workspace, window, cx| {
11606 // Open two docks
11607 let left_dock = workspace.dock_at_position(DockPosition::Left);
11608 let right_dock = workspace.dock_at_position(DockPosition::Right);
11609
11610 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11611 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11612
11613 assert!(left_dock.read(cx).is_open());
11614 assert!(right_dock.read(cx).is_open());
11615 });
11616
11617 workspace.update_in(cx, |workspace, window, cx| {
11618 // Toggle all docks - should close both
11619 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11620
11621 let left_dock = workspace.dock_at_position(DockPosition::Left);
11622 let right_dock = workspace.dock_at_position(DockPosition::Right);
11623 assert!(!left_dock.read(cx).is_open());
11624 assert!(!right_dock.read(cx).is_open());
11625 });
11626
11627 workspace.update_in(cx, |workspace, window, cx| {
11628 // Toggle again - should reopen both
11629 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11630
11631 let left_dock = workspace.dock_at_position(DockPosition::Left);
11632 let right_dock = workspace.dock_at_position(DockPosition::Right);
11633 assert!(left_dock.read(cx).is_open());
11634 assert!(right_dock.read(cx).is_open());
11635 });
11636 }
11637
11638 #[gpui::test]
11639 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11640 init_test(cx);
11641 let fs = FakeFs::new(cx.executor());
11642
11643 let project = Project::test(fs, [], cx).await;
11644 let (workspace, cx) =
11645 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11646 workspace.update_in(cx, |workspace, window, cx| {
11647 // Open two docks
11648 let left_dock = workspace.dock_at_position(DockPosition::Left);
11649 let right_dock = workspace.dock_at_position(DockPosition::Right);
11650
11651 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11652 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11653
11654 assert!(left_dock.read(cx).is_open());
11655 assert!(right_dock.read(cx).is_open());
11656 });
11657
11658 workspace.update_in(cx, |workspace, window, cx| {
11659 // Close them manually
11660 workspace.toggle_dock(DockPosition::Left, window, cx);
11661 workspace.toggle_dock(DockPosition::Right, window, cx);
11662
11663 let left_dock = workspace.dock_at_position(DockPosition::Left);
11664 let right_dock = workspace.dock_at_position(DockPosition::Right);
11665 assert!(!left_dock.read(cx).is_open());
11666 assert!(!right_dock.read(cx).is_open());
11667 });
11668
11669 workspace.update_in(cx, |workspace, window, cx| {
11670 // Toggle all docks - only last closed (right dock) should reopen
11671 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11672
11673 let left_dock = workspace.dock_at_position(DockPosition::Left);
11674 let right_dock = workspace.dock_at_position(DockPosition::Right);
11675 assert!(!left_dock.read(cx).is_open());
11676 assert!(right_dock.read(cx).is_open());
11677 });
11678 }
11679
11680 #[gpui::test]
11681 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11682 init_test(cx);
11683 let fs = FakeFs::new(cx.executor());
11684 let project = Project::test(fs, [], cx).await;
11685 let (multi_workspace, cx) =
11686 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11687 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11688
11689 // Open two docks (left and right) with one panel each
11690 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11691 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11692 workspace.add_panel(left_panel.clone(), window, cx);
11693
11694 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11695 workspace.add_panel(right_panel.clone(), window, cx);
11696
11697 workspace.toggle_dock(DockPosition::Left, window, cx);
11698 workspace.toggle_dock(DockPosition::Right, window, cx);
11699
11700 // Verify initial state
11701 assert!(
11702 workspace.left_dock().read(cx).is_open(),
11703 "Left dock should be open"
11704 );
11705 assert_eq!(
11706 workspace
11707 .left_dock()
11708 .read(cx)
11709 .visible_panel()
11710 .unwrap()
11711 .panel_id(),
11712 left_panel.panel_id(),
11713 "Left panel should be visible in left dock"
11714 );
11715 assert!(
11716 workspace.right_dock().read(cx).is_open(),
11717 "Right dock should be open"
11718 );
11719 assert_eq!(
11720 workspace
11721 .right_dock()
11722 .read(cx)
11723 .visible_panel()
11724 .unwrap()
11725 .panel_id(),
11726 right_panel.panel_id(),
11727 "Right panel should be visible in right dock"
11728 );
11729 assert!(
11730 !workspace.bottom_dock().read(cx).is_open(),
11731 "Bottom dock should be closed"
11732 );
11733
11734 (left_panel, right_panel)
11735 });
11736
11737 // Focus the left panel and move it to the next position (bottom dock)
11738 workspace.update_in(cx, |workspace, window, cx| {
11739 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11740 assert!(
11741 left_panel.read(cx).focus_handle(cx).is_focused(window),
11742 "Left panel should be focused"
11743 );
11744 });
11745
11746 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11747
11748 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11749 workspace.update(cx, |workspace, cx| {
11750 assert!(
11751 !workspace.left_dock().read(cx).is_open(),
11752 "Left dock should be closed"
11753 );
11754 assert!(
11755 workspace.bottom_dock().read(cx).is_open(),
11756 "Bottom dock should now be open"
11757 );
11758 assert_eq!(
11759 left_panel.read(cx).position,
11760 DockPosition::Bottom,
11761 "Left panel should now be in the bottom dock"
11762 );
11763 assert_eq!(
11764 workspace
11765 .bottom_dock()
11766 .read(cx)
11767 .visible_panel()
11768 .unwrap()
11769 .panel_id(),
11770 left_panel.panel_id(),
11771 "Left panel should be the visible panel in the bottom dock"
11772 );
11773 });
11774
11775 // Toggle all docks off
11776 workspace.update_in(cx, |workspace, window, cx| {
11777 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11778 assert!(
11779 !workspace.left_dock().read(cx).is_open(),
11780 "Left dock should be closed"
11781 );
11782 assert!(
11783 !workspace.right_dock().read(cx).is_open(),
11784 "Right dock should be closed"
11785 );
11786 assert!(
11787 !workspace.bottom_dock().read(cx).is_open(),
11788 "Bottom dock should be closed"
11789 );
11790 });
11791
11792 // Toggle all docks back on and verify positions are restored
11793 workspace.update_in(cx, |workspace, window, cx| {
11794 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11795 assert!(
11796 !workspace.left_dock().read(cx).is_open(),
11797 "Left dock should remain closed"
11798 );
11799 assert!(
11800 workspace.right_dock().read(cx).is_open(),
11801 "Right dock should remain open"
11802 );
11803 assert!(
11804 workspace.bottom_dock().read(cx).is_open(),
11805 "Bottom dock should remain open"
11806 );
11807 assert_eq!(
11808 left_panel.read(cx).position,
11809 DockPosition::Bottom,
11810 "Left panel should remain in the bottom dock"
11811 );
11812 assert_eq!(
11813 right_panel.read(cx).position,
11814 DockPosition::Right,
11815 "Right panel should remain in the right dock"
11816 );
11817 assert_eq!(
11818 workspace
11819 .bottom_dock()
11820 .read(cx)
11821 .visible_panel()
11822 .unwrap()
11823 .panel_id(),
11824 left_panel.panel_id(),
11825 "Left panel should be the visible panel in the right dock"
11826 );
11827 });
11828 }
11829
11830 #[gpui::test]
11831 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11832 init_test(cx);
11833
11834 let fs = FakeFs::new(cx.executor());
11835
11836 let project = Project::test(fs, None, cx).await;
11837 let (workspace, cx) =
11838 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11839
11840 // Let's arrange the panes like this:
11841 //
11842 // +-----------------------+
11843 // | top |
11844 // +------+--------+-------+
11845 // | left | center | right |
11846 // +------+--------+-------+
11847 // | bottom |
11848 // +-----------------------+
11849
11850 let top_item = cx.new(|cx| {
11851 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11852 });
11853 let bottom_item = cx.new(|cx| {
11854 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11855 });
11856 let left_item = cx.new(|cx| {
11857 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11858 });
11859 let right_item = cx.new(|cx| {
11860 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11861 });
11862 let center_item = cx.new(|cx| {
11863 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11864 });
11865
11866 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11867 let top_pane_id = workspace.active_pane().entity_id();
11868 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11869 workspace.split_pane(
11870 workspace.active_pane().clone(),
11871 SplitDirection::Down,
11872 window,
11873 cx,
11874 );
11875 top_pane_id
11876 });
11877 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11878 let bottom_pane_id = workspace.active_pane().entity_id();
11879 workspace.add_item_to_active_pane(
11880 Box::new(bottom_item.clone()),
11881 None,
11882 false,
11883 window,
11884 cx,
11885 );
11886 workspace.split_pane(
11887 workspace.active_pane().clone(),
11888 SplitDirection::Up,
11889 window,
11890 cx,
11891 );
11892 bottom_pane_id
11893 });
11894 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11895 let left_pane_id = workspace.active_pane().entity_id();
11896 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11897 workspace.split_pane(
11898 workspace.active_pane().clone(),
11899 SplitDirection::Right,
11900 window,
11901 cx,
11902 );
11903 left_pane_id
11904 });
11905 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11906 let right_pane_id = workspace.active_pane().entity_id();
11907 workspace.add_item_to_active_pane(
11908 Box::new(right_item.clone()),
11909 None,
11910 false,
11911 window,
11912 cx,
11913 );
11914 workspace.split_pane(
11915 workspace.active_pane().clone(),
11916 SplitDirection::Left,
11917 window,
11918 cx,
11919 );
11920 right_pane_id
11921 });
11922 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11923 let center_pane_id = workspace.active_pane().entity_id();
11924 workspace.add_item_to_active_pane(
11925 Box::new(center_item.clone()),
11926 None,
11927 false,
11928 window,
11929 cx,
11930 );
11931 center_pane_id
11932 });
11933 cx.executor().run_until_parked();
11934
11935 workspace.update_in(cx, |workspace, window, cx| {
11936 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11937
11938 // Join into next from center pane into right
11939 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11940 });
11941
11942 workspace.update_in(cx, |workspace, window, cx| {
11943 let active_pane = workspace.active_pane();
11944 assert_eq!(right_pane_id, active_pane.entity_id());
11945 assert_eq!(2, active_pane.read(cx).items_len());
11946 let item_ids_in_pane =
11947 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11948 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11949 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11950
11951 // Join into next from right pane into bottom
11952 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11953 });
11954
11955 workspace.update_in(cx, |workspace, window, cx| {
11956 let active_pane = workspace.active_pane();
11957 assert_eq!(bottom_pane_id, active_pane.entity_id());
11958 assert_eq!(3, active_pane.read(cx).items_len());
11959 let item_ids_in_pane =
11960 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11961 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11962 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11963 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11964
11965 // Join into next from bottom pane into left
11966 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11967 });
11968
11969 workspace.update_in(cx, |workspace, window, cx| {
11970 let active_pane = workspace.active_pane();
11971 assert_eq!(left_pane_id, active_pane.entity_id());
11972 assert_eq!(4, active_pane.read(cx).items_len());
11973 let item_ids_in_pane =
11974 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11975 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11976 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11977 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11978 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11979
11980 // Join into next from left pane into top
11981 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11982 });
11983
11984 workspace.update_in(cx, |workspace, window, cx| {
11985 let active_pane = workspace.active_pane();
11986 assert_eq!(top_pane_id, active_pane.entity_id());
11987 assert_eq!(5, active_pane.read(cx).items_len());
11988 let item_ids_in_pane =
11989 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11990 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11991 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11992 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11993 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11994 assert!(item_ids_in_pane.contains(&top_item.item_id()));
11995
11996 // Single pane left: no-op
11997 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11998 });
11999
12000 workspace.update(cx, |workspace, _cx| {
12001 let active_pane = workspace.active_pane();
12002 assert_eq!(top_pane_id, active_pane.entity_id());
12003 });
12004 }
12005
12006 fn add_an_item_to_active_pane(
12007 cx: &mut VisualTestContext,
12008 workspace: &Entity<Workspace>,
12009 item_id: u64,
12010 ) -> Entity<TestItem> {
12011 let item = cx.new(|cx| {
12012 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12013 item_id,
12014 "item{item_id}.txt",
12015 cx,
12016 )])
12017 });
12018 workspace.update_in(cx, |workspace, window, cx| {
12019 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12020 });
12021 item
12022 }
12023
12024 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12025 workspace.update_in(cx, |workspace, window, cx| {
12026 workspace.split_pane(
12027 workspace.active_pane().clone(),
12028 SplitDirection::Right,
12029 window,
12030 cx,
12031 )
12032 })
12033 }
12034
12035 #[gpui::test]
12036 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12037 init_test(cx);
12038 let fs = FakeFs::new(cx.executor());
12039 let project = Project::test(fs, None, cx).await;
12040 let (workspace, cx) =
12041 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12042
12043 add_an_item_to_active_pane(cx, &workspace, 1);
12044 split_pane(cx, &workspace);
12045 add_an_item_to_active_pane(cx, &workspace, 2);
12046 split_pane(cx, &workspace); // empty pane
12047 split_pane(cx, &workspace);
12048 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12049
12050 cx.executor().run_until_parked();
12051
12052 workspace.update(cx, |workspace, cx| {
12053 let num_panes = workspace.panes().len();
12054 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12055 let active_item = workspace
12056 .active_pane()
12057 .read(cx)
12058 .active_item()
12059 .expect("item is in focus");
12060
12061 assert_eq!(num_panes, 4);
12062 assert_eq!(num_items_in_current_pane, 1);
12063 assert_eq!(active_item.item_id(), last_item.item_id());
12064 });
12065
12066 workspace.update_in(cx, |workspace, window, cx| {
12067 workspace.join_all_panes(window, cx);
12068 });
12069
12070 workspace.update(cx, |workspace, cx| {
12071 let num_panes = workspace.panes().len();
12072 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12073 let active_item = workspace
12074 .active_pane()
12075 .read(cx)
12076 .active_item()
12077 .expect("item is in focus");
12078
12079 assert_eq!(num_panes, 1);
12080 assert_eq!(num_items_in_current_pane, 3);
12081 assert_eq!(active_item.item_id(), last_item.item_id());
12082 });
12083 }
12084 struct TestModal(FocusHandle);
12085
12086 impl TestModal {
12087 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12088 Self(cx.focus_handle())
12089 }
12090 }
12091
12092 impl EventEmitter<DismissEvent> for TestModal {}
12093
12094 impl Focusable for TestModal {
12095 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12096 self.0.clone()
12097 }
12098 }
12099
12100 impl ModalView for TestModal {}
12101
12102 impl Render for TestModal {
12103 fn render(
12104 &mut self,
12105 _window: &mut Window,
12106 _cx: &mut Context<TestModal>,
12107 ) -> impl IntoElement {
12108 div().track_focus(&self.0)
12109 }
12110 }
12111
12112 #[gpui::test]
12113 async fn test_panels(cx: &mut gpui::TestAppContext) {
12114 init_test(cx);
12115 let fs = FakeFs::new(cx.executor());
12116
12117 let project = Project::test(fs, [], cx).await;
12118 let (multi_workspace, cx) =
12119 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12120 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12121
12122 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12123 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12124 workspace.add_panel(panel_1.clone(), window, cx);
12125 workspace.toggle_dock(DockPosition::Left, window, cx);
12126 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12127 workspace.add_panel(panel_2.clone(), window, cx);
12128 workspace.toggle_dock(DockPosition::Right, window, cx);
12129
12130 let left_dock = workspace.left_dock();
12131 assert_eq!(
12132 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12133 panel_1.panel_id()
12134 );
12135 assert_eq!(
12136 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
12137 panel_1.size(window, cx)
12138 );
12139
12140 left_dock.update(cx, |left_dock, cx| {
12141 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
12142 });
12143 assert_eq!(
12144 workspace
12145 .right_dock()
12146 .read(cx)
12147 .visible_panel()
12148 .unwrap()
12149 .panel_id(),
12150 panel_2.panel_id(),
12151 );
12152
12153 (panel_1, panel_2)
12154 });
12155
12156 // Move panel_1 to the right
12157 panel_1.update_in(cx, |panel_1, window, cx| {
12158 panel_1.set_position(DockPosition::Right, window, cx)
12159 });
12160
12161 workspace.update_in(cx, |workspace, window, cx| {
12162 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12163 // Since it was the only panel on the left, the left dock should now be closed.
12164 assert!(!workspace.left_dock().read(cx).is_open());
12165 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12166 let right_dock = workspace.right_dock();
12167 assert_eq!(
12168 right_dock.read(cx).visible_panel().unwrap().panel_id(),
12169 panel_1.panel_id()
12170 );
12171 assert_eq!(
12172 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
12173 px(1337.)
12174 );
12175
12176 // Now we move panel_2 to the left
12177 panel_2.set_position(DockPosition::Left, window, cx);
12178 });
12179
12180 workspace.update(cx, |workspace, cx| {
12181 // Since panel_2 was not visible on the right, we don't open the left dock.
12182 assert!(!workspace.left_dock().read(cx).is_open());
12183 // And the right dock is unaffected in its displaying of panel_1
12184 assert!(workspace.right_dock().read(cx).is_open());
12185 assert_eq!(
12186 workspace
12187 .right_dock()
12188 .read(cx)
12189 .visible_panel()
12190 .unwrap()
12191 .panel_id(),
12192 panel_1.panel_id(),
12193 );
12194 });
12195
12196 // Move panel_1 back to the left
12197 panel_1.update_in(cx, |panel_1, window, cx| {
12198 panel_1.set_position(DockPosition::Left, window, cx)
12199 });
12200
12201 workspace.update_in(cx, |workspace, window, cx| {
12202 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12203 let left_dock = workspace.left_dock();
12204 assert!(left_dock.read(cx).is_open());
12205 assert_eq!(
12206 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12207 panel_1.panel_id()
12208 );
12209 assert_eq!(
12210 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
12211 px(1337.)
12212 );
12213 // And the right dock should be closed as it no longer has any panels.
12214 assert!(!workspace.right_dock().read(cx).is_open());
12215
12216 // Now we move panel_1 to the bottom
12217 panel_1.set_position(DockPosition::Bottom, window, cx);
12218 });
12219
12220 workspace.update_in(cx, |workspace, window, cx| {
12221 // Since panel_1 was visible on the left, we close the left dock.
12222 assert!(!workspace.left_dock().read(cx).is_open());
12223 // The bottom dock is sized based on the panel's default size,
12224 // since the panel orientation changed from vertical to horizontal.
12225 let bottom_dock = workspace.bottom_dock();
12226 assert_eq!(
12227 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
12228 panel_1.size(window, cx),
12229 );
12230 // Close bottom dock and move panel_1 back to the left.
12231 bottom_dock.update(cx, |bottom_dock, cx| {
12232 bottom_dock.set_open(false, window, cx)
12233 });
12234 panel_1.set_position(DockPosition::Left, window, cx);
12235 });
12236
12237 // Emit activated event on panel 1
12238 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12239
12240 // Now the left dock is open and panel_1 is active and focused.
12241 workspace.update_in(cx, |workspace, window, cx| {
12242 let left_dock = workspace.left_dock();
12243 assert!(left_dock.read(cx).is_open());
12244 assert_eq!(
12245 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12246 panel_1.panel_id(),
12247 );
12248 assert!(panel_1.focus_handle(cx).is_focused(window));
12249 });
12250
12251 // Emit closed event on panel 2, which is not active
12252 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12253
12254 // Wo don't close the left dock, because panel_2 wasn't the active panel
12255 workspace.update(cx, |workspace, cx| {
12256 let left_dock = workspace.left_dock();
12257 assert!(left_dock.read(cx).is_open());
12258 assert_eq!(
12259 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12260 panel_1.panel_id(),
12261 );
12262 });
12263
12264 // Emitting a ZoomIn event shows the panel as zoomed.
12265 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12266 workspace.read_with(cx, |workspace, _| {
12267 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12268 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12269 });
12270
12271 // Move panel to another dock while it is zoomed
12272 panel_1.update_in(cx, |panel, window, cx| {
12273 panel.set_position(DockPosition::Right, window, cx)
12274 });
12275 workspace.read_with(cx, |workspace, _| {
12276 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12277
12278 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12279 });
12280
12281 // This is a helper for getting a:
12282 // - valid focus on an element,
12283 // - that isn't a part of the panes and panels system of the Workspace,
12284 // - and doesn't trigger the 'on_focus_lost' API.
12285 let focus_other_view = {
12286 let workspace = workspace.clone();
12287 move |cx: &mut VisualTestContext| {
12288 workspace.update_in(cx, |workspace, window, cx| {
12289 if workspace.active_modal::<TestModal>(cx).is_some() {
12290 workspace.toggle_modal(window, cx, TestModal::new);
12291 workspace.toggle_modal(window, cx, TestModal::new);
12292 } else {
12293 workspace.toggle_modal(window, cx, TestModal::new);
12294 }
12295 })
12296 }
12297 };
12298
12299 // If focus is transferred to another view that's not a panel or another pane, we still show
12300 // the panel as zoomed.
12301 focus_other_view(cx);
12302 workspace.read_with(cx, |workspace, _| {
12303 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12304 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12305 });
12306
12307 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12308 workspace.update_in(cx, |_workspace, window, cx| {
12309 cx.focus_self(window);
12310 });
12311 workspace.read_with(cx, |workspace, _| {
12312 assert_eq!(workspace.zoomed, None);
12313 assert_eq!(workspace.zoomed_position, None);
12314 });
12315
12316 // If focus is transferred again to another view that's not a panel or a pane, we won't
12317 // show the panel as zoomed because it wasn't zoomed before.
12318 focus_other_view(cx);
12319 workspace.read_with(cx, |workspace, _| {
12320 assert_eq!(workspace.zoomed, None);
12321 assert_eq!(workspace.zoomed_position, None);
12322 });
12323
12324 // When the panel is activated, it is zoomed again.
12325 cx.dispatch_action(ToggleRightDock);
12326 workspace.read_with(cx, |workspace, _| {
12327 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12328 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12329 });
12330
12331 // Emitting a ZoomOut event unzooms the panel.
12332 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12333 workspace.read_with(cx, |workspace, _| {
12334 assert_eq!(workspace.zoomed, None);
12335 assert_eq!(workspace.zoomed_position, None);
12336 });
12337
12338 // Emit closed event on panel 1, which is active
12339 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12340
12341 // Now the left dock is closed, because panel_1 was the active panel
12342 workspace.update(cx, |workspace, cx| {
12343 let right_dock = workspace.right_dock();
12344 assert!(!right_dock.read(cx).is_open());
12345 });
12346 }
12347
12348 #[gpui::test]
12349 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12350 init_test(cx);
12351
12352 let fs = FakeFs::new(cx.background_executor.clone());
12353 let project = Project::test(fs, [], cx).await;
12354 let (workspace, cx) =
12355 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12356 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12357
12358 let dirty_regular_buffer = cx.new(|cx| {
12359 TestItem::new(cx)
12360 .with_dirty(true)
12361 .with_label("1.txt")
12362 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12363 });
12364 let dirty_regular_buffer_2 = cx.new(|cx| {
12365 TestItem::new(cx)
12366 .with_dirty(true)
12367 .with_label("2.txt")
12368 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12369 });
12370 let dirty_multi_buffer_with_both = cx.new(|cx| {
12371 TestItem::new(cx)
12372 .with_dirty(true)
12373 .with_buffer_kind(ItemBufferKind::Multibuffer)
12374 .with_label("Fake Project Search")
12375 .with_project_items(&[
12376 dirty_regular_buffer.read(cx).project_items[0].clone(),
12377 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12378 ])
12379 });
12380 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12381 workspace.update_in(cx, |workspace, window, cx| {
12382 workspace.add_item(
12383 pane.clone(),
12384 Box::new(dirty_regular_buffer.clone()),
12385 None,
12386 false,
12387 false,
12388 window,
12389 cx,
12390 );
12391 workspace.add_item(
12392 pane.clone(),
12393 Box::new(dirty_regular_buffer_2.clone()),
12394 None,
12395 false,
12396 false,
12397 window,
12398 cx,
12399 );
12400 workspace.add_item(
12401 pane.clone(),
12402 Box::new(dirty_multi_buffer_with_both.clone()),
12403 None,
12404 false,
12405 false,
12406 window,
12407 cx,
12408 );
12409 });
12410
12411 pane.update_in(cx, |pane, window, cx| {
12412 pane.activate_item(2, true, true, window, cx);
12413 assert_eq!(
12414 pane.active_item().unwrap().item_id(),
12415 multi_buffer_with_both_files_id,
12416 "Should select the multi buffer in the pane"
12417 );
12418 });
12419 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12420 pane.close_other_items(
12421 &CloseOtherItems {
12422 save_intent: Some(SaveIntent::Save),
12423 close_pinned: true,
12424 },
12425 None,
12426 window,
12427 cx,
12428 )
12429 });
12430 cx.background_executor.run_until_parked();
12431 assert!(!cx.has_pending_prompt());
12432 close_all_but_multi_buffer_task
12433 .await
12434 .expect("Closing all buffers but the multi buffer failed");
12435 pane.update(cx, |pane, cx| {
12436 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12437 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12438 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12439 assert_eq!(pane.items_len(), 1);
12440 assert_eq!(
12441 pane.active_item().unwrap().item_id(),
12442 multi_buffer_with_both_files_id,
12443 "Should have only the multi buffer left in the pane"
12444 );
12445 assert!(
12446 dirty_multi_buffer_with_both.read(cx).is_dirty,
12447 "The multi buffer containing the unsaved buffer should still be dirty"
12448 );
12449 });
12450
12451 dirty_regular_buffer.update(cx, |buffer, cx| {
12452 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12453 });
12454
12455 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12456 pane.close_active_item(
12457 &CloseActiveItem {
12458 save_intent: Some(SaveIntent::Close),
12459 close_pinned: false,
12460 },
12461 window,
12462 cx,
12463 )
12464 });
12465 cx.background_executor.run_until_parked();
12466 assert!(
12467 cx.has_pending_prompt(),
12468 "Dirty multi buffer should prompt a save dialog"
12469 );
12470 cx.simulate_prompt_answer("Save");
12471 cx.background_executor.run_until_parked();
12472 close_multi_buffer_task
12473 .await
12474 .expect("Closing the multi buffer failed");
12475 pane.update(cx, |pane, cx| {
12476 assert_eq!(
12477 dirty_multi_buffer_with_both.read(cx).save_count,
12478 1,
12479 "Multi buffer item should get be saved"
12480 );
12481 // Test impl does not save inner items, so we do not assert them
12482 assert_eq!(
12483 pane.items_len(),
12484 0,
12485 "No more items should be left in the pane"
12486 );
12487 assert!(pane.active_item().is_none());
12488 });
12489 }
12490
12491 #[gpui::test]
12492 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
12493 cx: &mut TestAppContext,
12494 ) {
12495 init_test(cx);
12496
12497 let fs = FakeFs::new(cx.background_executor.clone());
12498 let project = Project::test(fs, [], cx).await;
12499 let (workspace, cx) =
12500 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12501 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12502
12503 let dirty_regular_buffer = cx.new(|cx| {
12504 TestItem::new(cx)
12505 .with_dirty(true)
12506 .with_label("1.txt")
12507 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12508 });
12509 let dirty_regular_buffer_2 = cx.new(|cx| {
12510 TestItem::new(cx)
12511 .with_dirty(true)
12512 .with_label("2.txt")
12513 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12514 });
12515 let clear_regular_buffer = cx.new(|cx| {
12516 TestItem::new(cx)
12517 .with_label("3.txt")
12518 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12519 });
12520
12521 let dirty_multi_buffer_with_both = cx.new(|cx| {
12522 TestItem::new(cx)
12523 .with_dirty(true)
12524 .with_buffer_kind(ItemBufferKind::Multibuffer)
12525 .with_label("Fake Project Search")
12526 .with_project_items(&[
12527 dirty_regular_buffer.read(cx).project_items[0].clone(),
12528 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12529 clear_regular_buffer.read(cx).project_items[0].clone(),
12530 ])
12531 });
12532 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12533 workspace.update_in(cx, |workspace, window, cx| {
12534 workspace.add_item(
12535 pane.clone(),
12536 Box::new(dirty_regular_buffer.clone()),
12537 None,
12538 false,
12539 false,
12540 window,
12541 cx,
12542 );
12543 workspace.add_item(
12544 pane.clone(),
12545 Box::new(dirty_multi_buffer_with_both.clone()),
12546 None,
12547 false,
12548 false,
12549 window,
12550 cx,
12551 );
12552 });
12553
12554 pane.update_in(cx, |pane, window, cx| {
12555 pane.activate_item(1, true, true, window, cx);
12556 assert_eq!(
12557 pane.active_item().unwrap().item_id(),
12558 multi_buffer_with_both_files_id,
12559 "Should select the multi buffer in the pane"
12560 );
12561 });
12562 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12563 pane.close_active_item(
12564 &CloseActiveItem {
12565 save_intent: None,
12566 close_pinned: false,
12567 },
12568 window,
12569 cx,
12570 )
12571 });
12572 cx.background_executor.run_until_parked();
12573 assert!(
12574 cx.has_pending_prompt(),
12575 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
12576 );
12577 }
12578
12579 /// Tests that when `close_on_file_delete` is enabled, files are automatically
12580 /// closed when they are deleted from disk.
12581 #[gpui::test]
12582 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
12583 init_test(cx);
12584
12585 // Enable the close_on_disk_deletion setting
12586 cx.update_global(|store: &mut SettingsStore, cx| {
12587 store.update_user_settings(cx, |settings| {
12588 settings.workspace.close_on_file_delete = Some(true);
12589 });
12590 });
12591
12592 let fs = FakeFs::new(cx.background_executor.clone());
12593 let project = Project::test(fs, [], cx).await;
12594 let (workspace, cx) =
12595 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12596 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12597
12598 // Create a test item that simulates a file
12599 let item = cx.new(|cx| {
12600 TestItem::new(cx)
12601 .with_label("test.txt")
12602 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12603 });
12604
12605 // Add item to workspace
12606 workspace.update_in(cx, |workspace, window, cx| {
12607 workspace.add_item(
12608 pane.clone(),
12609 Box::new(item.clone()),
12610 None,
12611 false,
12612 false,
12613 window,
12614 cx,
12615 );
12616 });
12617
12618 // Verify the item is in the pane
12619 pane.read_with(cx, |pane, _| {
12620 assert_eq!(pane.items().count(), 1);
12621 });
12622
12623 // Simulate file deletion by setting the item's deleted state
12624 item.update(cx, |item, _| {
12625 item.set_has_deleted_file(true);
12626 });
12627
12628 // Emit UpdateTab event to trigger the close behavior
12629 cx.run_until_parked();
12630 item.update(cx, |_, cx| {
12631 cx.emit(ItemEvent::UpdateTab);
12632 });
12633
12634 // Allow the close operation to complete
12635 cx.run_until_parked();
12636
12637 // Verify the item was automatically closed
12638 pane.read_with(cx, |pane, _| {
12639 assert_eq!(
12640 pane.items().count(),
12641 0,
12642 "Item should be automatically closed when file is deleted"
12643 );
12644 });
12645 }
12646
12647 /// Tests that when `close_on_file_delete` is disabled (default), files remain
12648 /// open with a strikethrough when they are deleted from disk.
12649 #[gpui::test]
12650 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12651 init_test(cx);
12652
12653 // Ensure close_on_disk_deletion is disabled (default)
12654 cx.update_global(|store: &mut SettingsStore, cx| {
12655 store.update_user_settings(cx, |settings| {
12656 settings.workspace.close_on_file_delete = Some(false);
12657 });
12658 });
12659
12660 let fs = FakeFs::new(cx.background_executor.clone());
12661 let project = Project::test(fs, [], cx).await;
12662 let (workspace, cx) =
12663 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12664 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12665
12666 // Create a test item that simulates a file
12667 let item = cx.new(|cx| {
12668 TestItem::new(cx)
12669 .with_label("test.txt")
12670 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12671 });
12672
12673 // Add item to workspace
12674 workspace.update_in(cx, |workspace, window, cx| {
12675 workspace.add_item(
12676 pane.clone(),
12677 Box::new(item.clone()),
12678 None,
12679 false,
12680 false,
12681 window,
12682 cx,
12683 );
12684 });
12685
12686 // Verify the item is in the pane
12687 pane.read_with(cx, |pane, _| {
12688 assert_eq!(pane.items().count(), 1);
12689 });
12690
12691 // Simulate file deletion
12692 item.update(cx, |item, _| {
12693 item.set_has_deleted_file(true);
12694 });
12695
12696 // Emit UpdateTab event
12697 cx.run_until_parked();
12698 item.update(cx, |_, cx| {
12699 cx.emit(ItemEvent::UpdateTab);
12700 });
12701
12702 // Allow any potential close operation to complete
12703 cx.run_until_parked();
12704
12705 // Verify the item remains open (with strikethrough)
12706 pane.read_with(cx, |pane, _| {
12707 assert_eq!(
12708 pane.items().count(),
12709 1,
12710 "Item should remain open when close_on_disk_deletion is disabled"
12711 );
12712 });
12713
12714 // Verify the item shows as deleted
12715 item.read_with(cx, |item, _| {
12716 assert!(
12717 item.has_deleted_file,
12718 "Item should be marked as having deleted file"
12719 );
12720 });
12721 }
12722
12723 /// Tests that dirty files are not automatically closed when deleted from disk,
12724 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12725 /// unsaved changes without being prompted.
12726 #[gpui::test]
12727 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12728 init_test(cx);
12729
12730 // Enable the close_on_file_delete setting
12731 cx.update_global(|store: &mut SettingsStore, cx| {
12732 store.update_user_settings(cx, |settings| {
12733 settings.workspace.close_on_file_delete = Some(true);
12734 });
12735 });
12736
12737 let fs = FakeFs::new(cx.background_executor.clone());
12738 let project = Project::test(fs, [], cx).await;
12739 let (workspace, cx) =
12740 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12741 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12742
12743 // Create a dirty test item
12744 let item = cx.new(|cx| {
12745 TestItem::new(cx)
12746 .with_dirty(true)
12747 .with_label("test.txt")
12748 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12749 });
12750
12751 // Add item to workspace
12752 workspace.update_in(cx, |workspace, window, cx| {
12753 workspace.add_item(
12754 pane.clone(),
12755 Box::new(item.clone()),
12756 None,
12757 false,
12758 false,
12759 window,
12760 cx,
12761 );
12762 });
12763
12764 // Simulate file deletion
12765 item.update(cx, |item, _| {
12766 item.set_has_deleted_file(true);
12767 });
12768
12769 // Emit UpdateTab event to trigger the close behavior
12770 cx.run_until_parked();
12771 item.update(cx, |_, cx| {
12772 cx.emit(ItemEvent::UpdateTab);
12773 });
12774
12775 // Allow any potential close operation to complete
12776 cx.run_until_parked();
12777
12778 // Verify the item remains open (dirty files are not auto-closed)
12779 pane.read_with(cx, |pane, _| {
12780 assert_eq!(
12781 pane.items().count(),
12782 1,
12783 "Dirty items should not be automatically closed even when file is deleted"
12784 );
12785 });
12786
12787 // Verify the item is marked as deleted and still dirty
12788 item.read_with(cx, |item, _| {
12789 assert!(
12790 item.has_deleted_file,
12791 "Item should be marked as having deleted file"
12792 );
12793 assert!(item.is_dirty, "Item should still be dirty");
12794 });
12795 }
12796
12797 /// Tests that navigation history is cleaned up when files are auto-closed
12798 /// due to deletion from disk.
12799 #[gpui::test]
12800 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12801 init_test(cx);
12802
12803 // Enable the close_on_file_delete setting
12804 cx.update_global(|store: &mut SettingsStore, cx| {
12805 store.update_user_settings(cx, |settings| {
12806 settings.workspace.close_on_file_delete = Some(true);
12807 });
12808 });
12809
12810 let fs = FakeFs::new(cx.background_executor.clone());
12811 let project = Project::test(fs, [], cx).await;
12812 let (workspace, cx) =
12813 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12814 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12815
12816 // Create test items
12817 let item1 = cx.new(|cx| {
12818 TestItem::new(cx)
12819 .with_label("test1.txt")
12820 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12821 });
12822 let item1_id = item1.item_id();
12823
12824 let item2 = cx.new(|cx| {
12825 TestItem::new(cx)
12826 .with_label("test2.txt")
12827 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12828 });
12829
12830 // Add items to workspace
12831 workspace.update_in(cx, |workspace, window, cx| {
12832 workspace.add_item(
12833 pane.clone(),
12834 Box::new(item1.clone()),
12835 None,
12836 false,
12837 false,
12838 window,
12839 cx,
12840 );
12841 workspace.add_item(
12842 pane.clone(),
12843 Box::new(item2.clone()),
12844 None,
12845 false,
12846 false,
12847 window,
12848 cx,
12849 );
12850 });
12851
12852 // Activate item1 to ensure it gets navigation entries
12853 pane.update_in(cx, |pane, window, cx| {
12854 pane.activate_item(0, true, true, window, cx);
12855 });
12856
12857 // Switch to item2 and back to create navigation history
12858 pane.update_in(cx, |pane, window, cx| {
12859 pane.activate_item(1, true, true, window, cx);
12860 });
12861 cx.run_until_parked();
12862
12863 pane.update_in(cx, |pane, window, cx| {
12864 pane.activate_item(0, true, true, window, cx);
12865 });
12866 cx.run_until_parked();
12867
12868 // Simulate file deletion for item1
12869 item1.update(cx, |item, _| {
12870 item.set_has_deleted_file(true);
12871 });
12872
12873 // Emit UpdateTab event to trigger the close behavior
12874 item1.update(cx, |_, cx| {
12875 cx.emit(ItemEvent::UpdateTab);
12876 });
12877 cx.run_until_parked();
12878
12879 // Verify item1 was closed
12880 pane.read_with(cx, |pane, _| {
12881 assert_eq!(
12882 pane.items().count(),
12883 1,
12884 "Should have 1 item remaining after auto-close"
12885 );
12886 });
12887
12888 // Check navigation history after close
12889 let has_item = pane.read_with(cx, |pane, cx| {
12890 let mut has_item = false;
12891 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12892 if entry.item.id() == item1_id {
12893 has_item = true;
12894 }
12895 });
12896 has_item
12897 });
12898
12899 assert!(
12900 !has_item,
12901 "Navigation history should not contain closed item entries"
12902 );
12903 }
12904
12905 #[gpui::test]
12906 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12907 cx: &mut TestAppContext,
12908 ) {
12909 init_test(cx);
12910
12911 let fs = FakeFs::new(cx.background_executor.clone());
12912 let project = Project::test(fs, [], cx).await;
12913 let (workspace, cx) =
12914 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12915 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12916
12917 let dirty_regular_buffer = cx.new(|cx| {
12918 TestItem::new(cx)
12919 .with_dirty(true)
12920 .with_label("1.txt")
12921 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12922 });
12923 let dirty_regular_buffer_2 = cx.new(|cx| {
12924 TestItem::new(cx)
12925 .with_dirty(true)
12926 .with_label("2.txt")
12927 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12928 });
12929 let clear_regular_buffer = cx.new(|cx| {
12930 TestItem::new(cx)
12931 .with_label("3.txt")
12932 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12933 });
12934
12935 let dirty_multi_buffer = cx.new(|cx| {
12936 TestItem::new(cx)
12937 .with_dirty(true)
12938 .with_buffer_kind(ItemBufferKind::Multibuffer)
12939 .with_label("Fake Project Search")
12940 .with_project_items(&[
12941 dirty_regular_buffer.read(cx).project_items[0].clone(),
12942 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12943 clear_regular_buffer.read(cx).project_items[0].clone(),
12944 ])
12945 });
12946 workspace.update_in(cx, |workspace, window, cx| {
12947 workspace.add_item(
12948 pane.clone(),
12949 Box::new(dirty_regular_buffer.clone()),
12950 None,
12951 false,
12952 false,
12953 window,
12954 cx,
12955 );
12956 workspace.add_item(
12957 pane.clone(),
12958 Box::new(dirty_regular_buffer_2.clone()),
12959 None,
12960 false,
12961 false,
12962 window,
12963 cx,
12964 );
12965 workspace.add_item(
12966 pane.clone(),
12967 Box::new(dirty_multi_buffer.clone()),
12968 None,
12969 false,
12970 false,
12971 window,
12972 cx,
12973 );
12974 });
12975
12976 pane.update_in(cx, |pane, window, cx| {
12977 pane.activate_item(2, true, true, window, cx);
12978 assert_eq!(
12979 pane.active_item().unwrap().item_id(),
12980 dirty_multi_buffer.item_id(),
12981 "Should select the multi buffer in the pane"
12982 );
12983 });
12984 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12985 pane.close_active_item(
12986 &CloseActiveItem {
12987 save_intent: None,
12988 close_pinned: false,
12989 },
12990 window,
12991 cx,
12992 )
12993 });
12994 cx.background_executor.run_until_parked();
12995 assert!(
12996 !cx.has_pending_prompt(),
12997 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12998 );
12999 close_multi_buffer_task
13000 .await
13001 .expect("Closing multi buffer failed");
13002 pane.update(cx, |pane, cx| {
13003 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13004 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13005 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13006 assert_eq!(
13007 pane.items()
13008 .map(|item| item.item_id())
13009 .sorted()
13010 .collect::<Vec<_>>(),
13011 vec![
13012 dirty_regular_buffer.item_id(),
13013 dirty_regular_buffer_2.item_id(),
13014 ],
13015 "Should have no multi buffer left in the pane"
13016 );
13017 assert!(dirty_regular_buffer.read(cx).is_dirty);
13018 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13019 });
13020 }
13021
13022 #[gpui::test]
13023 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13024 init_test(cx);
13025 let fs = FakeFs::new(cx.executor());
13026 let project = Project::test(fs, [], cx).await;
13027 let (multi_workspace, cx) =
13028 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13029 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13030
13031 // Add a new panel to the right dock, opening the dock and setting the
13032 // focus to the new panel.
13033 let panel = workspace.update_in(cx, |workspace, window, cx| {
13034 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13035 workspace.add_panel(panel.clone(), window, cx);
13036
13037 workspace
13038 .right_dock()
13039 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13040
13041 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13042
13043 panel
13044 });
13045
13046 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13047 // panel to the next valid position which, in this case, is the left
13048 // dock.
13049 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13050 workspace.update(cx, |workspace, cx| {
13051 assert!(workspace.left_dock().read(cx).is_open());
13052 assert_eq!(panel.read(cx).position, DockPosition::Left);
13053 });
13054
13055 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13056 // panel to the next valid position which, in this case, is the bottom
13057 // dock.
13058 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13059 workspace.update(cx, |workspace, cx| {
13060 assert!(workspace.bottom_dock().read(cx).is_open());
13061 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13062 });
13063
13064 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13065 // around moving the panel to its initial position, the right dock.
13066 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13067 workspace.update(cx, |workspace, cx| {
13068 assert!(workspace.right_dock().read(cx).is_open());
13069 assert_eq!(panel.read(cx).position, DockPosition::Right);
13070 });
13071
13072 // Remove focus from the panel, ensuring that, if the panel is not
13073 // focused, the `MoveFocusedPanelToNextPosition` action does not update
13074 // the panel's position, so the panel is still in the right dock.
13075 workspace.update_in(cx, |workspace, window, cx| {
13076 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13077 });
13078
13079 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13080 workspace.update(cx, |workspace, cx| {
13081 assert!(workspace.right_dock().read(cx).is_open());
13082 assert_eq!(panel.read(cx).position, DockPosition::Right);
13083 });
13084 }
13085
13086 #[gpui::test]
13087 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13088 init_test(cx);
13089
13090 let fs = FakeFs::new(cx.executor());
13091 let project = Project::test(fs, [], cx).await;
13092 let (workspace, cx) =
13093 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13094
13095 let item_1 = cx.new(|cx| {
13096 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13097 });
13098 workspace.update_in(cx, |workspace, window, cx| {
13099 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13100 workspace.move_item_to_pane_in_direction(
13101 &MoveItemToPaneInDirection {
13102 direction: SplitDirection::Right,
13103 focus: true,
13104 clone: false,
13105 },
13106 window,
13107 cx,
13108 );
13109 workspace.move_item_to_pane_at_index(
13110 &MoveItemToPane {
13111 destination: 3,
13112 focus: true,
13113 clone: false,
13114 },
13115 window,
13116 cx,
13117 );
13118
13119 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13120 assert_eq!(
13121 pane_items_paths(&workspace.active_pane, cx),
13122 vec!["first.txt".to_string()],
13123 "Single item was not moved anywhere"
13124 );
13125 });
13126
13127 let item_2 = cx.new(|cx| {
13128 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13129 });
13130 workspace.update_in(cx, |workspace, window, cx| {
13131 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13132 assert_eq!(
13133 pane_items_paths(&workspace.panes[0], cx),
13134 vec!["first.txt".to_string(), "second.txt".to_string()],
13135 );
13136 workspace.move_item_to_pane_in_direction(
13137 &MoveItemToPaneInDirection {
13138 direction: SplitDirection::Right,
13139 focus: true,
13140 clone: false,
13141 },
13142 window,
13143 cx,
13144 );
13145
13146 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13147 assert_eq!(
13148 pane_items_paths(&workspace.panes[0], cx),
13149 vec!["first.txt".to_string()],
13150 "After moving, one item should be left in the original pane"
13151 );
13152 assert_eq!(
13153 pane_items_paths(&workspace.panes[1], cx),
13154 vec!["second.txt".to_string()],
13155 "New item should have been moved to the new pane"
13156 );
13157 });
13158
13159 let item_3 = cx.new(|cx| {
13160 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13161 });
13162 workspace.update_in(cx, |workspace, window, cx| {
13163 let original_pane = workspace.panes[0].clone();
13164 workspace.set_active_pane(&original_pane, window, cx);
13165 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13166 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13167 assert_eq!(
13168 pane_items_paths(&workspace.active_pane, cx),
13169 vec!["first.txt".to_string(), "third.txt".to_string()],
13170 "New pane should be ready to move one item out"
13171 );
13172
13173 workspace.move_item_to_pane_at_index(
13174 &MoveItemToPane {
13175 destination: 3,
13176 focus: true,
13177 clone: false,
13178 },
13179 window,
13180 cx,
13181 );
13182 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13183 assert_eq!(
13184 pane_items_paths(&workspace.active_pane, cx),
13185 vec!["first.txt".to_string()],
13186 "After moving, one item should be left in the original pane"
13187 );
13188 assert_eq!(
13189 pane_items_paths(&workspace.panes[1], cx),
13190 vec!["second.txt".to_string()],
13191 "Previously created pane should be unchanged"
13192 );
13193 assert_eq!(
13194 pane_items_paths(&workspace.panes[2], cx),
13195 vec!["third.txt".to_string()],
13196 "New item should have been moved to the new pane"
13197 );
13198 });
13199 }
13200
13201 #[gpui::test]
13202 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13203 init_test(cx);
13204
13205 let fs = FakeFs::new(cx.executor());
13206 let project = Project::test(fs, [], cx).await;
13207 let (workspace, cx) =
13208 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13209
13210 let item_1 = cx.new(|cx| {
13211 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13212 });
13213 workspace.update_in(cx, |workspace, window, cx| {
13214 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13215 workspace.move_item_to_pane_in_direction(
13216 &MoveItemToPaneInDirection {
13217 direction: SplitDirection::Right,
13218 focus: true,
13219 clone: true,
13220 },
13221 window,
13222 cx,
13223 );
13224 });
13225 cx.run_until_parked();
13226 workspace.update_in(cx, |workspace, window, cx| {
13227 workspace.move_item_to_pane_at_index(
13228 &MoveItemToPane {
13229 destination: 3,
13230 focus: true,
13231 clone: true,
13232 },
13233 window,
13234 cx,
13235 );
13236 });
13237 cx.run_until_parked();
13238
13239 workspace.update(cx, |workspace, cx| {
13240 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13241 for pane in workspace.panes() {
13242 assert_eq!(
13243 pane_items_paths(pane, cx),
13244 vec!["first.txt".to_string()],
13245 "Single item exists in all panes"
13246 );
13247 }
13248 });
13249
13250 // verify that the active pane has been updated after waiting for the
13251 // pane focus event to fire and resolve
13252 workspace.read_with(cx, |workspace, _app| {
13253 assert_eq!(
13254 workspace.active_pane(),
13255 &workspace.panes[2],
13256 "The third pane should be the active one: {:?}",
13257 workspace.panes
13258 );
13259 })
13260 }
13261
13262 #[gpui::test]
13263 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13264 init_test(cx);
13265
13266 let fs = FakeFs::new(cx.executor());
13267 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13268
13269 let project = Project::test(fs, ["root".as_ref()], cx).await;
13270 let (workspace, cx) =
13271 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13272
13273 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13274 // Add item to pane A with project path
13275 let item_a = cx.new(|cx| {
13276 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13277 });
13278 workspace.update_in(cx, |workspace, window, cx| {
13279 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13280 });
13281
13282 // Split to create pane B
13283 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13284 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13285 });
13286
13287 // Add item with SAME project path to pane B, and pin it
13288 let item_b = cx.new(|cx| {
13289 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13290 });
13291 pane_b.update_in(cx, |pane, window, cx| {
13292 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13293 pane.set_pinned_count(1);
13294 });
13295
13296 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13297 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13298
13299 // close_pinned: false should only close the unpinned copy
13300 workspace.update_in(cx, |workspace, window, cx| {
13301 workspace.close_item_in_all_panes(
13302 &CloseItemInAllPanes {
13303 save_intent: Some(SaveIntent::Close),
13304 close_pinned: false,
13305 },
13306 window,
13307 cx,
13308 )
13309 });
13310 cx.executor().run_until_parked();
13311
13312 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13313 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13314 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13315 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13316
13317 // Split again, seeing as closing the previous item also closed its
13318 // pane, so only pane remains, which does not allow us to properly test
13319 // that both items close when `close_pinned: true`.
13320 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13321 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13322 });
13323
13324 // Add an item with the same project path to pane C so that
13325 // close_item_in_all_panes can determine what to close across all panes
13326 // (it reads the active item from the active pane, and split_pane
13327 // creates an empty pane).
13328 let item_c = cx.new(|cx| {
13329 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13330 });
13331 pane_c.update_in(cx, |pane, window, cx| {
13332 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13333 });
13334
13335 // close_pinned: true should close the pinned copy too
13336 workspace.update_in(cx, |workspace, window, cx| {
13337 let panes_count = workspace.panes().len();
13338 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13339
13340 workspace.close_item_in_all_panes(
13341 &CloseItemInAllPanes {
13342 save_intent: Some(SaveIntent::Close),
13343 close_pinned: true,
13344 },
13345 window,
13346 cx,
13347 )
13348 });
13349 cx.executor().run_until_parked();
13350
13351 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13352 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13353 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13354 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13355 }
13356
13357 mod register_project_item_tests {
13358
13359 use super::*;
13360
13361 // View
13362 struct TestPngItemView {
13363 focus_handle: FocusHandle,
13364 }
13365 // Model
13366 struct TestPngItem {}
13367
13368 impl project::ProjectItem for TestPngItem {
13369 fn try_open(
13370 _project: &Entity<Project>,
13371 path: &ProjectPath,
13372 cx: &mut App,
13373 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13374 if path.path.extension().unwrap() == "png" {
13375 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13376 } else {
13377 None
13378 }
13379 }
13380
13381 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13382 None
13383 }
13384
13385 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13386 None
13387 }
13388
13389 fn is_dirty(&self) -> bool {
13390 false
13391 }
13392 }
13393
13394 impl Item for TestPngItemView {
13395 type Event = ();
13396 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13397 "".into()
13398 }
13399 }
13400 impl EventEmitter<()> for TestPngItemView {}
13401 impl Focusable for TestPngItemView {
13402 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13403 self.focus_handle.clone()
13404 }
13405 }
13406
13407 impl Render for TestPngItemView {
13408 fn render(
13409 &mut self,
13410 _window: &mut Window,
13411 _cx: &mut Context<Self>,
13412 ) -> impl IntoElement {
13413 Empty
13414 }
13415 }
13416
13417 impl ProjectItem for TestPngItemView {
13418 type Item = TestPngItem;
13419
13420 fn for_project_item(
13421 _project: Entity<Project>,
13422 _pane: Option<&Pane>,
13423 _item: Entity<Self::Item>,
13424 _: &mut Window,
13425 cx: &mut Context<Self>,
13426 ) -> Self
13427 where
13428 Self: Sized,
13429 {
13430 Self {
13431 focus_handle: cx.focus_handle(),
13432 }
13433 }
13434 }
13435
13436 // View
13437 struct TestIpynbItemView {
13438 focus_handle: FocusHandle,
13439 }
13440 // Model
13441 struct TestIpynbItem {}
13442
13443 impl project::ProjectItem for TestIpynbItem {
13444 fn try_open(
13445 _project: &Entity<Project>,
13446 path: &ProjectPath,
13447 cx: &mut App,
13448 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13449 if path.path.extension().unwrap() == "ipynb" {
13450 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13451 } else {
13452 None
13453 }
13454 }
13455
13456 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13457 None
13458 }
13459
13460 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13461 None
13462 }
13463
13464 fn is_dirty(&self) -> bool {
13465 false
13466 }
13467 }
13468
13469 impl Item for TestIpynbItemView {
13470 type Event = ();
13471 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13472 "".into()
13473 }
13474 }
13475 impl EventEmitter<()> for TestIpynbItemView {}
13476 impl Focusable for TestIpynbItemView {
13477 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13478 self.focus_handle.clone()
13479 }
13480 }
13481
13482 impl Render for TestIpynbItemView {
13483 fn render(
13484 &mut self,
13485 _window: &mut Window,
13486 _cx: &mut Context<Self>,
13487 ) -> impl IntoElement {
13488 Empty
13489 }
13490 }
13491
13492 impl ProjectItem for TestIpynbItemView {
13493 type Item = TestIpynbItem;
13494
13495 fn for_project_item(
13496 _project: Entity<Project>,
13497 _pane: Option<&Pane>,
13498 _item: Entity<Self::Item>,
13499 _: &mut Window,
13500 cx: &mut Context<Self>,
13501 ) -> Self
13502 where
13503 Self: Sized,
13504 {
13505 Self {
13506 focus_handle: cx.focus_handle(),
13507 }
13508 }
13509 }
13510
13511 struct TestAlternatePngItemView {
13512 focus_handle: FocusHandle,
13513 }
13514
13515 impl Item for TestAlternatePngItemView {
13516 type Event = ();
13517 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13518 "".into()
13519 }
13520 }
13521
13522 impl EventEmitter<()> for TestAlternatePngItemView {}
13523 impl Focusable for TestAlternatePngItemView {
13524 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13525 self.focus_handle.clone()
13526 }
13527 }
13528
13529 impl Render for TestAlternatePngItemView {
13530 fn render(
13531 &mut self,
13532 _window: &mut Window,
13533 _cx: &mut Context<Self>,
13534 ) -> impl IntoElement {
13535 Empty
13536 }
13537 }
13538
13539 impl ProjectItem for TestAlternatePngItemView {
13540 type Item = TestPngItem;
13541
13542 fn for_project_item(
13543 _project: Entity<Project>,
13544 _pane: Option<&Pane>,
13545 _item: Entity<Self::Item>,
13546 _: &mut Window,
13547 cx: &mut Context<Self>,
13548 ) -> Self
13549 where
13550 Self: Sized,
13551 {
13552 Self {
13553 focus_handle: cx.focus_handle(),
13554 }
13555 }
13556 }
13557
13558 #[gpui::test]
13559 async fn test_register_project_item(cx: &mut TestAppContext) {
13560 init_test(cx);
13561
13562 cx.update(|cx| {
13563 register_project_item::<TestPngItemView>(cx);
13564 register_project_item::<TestIpynbItemView>(cx);
13565 });
13566
13567 let fs = FakeFs::new(cx.executor());
13568 fs.insert_tree(
13569 "/root1",
13570 json!({
13571 "one.png": "BINARYDATAHERE",
13572 "two.ipynb": "{ totally a notebook }",
13573 "three.txt": "editing text, sure why not?"
13574 }),
13575 )
13576 .await;
13577
13578 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13579 let (workspace, cx) =
13580 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13581
13582 let worktree_id = project.update(cx, |project, cx| {
13583 project.worktrees(cx).next().unwrap().read(cx).id()
13584 });
13585
13586 let handle = workspace
13587 .update_in(cx, |workspace, window, cx| {
13588 let project_path = (worktree_id, rel_path("one.png"));
13589 workspace.open_path(project_path, None, true, window, cx)
13590 })
13591 .await
13592 .unwrap();
13593
13594 // Now we can check if the handle we got back errored or not
13595 assert_eq!(
13596 handle.to_any_view().entity_type(),
13597 TypeId::of::<TestPngItemView>()
13598 );
13599
13600 let handle = workspace
13601 .update_in(cx, |workspace, window, cx| {
13602 let project_path = (worktree_id, rel_path("two.ipynb"));
13603 workspace.open_path(project_path, None, true, window, cx)
13604 })
13605 .await
13606 .unwrap();
13607
13608 assert_eq!(
13609 handle.to_any_view().entity_type(),
13610 TypeId::of::<TestIpynbItemView>()
13611 );
13612
13613 let handle = workspace
13614 .update_in(cx, |workspace, window, cx| {
13615 let project_path = (worktree_id, rel_path("three.txt"));
13616 workspace.open_path(project_path, None, true, window, cx)
13617 })
13618 .await;
13619 assert!(handle.is_err());
13620 }
13621
13622 #[gpui::test]
13623 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
13624 init_test(cx);
13625
13626 cx.update(|cx| {
13627 register_project_item::<TestPngItemView>(cx);
13628 register_project_item::<TestAlternatePngItemView>(cx);
13629 });
13630
13631 let fs = FakeFs::new(cx.executor());
13632 fs.insert_tree(
13633 "/root1",
13634 json!({
13635 "one.png": "BINARYDATAHERE",
13636 "two.ipynb": "{ totally a notebook }",
13637 "three.txt": "editing text, sure why not?"
13638 }),
13639 )
13640 .await;
13641 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13642 let (workspace, cx) =
13643 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13644 let worktree_id = project.update(cx, |project, cx| {
13645 project.worktrees(cx).next().unwrap().read(cx).id()
13646 });
13647
13648 let handle = workspace
13649 .update_in(cx, |workspace, window, cx| {
13650 let project_path = (worktree_id, rel_path("one.png"));
13651 workspace.open_path(project_path, None, true, window, cx)
13652 })
13653 .await
13654 .unwrap();
13655
13656 // This _must_ be the second item registered
13657 assert_eq!(
13658 handle.to_any_view().entity_type(),
13659 TypeId::of::<TestAlternatePngItemView>()
13660 );
13661
13662 let handle = workspace
13663 .update_in(cx, |workspace, window, cx| {
13664 let project_path = (worktree_id, rel_path("three.txt"));
13665 workspace.open_path(project_path, None, true, window, cx)
13666 })
13667 .await;
13668 assert!(handle.is_err());
13669 }
13670 }
13671
13672 #[gpui::test]
13673 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13674 init_test(cx);
13675
13676 let fs = FakeFs::new(cx.executor());
13677 let project = Project::test(fs, [], cx).await;
13678 let (workspace, _cx) =
13679 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13680
13681 // Test with status bar shown (default)
13682 workspace.read_with(cx, |workspace, cx| {
13683 let visible = workspace.status_bar_visible(cx);
13684 assert!(visible, "Status bar should be visible by default");
13685 });
13686
13687 // Test with status bar hidden
13688 cx.update_global(|store: &mut SettingsStore, cx| {
13689 store.update_user_settings(cx, |settings| {
13690 settings.status_bar.get_or_insert_default().show = Some(false);
13691 });
13692 });
13693
13694 workspace.read_with(cx, |workspace, cx| {
13695 let visible = workspace.status_bar_visible(cx);
13696 assert!(!visible, "Status bar should be hidden when show is false");
13697 });
13698
13699 // Test with status bar shown explicitly
13700 cx.update_global(|store: &mut SettingsStore, cx| {
13701 store.update_user_settings(cx, |settings| {
13702 settings.status_bar.get_or_insert_default().show = Some(true);
13703 });
13704 });
13705
13706 workspace.read_with(cx, |workspace, cx| {
13707 let visible = workspace.status_bar_visible(cx);
13708 assert!(visible, "Status bar should be visible when show is true");
13709 });
13710 }
13711
13712 #[gpui::test]
13713 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13714 init_test(cx);
13715
13716 let fs = FakeFs::new(cx.executor());
13717 let project = Project::test(fs, [], cx).await;
13718 let (multi_workspace, cx) =
13719 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13720 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13721 let panel = workspace.update_in(cx, |workspace, window, cx| {
13722 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13723 workspace.add_panel(panel.clone(), window, cx);
13724
13725 workspace
13726 .right_dock()
13727 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13728
13729 panel
13730 });
13731
13732 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13733 let item_a = cx.new(TestItem::new);
13734 let item_b = cx.new(TestItem::new);
13735 let item_a_id = item_a.entity_id();
13736 let item_b_id = item_b.entity_id();
13737
13738 pane.update_in(cx, |pane, window, cx| {
13739 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13740 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13741 });
13742
13743 pane.read_with(cx, |pane, _| {
13744 assert_eq!(pane.items_len(), 2);
13745 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13746 });
13747
13748 workspace.update_in(cx, |workspace, window, cx| {
13749 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13750 });
13751
13752 workspace.update_in(cx, |_, window, cx| {
13753 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13754 });
13755
13756 // Assert that the `pane::CloseActiveItem` action is handled at the
13757 // workspace level when one of the dock panels is focused and, in that
13758 // case, the center pane's active item is closed but the focus is not
13759 // moved.
13760 cx.dispatch_action(pane::CloseActiveItem::default());
13761 cx.run_until_parked();
13762
13763 pane.read_with(cx, |pane, _| {
13764 assert_eq!(pane.items_len(), 1);
13765 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13766 });
13767
13768 workspace.update_in(cx, |workspace, window, cx| {
13769 assert!(workspace.right_dock().read(cx).is_open());
13770 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13771 });
13772 }
13773
13774 #[gpui::test]
13775 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13776 init_test(cx);
13777 let fs = FakeFs::new(cx.executor());
13778
13779 let project_a = Project::test(fs.clone(), [], cx).await;
13780 let project_b = Project::test(fs, [], cx).await;
13781
13782 let multi_workspace_handle =
13783 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13784 cx.run_until_parked();
13785
13786 let workspace_a = multi_workspace_handle
13787 .read_with(cx, |mw, _| mw.workspace().clone())
13788 .unwrap();
13789
13790 let _workspace_b = multi_workspace_handle
13791 .update(cx, |mw, window, cx| {
13792 mw.test_add_workspace(project_b, window, cx)
13793 })
13794 .unwrap();
13795
13796 // Switch to workspace A
13797 multi_workspace_handle
13798 .update(cx, |mw, window, cx| {
13799 mw.activate_index(0, window, cx);
13800 })
13801 .unwrap();
13802
13803 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13804
13805 // Add a panel to workspace A's right dock and open the dock
13806 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13807 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13808 workspace.add_panel(panel.clone(), window, cx);
13809 workspace
13810 .right_dock()
13811 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13812 panel
13813 });
13814
13815 // Focus the panel through the workspace (matching existing test pattern)
13816 workspace_a.update_in(cx, |workspace, window, cx| {
13817 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13818 });
13819
13820 // Zoom the panel
13821 panel.update_in(cx, |panel, window, cx| {
13822 panel.set_zoomed(true, window, cx);
13823 });
13824
13825 // Verify the panel is zoomed and the dock is open
13826 workspace_a.update_in(cx, |workspace, window, cx| {
13827 assert!(
13828 workspace.right_dock().read(cx).is_open(),
13829 "dock should be open before switch"
13830 );
13831 assert!(
13832 panel.is_zoomed(window, cx),
13833 "panel should be zoomed before switch"
13834 );
13835 assert!(
13836 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13837 "panel should be focused before switch"
13838 );
13839 });
13840
13841 // Switch to workspace B
13842 multi_workspace_handle
13843 .update(cx, |mw, window, cx| {
13844 mw.activate_index(1, window, cx);
13845 })
13846 .unwrap();
13847 cx.run_until_parked();
13848
13849 // Switch back to workspace A
13850 multi_workspace_handle
13851 .update(cx, |mw, window, cx| {
13852 mw.activate_index(0, window, cx);
13853 })
13854 .unwrap();
13855 cx.run_until_parked();
13856
13857 // Verify the panel is still zoomed and the dock is still open
13858 workspace_a.update_in(cx, |workspace, window, cx| {
13859 assert!(
13860 workspace.right_dock().read(cx).is_open(),
13861 "dock should still be open after switching back"
13862 );
13863 assert!(
13864 panel.is_zoomed(window, cx),
13865 "panel should still be zoomed after switching back"
13866 );
13867 });
13868 }
13869
13870 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13871 pane.read(cx)
13872 .items()
13873 .flat_map(|item| {
13874 item.project_paths(cx)
13875 .into_iter()
13876 .map(|path| path.path.display(PathStyle::local()).into_owned())
13877 })
13878 .collect()
13879 }
13880
13881 pub fn init_test(cx: &mut TestAppContext) {
13882 cx.update(|cx| {
13883 let settings_store = SettingsStore::test(cx);
13884 cx.set_global(settings_store);
13885 theme::init(theme::LoadThemes::JustBase, cx);
13886 });
13887 }
13888
13889 #[gpui::test]
13890 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
13891 use settings::{ThemeName, ThemeSelection};
13892 use theme::SystemAppearance;
13893 use zed_actions::theme::ToggleMode;
13894
13895 init_test(cx);
13896
13897 let fs = FakeFs::new(cx.executor());
13898 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
13899
13900 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
13901 .await;
13902
13903 // Build a test project and workspace view so the test can invoke
13904 // the workspace action handler the same way the UI would.
13905 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
13906 let (workspace, cx) =
13907 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13908
13909 // Seed the settings file with a plain static light theme so the
13910 // first toggle always starts from a known persisted state.
13911 workspace.update_in(cx, |_workspace, _window, cx| {
13912 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
13913 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
13914 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
13915 });
13916 });
13917 cx.executor().advance_clock(Duration::from_millis(200));
13918 cx.run_until_parked();
13919
13920 // Confirm the initial persisted settings contain the static theme
13921 // we just wrote before any toggling happens.
13922 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13923 assert!(settings_text.contains(r#""theme": "One Light""#));
13924
13925 // Toggle once. This should migrate the persisted theme settings
13926 // into light/dark slots and enable system mode.
13927 workspace.update_in(cx, |workspace, window, cx| {
13928 workspace.toggle_theme_mode(&ToggleMode, window, cx);
13929 });
13930 cx.executor().advance_clock(Duration::from_millis(200));
13931 cx.run_until_parked();
13932
13933 // 1. Static -> Dynamic
13934 // this assertion checks theme changed from static to dynamic.
13935 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13936 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
13937 assert_eq!(
13938 parsed["theme"],
13939 serde_json::json!({
13940 "mode": "system",
13941 "light": "One Light",
13942 "dark": "One Dark"
13943 })
13944 );
13945
13946 // 2. Toggle again, suppose it will change the mode to light
13947 workspace.update_in(cx, |workspace, window, cx| {
13948 workspace.toggle_theme_mode(&ToggleMode, window, cx);
13949 });
13950 cx.executor().advance_clock(Duration::from_millis(200));
13951 cx.run_until_parked();
13952
13953 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13954 assert!(settings_text.contains(r#""mode": "light""#));
13955 }
13956
13957 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13958 let item = TestProjectItem::new(id, path, cx);
13959 item.update(cx, |item, _| {
13960 item.is_dirty = true;
13961 });
13962 item
13963 }
13964
13965 #[gpui::test]
13966 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13967 cx: &mut gpui::TestAppContext,
13968 ) {
13969 init_test(cx);
13970 let fs = FakeFs::new(cx.executor());
13971
13972 let project = Project::test(fs, [], cx).await;
13973 let (workspace, cx) =
13974 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13975
13976 let panel = workspace.update_in(cx, |workspace, window, cx| {
13977 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13978 workspace.add_panel(panel.clone(), window, cx);
13979 workspace
13980 .right_dock()
13981 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13982 panel
13983 });
13984
13985 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13986 pane.update_in(cx, |pane, window, cx| {
13987 let item = cx.new(TestItem::new);
13988 pane.add_item(Box::new(item), true, true, None, window, cx);
13989 });
13990
13991 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13992 // mirrors the real-world flow and avoids side effects from directly
13993 // focusing the panel while the center pane is active.
13994 workspace.update_in(cx, |workspace, window, cx| {
13995 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13996 });
13997
13998 panel.update_in(cx, |panel, window, cx| {
13999 panel.set_zoomed(true, window, cx);
14000 });
14001
14002 workspace.update_in(cx, |workspace, window, cx| {
14003 assert!(workspace.right_dock().read(cx).is_open());
14004 assert!(panel.is_zoomed(window, cx));
14005 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14006 });
14007
14008 // Simulate a spurious pane::Event::Focus on the center pane while the
14009 // panel still has focus. This mirrors what happens during macOS window
14010 // activation: the center pane fires a focus event even though actual
14011 // focus remains on the dock panel.
14012 pane.update_in(cx, |_, _, cx| {
14013 cx.emit(pane::Event::Focus);
14014 });
14015
14016 // The dock must remain open because the panel had focus at the time the
14017 // event was processed. Before the fix, dock_to_preserve was None for
14018 // panels that don't implement pane(), causing the dock to close.
14019 workspace.update_in(cx, |workspace, window, cx| {
14020 assert!(
14021 workspace.right_dock().read(cx).is_open(),
14022 "Dock should stay open when its zoomed panel (without pane()) still has focus"
14023 );
14024 assert!(panel.is_zoomed(window, cx));
14025 });
14026 }
14027}