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, Sidebar, SidebarEvent,
32 SidebarHandle, ToggleWorkspaceSidebar,
33};
34pub use path_list::{PathList, SerializedPathList};
35pub use toast_layer::{ToastAction, ToastLayer, ToastView};
36
37use anyhow::{Context as _, Result, anyhow};
38use client::{
39 ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
40 proto::{self, ErrorCode, PanelId, PeerId},
41};
42use collections::{HashMap, HashSet, hash_map};
43use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
44use fs::Fs;
45use futures::{
46 Future, FutureExt, StreamExt,
47 channel::{
48 mpsc::{self, UnboundedReceiver, UnboundedSender},
49 oneshot,
50 },
51 future::{Shared, try_join_all},
52};
53use gpui::{
54 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
55 CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
56 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
57 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
58 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
59 WindowOptions, actions, canvas, point, relative, size, transparent_black,
60};
61pub use history_manager::*;
62pub use item::{
63 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
64 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
65};
66use itertools::Itertools;
67use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
68pub use modal_layer::*;
69use node_runtime::NodeRuntime;
70use notifications::{
71 DetachAndPromptErr, Notifications, dismiss_app_notification,
72 simple_message_notification::MessageNotification,
73};
74pub use pane::*;
75pub use pane_group::{
76 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
77 SplitDirection,
78};
79use persistence::{DB, SerializedWindowBounds, model::SerializedWorkspace};
80pub use persistence::{
81 DB as WORKSPACE_DB, WorkspaceDb, delete_unloaded_items,
82 model::{
83 DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
84 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};
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 (window, _) = task.await?;
663 window.update(cx, |multi_workspace, window, cx| {
664 window.activate_window();
665 let workspace = multi_workspace.workspace().clone();
666 workspace.update(cx, |workspace, cx| {
667 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
668 });
669 })?;
670 anyhow::Ok(())
671 })
672 .detach_and_log_err(cx);
673 }
674}
675
676pub fn prompt_for_open_path_and_open(
677 workspace: &mut Workspace,
678 app_state: Arc<AppState>,
679 options: PathPromptOptions,
680 create_new_window: bool,
681 window: &mut Window,
682 cx: &mut Context<Workspace>,
683) {
684 let paths = workspace.prompt_for_open_path(
685 options,
686 DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
687 window,
688 cx,
689 );
690 let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
691 cx.spawn_in(window, async move |this, cx| {
692 let Some(paths) = paths.await.log_err().flatten() else {
693 return;
694 };
695 if !create_new_window {
696 if let Some(handle) = multi_workspace_handle {
697 if let Some(task) = handle
698 .update(cx, |multi_workspace, window, cx| {
699 multi_workspace.open_project(paths, window, cx)
700 })
701 .log_err()
702 {
703 task.await.log_err();
704 }
705 return;
706 }
707 }
708 if let Some(task) = this
709 .update_in(cx, |this, window, cx| {
710 this.open_workspace_for_paths(false, paths, window, cx)
711 })
712 .log_err()
713 {
714 task.await.log_err();
715 }
716 })
717 .detach();
718}
719
720pub fn init(app_state: Arc<AppState>, cx: &mut App) {
721 component::init();
722 theme_preview::init(cx);
723 toast_layer::init(cx);
724 history_manager::init(app_state.fs.clone(), cx);
725
726 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
727 .on_action(|_: &Reload, cx| reload(cx))
728 .on_action({
729 let app_state = Arc::downgrade(&app_state);
730 move |_: &Open, cx: &mut App| {
731 if let Some(app_state) = app_state.upgrade() {
732 prompt_and_open_paths(
733 app_state,
734 PathPromptOptions {
735 files: true,
736 directories: true,
737 multiple: true,
738 prompt: None,
739 },
740 cx,
741 );
742 }
743 }
744 })
745 .on_action({
746 let app_state = Arc::downgrade(&app_state);
747 move |_: &OpenFiles, cx: &mut App| {
748 let directories = cx.can_select_mixed_files_and_dirs();
749 if let Some(app_state) = app_state.upgrade() {
750 prompt_and_open_paths(
751 app_state,
752 PathPromptOptions {
753 files: true,
754 directories,
755 multiple: true,
756 prompt: None,
757 },
758 cx,
759 );
760 }
761 }
762 });
763}
764
765type BuildProjectItemFn =
766 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
767
768type BuildProjectItemForPathFn =
769 fn(
770 &Entity<Project>,
771 &ProjectPath,
772 &mut Window,
773 &mut App,
774 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
775
776#[derive(Clone, Default)]
777struct ProjectItemRegistry {
778 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
779 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
780}
781
782impl ProjectItemRegistry {
783 fn register<T: ProjectItem>(&mut self) {
784 self.build_project_item_fns_by_type.insert(
785 TypeId::of::<T::Item>(),
786 |item, project, pane, window, cx| {
787 let item = item.downcast().unwrap();
788 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
789 as Box<dyn ItemHandle>
790 },
791 );
792 self.build_project_item_for_path_fns
793 .push(|project, project_path, window, cx| {
794 let project_path = project_path.clone();
795 let is_file = project
796 .read(cx)
797 .entry_for_path(&project_path, cx)
798 .is_some_and(|entry| entry.is_file());
799 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
800 let is_local = project.read(cx).is_local();
801 let project_item =
802 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
803 let project = project.clone();
804 Some(window.spawn(cx, async move |cx| {
805 match project_item.await.with_context(|| {
806 format!(
807 "opening project path {:?}",
808 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
809 )
810 }) {
811 Ok(project_item) => {
812 let project_item = project_item;
813 let project_entry_id: Option<ProjectEntryId> =
814 project_item.read_with(cx, project::ProjectItem::entry_id);
815 let build_workspace_item = Box::new(
816 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
817 Box::new(cx.new(|cx| {
818 T::for_project_item(
819 project,
820 Some(pane),
821 project_item,
822 window,
823 cx,
824 )
825 })) as Box<dyn ItemHandle>
826 },
827 ) as Box<_>;
828 Ok((project_entry_id, build_workspace_item))
829 }
830 Err(e) => {
831 log::warn!("Failed to open a project item: {e:#}");
832 if e.error_code() == ErrorCode::Internal {
833 if let Some(abs_path) =
834 entry_abs_path.as_deref().filter(|_| is_file)
835 {
836 if let Some(broken_project_item_view) =
837 cx.update(|window, cx| {
838 T::for_broken_project_item(
839 abs_path, is_local, &e, window, cx,
840 )
841 })?
842 {
843 let build_workspace_item = Box::new(
844 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
845 cx.new(|_| broken_project_item_view).boxed_clone()
846 },
847 )
848 as Box<_>;
849 return Ok((None, build_workspace_item));
850 }
851 }
852 }
853 Err(e)
854 }
855 }
856 }))
857 });
858 }
859
860 fn open_path(
861 &self,
862 project: &Entity<Project>,
863 path: &ProjectPath,
864 window: &mut Window,
865 cx: &mut App,
866 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
867 let Some(open_project_item) = self
868 .build_project_item_for_path_fns
869 .iter()
870 .rev()
871 .find_map(|open_project_item| open_project_item(project, path, window, cx))
872 else {
873 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
874 };
875 open_project_item
876 }
877
878 fn build_item<T: project::ProjectItem>(
879 &self,
880 item: Entity<T>,
881 project: Entity<Project>,
882 pane: Option<&Pane>,
883 window: &mut Window,
884 cx: &mut App,
885 ) -> Option<Box<dyn ItemHandle>> {
886 let build = self
887 .build_project_item_fns_by_type
888 .get(&TypeId::of::<T>())?;
889 Some(build(item.into_any(), project, pane, window, cx))
890 }
891}
892
893type WorkspaceItemBuilder =
894 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
895
896impl Global for ProjectItemRegistry {}
897
898/// Registers a [ProjectItem] for the app. When opening a file, all the registered
899/// items will get a chance to open the file, starting from the project item that
900/// was added last.
901pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
902 cx.default_global::<ProjectItemRegistry>().register::<I>();
903}
904
905#[derive(Default)]
906pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
907
908struct FollowableViewDescriptor {
909 from_state_proto: fn(
910 Entity<Workspace>,
911 ViewId,
912 &mut Option<proto::view::Variant>,
913 &mut Window,
914 &mut App,
915 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
916 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
917}
918
919impl Global for FollowableViewRegistry {}
920
921impl FollowableViewRegistry {
922 pub fn register<I: FollowableItem>(cx: &mut App) {
923 cx.default_global::<Self>().0.insert(
924 TypeId::of::<I>(),
925 FollowableViewDescriptor {
926 from_state_proto: |workspace, id, state, window, cx| {
927 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
928 cx.foreground_executor()
929 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
930 })
931 },
932 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
933 },
934 );
935 }
936
937 pub fn from_state_proto(
938 workspace: Entity<Workspace>,
939 view_id: ViewId,
940 mut state: Option<proto::view::Variant>,
941 window: &mut Window,
942 cx: &mut App,
943 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
944 cx.update_default_global(|this: &mut Self, cx| {
945 this.0.values().find_map(|descriptor| {
946 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
947 })
948 })
949 }
950
951 pub fn to_followable_view(
952 view: impl Into<AnyView>,
953 cx: &App,
954 ) -> Option<Box<dyn FollowableItemHandle>> {
955 let this = cx.try_global::<Self>()?;
956 let view = view.into();
957 let descriptor = this.0.get(&view.entity_type())?;
958 Some((descriptor.to_followable_view)(&view))
959 }
960}
961
962#[derive(Copy, Clone)]
963struct SerializableItemDescriptor {
964 deserialize: fn(
965 Entity<Project>,
966 WeakEntity<Workspace>,
967 WorkspaceId,
968 ItemId,
969 &mut Window,
970 &mut Context<Pane>,
971 ) -> Task<Result<Box<dyn ItemHandle>>>,
972 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
973 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
974}
975
976#[derive(Default)]
977struct SerializableItemRegistry {
978 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
979 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
980}
981
982impl Global for SerializableItemRegistry {}
983
984impl SerializableItemRegistry {
985 fn deserialize(
986 item_kind: &str,
987 project: Entity<Project>,
988 workspace: WeakEntity<Workspace>,
989 workspace_id: WorkspaceId,
990 item_item: ItemId,
991 window: &mut Window,
992 cx: &mut Context<Pane>,
993 ) -> Task<Result<Box<dyn ItemHandle>>> {
994 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
995 return Task::ready(Err(anyhow!(
996 "cannot deserialize {}, descriptor not found",
997 item_kind
998 )));
999 };
1000
1001 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
1002 }
1003
1004 fn cleanup(
1005 item_kind: &str,
1006 workspace_id: WorkspaceId,
1007 loaded_items: Vec<ItemId>,
1008 window: &mut Window,
1009 cx: &mut App,
1010 ) -> Task<Result<()>> {
1011 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1012 return Task::ready(Err(anyhow!(
1013 "cannot cleanup {}, descriptor not found",
1014 item_kind
1015 )));
1016 };
1017
1018 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
1019 }
1020
1021 fn view_to_serializable_item_handle(
1022 view: AnyView,
1023 cx: &App,
1024 ) -> Option<Box<dyn SerializableItemHandle>> {
1025 let this = cx.try_global::<Self>()?;
1026 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
1027 Some((descriptor.view_to_serializable_item)(view))
1028 }
1029
1030 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
1031 let this = cx.try_global::<Self>()?;
1032 this.descriptors_by_kind.get(item_kind).copied()
1033 }
1034}
1035
1036pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
1037 let serialized_item_kind = I::serialized_item_kind();
1038
1039 let registry = cx.default_global::<SerializableItemRegistry>();
1040 let descriptor = SerializableItemDescriptor {
1041 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
1042 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
1043 cx.foreground_executor()
1044 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
1045 },
1046 cleanup: |workspace_id, loaded_items, window, cx| {
1047 I::cleanup(workspace_id, loaded_items, window, cx)
1048 },
1049 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
1050 };
1051 registry
1052 .descriptors_by_kind
1053 .insert(Arc::from(serialized_item_kind), descriptor);
1054 registry
1055 .descriptors_by_type
1056 .insert(TypeId::of::<I>(), descriptor);
1057}
1058
1059pub struct AppState {
1060 pub languages: Arc<LanguageRegistry>,
1061 pub client: Arc<Client>,
1062 pub user_store: Entity<UserStore>,
1063 pub workspace_store: Entity<WorkspaceStore>,
1064 pub fs: Arc<dyn fs::Fs>,
1065 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1066 pub node_runtime: NodeRuntime,
1067 pub session: Entity<AppSession>,
1068}
1069
1070struct GlobalAppState(Weak<AppState>);
1071
1072impl Global for GlobalAppState {}
1073
1074pub struct WorkspaceStore {
1075 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1076 client: Arc<Client>,
1077 _subscriptions: Vec<client::Subscription>,
1078}
1079
1080#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1081pub enum CollaboratorId {
1082 PeerId(PeerId),
1083 Agent,
1084}
1085
1086impl From<PeerId> for CollaboratorId {
1087 fn from(peer_id: PeerId) -> Self {
1088 CollaboratorId::PeerId(peer_id)
1089 }
1090}
1091
1092impl From<&PeerId> for CollaboratorId {
1093 fn from(peer_id: &PeerId) -> Self {
1094 CollaboratorId::PeerId(*peer_id)
1095 }
1096}
1097
1098#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1099struct Follower {
1100 project_id: Option<u64>,
1101 peer_id: PeerId,
1102}
1103
1104impl AppState {
1105 #[track_caller]
1106 pub fn global(cx: &App) -> Weak<Self> {
1107 cx.global::<GlobalAppState>().0.clone()
1108 }
1109 pub fn try_global(cx: &App) -> Option<Weak<Self>> {
1110 cx.try_global::<GlobalAppState>()
1111 .map(|state| state.0.clone())
1112 }
1113 pub fn set_global(state: Weak<AppState>, cx: &mut App) {
1114 cx.set_global(GlobalAppState(state));
1115 }
1116
1117 #[cfg(any(test, feature = "test-support"))]
1118 pub fn test(cx: &mut App) -> Arc<Self> {
1119 use fs::Fs;
1120 use node_runtime::NodeRuntime;
1121 use session::Session;
1122 use settings::SettingsStore;
1123
1124 if !cx.has_global::<SettingsStore>() {
1125 let settings_store = SettingsStore::test(cx);
1126 cx.set_global(settings_store);
1127 }
1128
1129 let fs = fs::FakeFs::new(cx.background_executor().clone());
1130 <dyn Fs>::set_global(fs.clone(), cx);
1131 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1132 let clock = Arc::new(clock::FakeSystemClock::new());
1133 let http_client = http_client::FakeHttpClient::with_404_response();
1134 let client = Client::new(clock, http_client, cx);
1135 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1136 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1137 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1138
1139 theme::init(theme::LoadThemes::JustBase, cx);
1140 client::init(&client, cx);
1141
1142 Arc::new(Self {
1143 client,
1144 fs,
1145 languages,
1146 user_store,
1147 workspace_store,
1148 node_runtime: NodeRuntime::unavailable(),
1149 build_window_options: |_, _| Default::default(),
1150 session,
1151 })
1152 }
1153}
1154
1155struct DelayedDebouncedEditAction {
1156 task: Option<Task<()>>,
1157 cancel_channel: Option<oneshot::Sender<()>>,
1158}
1159
1160impl DelayedDebouncedEditAction {
1161 fn new() -> DelayedDebouncedEditAction {
1162 DelayedDebouncedEditAction {
1163 task: None,
1164 cancel_channel: None,
1165 }
1166 }
1167
1168 fn fire_new<F>(
1169 &mut self,
1170 delay: Duration,
1171 window: &mut Window,
1172 cx: &mut Context<Workspace>,
1173 func: F,
1174 ) where
1175 F: 'static
1176 + Send
1177 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1178 {
1179 if let Some(channel) = self.cancel_channel.take() {
1180 _ = channel.send(());
1181 }
1182
1183 let (sender, mut receiver) = oneshot::channel::<()>();
1184 self.cancel_channel = Some(sender);
1185
1186 let previous_task = self.task.take();
1187 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1188 let mut timer = cx.background_executor().timer(delay).fuse();
1189 if let Some(previous_task) = previous_task {
1190 previous_task.await;
1191 }
1192
1193 futures::select_biased! {
1194 _ = receiver => return,
1195 _ = timer => {}
1196 }
1197
1198 if let Some(result) = workspace
1199 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1200 .log_err()
1201 {
1202 result.await.log_err();
1203 }
1204 }));
1205 }
1206}
1207
1208pub enum Event {
1209 PaneAdded(Entity<Pane>),
1210 PaneRemoved,
1211 ItemAdded {
1212 item: Box<dyn ItemHandle>,
1213 },
1214 ActiveItemChanged,
1215 ItemRemoved {
1216 item_id: EntityId,
1217 },
1218 UserSavedItem {
1219 pane: WeakEntity<Pane>,
1220 item: Box<dyn WeakItemHandle>,
1221 save_intent: SaveIntent,
1222 },
1223 ContactRequestedJoin(u64),
1224 WorkspaceCreated(WeakEntity<Workspace>),
1225 OpenBundledFile {
1226 text: Cow<'static, str>,
1227 title: &'static str,
1228 language: &'static str,
1229 },
1230 ZoomChanged,
1231 ModalOpened,
1232 Activate,
1233 PanelAdded(AnyView),
1234}
1235
1236#[derive(Debug, Clone)]
1237pub enum OpenVisible {
1238 All,
1239 None,
1240 OnlyFiles,
1241 OnlyDirectories,
1242}
1243
1244enum WorkspaceLocation {
1245 // Valid local paths or SSH project to serialize
1246 Location(SerializedWorkspaceLocation, PathList),
1247 // No valid location found hence clear session id
1248 DetachFromSession,
1249 // No valid location found to serialize
1250 None,
1251}
1252
1253type PromptForNewPath = Box<
1254 dyn Fn(
1255 &mut Workspace,
1256 DirectoryLister,
1257 Option<String>,
1258 &mut Window,
1259 &mut Context<Workspace>,
1260 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1261>;
1262
1263type PromptForOpenPath = Box<
1264 dyn Fn(
1265 &mut Workspace,
1266 DirectoryLister,
1267 &mut Window,
1268 &mut Context<Workspace>,
1269 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1270>;
1271
1272#[derive(Default)]
1273struct DispatchingKeystrokes {
1274 dispatched: HashSet<Vec<Keystroke>>,
1275 queue: VecDeque<Keystroke>,
1276 task: Option<Shared<Task<()>>>,
1277}
1278
1279/// Collects everything project-related for a certain window opened.
1280/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1281///
1282/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1283/// The `Workspace` owns everybody's state and serves as a default, "global context",
1284/// that can be used to register a global action to be triggered from any place in the window.
1285pub struct Workspace {
1286 weak_self: WeakEntity<Self>,
1287 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1288 zoomed: Option<AnyWeakView>,
1289 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1290 zoomed_position: Option<DockPosition>,
1291 center: PaneGroup,
1292 left_dock: Entity<Dock>,
1293 bottom_dock: Entity<Dock>,
1294 right_dock: Entity<Dock>,
1295 panes: Vec<Entity<Pane>>,
1296 active_worktree_override: Option<WorktreeId>,
1297 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1298 active_pane: Entity<Pane>,
1299 last_active_center_pane: Option<WeakEntity<Pane>>,
1300 last_active_view_id: Option<proto::ViewId>,
1301 status_bar: Entity<StatusBar>,
1302 pub(crate) modal_layer: Entity<ModalLayer>,
1303 toast_layer: Entity<ToastLayer>,
1304 titlebar_item: Option<AnyView>,
1305 notifications: Notifications,
1306 suppressed_notifications: HashSet<NotificationId>,
1307 project: Entity<Project>,
1308 follower_states: HashMap<CollaboratorId, FollowerState>,
1309 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1310 window_edited: bool,
1311 last_window_title: Option<String>,
1312 dirty_items: HashMap<EntityId, Subscription>,
1313 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1314 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1315 database_id: Option<WorkspaceId>,
1316 app_state: Arc<AppState>,
1317 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1318 _subscriptions: Vec<Subscription>,
1319 _apply_leader_updates: Task<Result<()>>,
1320 _observe_current_user: Task<Result<()>>,
1321 _schedule_serialize_workspace: Option<Task<()>>,
1322 _serialize_workspace_task: Option<Task<()>>,
1323 _schedule_serialize_ssh_paths: Option<Task<()>>,
1324 pane_history_timestamp: Arc<AtomicUsize>,
1325 bounds: Bounds<Pixels>,
1326 pub centered_layout: bool,
1327 bounds_save_task_queued: Option<Task<()>>,
1328 on_prompt_for_new_path: Option<PromptForNewPath>,
1329 on_prompt_for_open_path: Option<PromptForOpenPath>,
1330 terminal_provider: Option<Box<dyn TerminalProvider>>,
1331 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1332 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1333 _items_serializer: Task<Result<()>>,
1334 session_id: Option<String>,
1335 scheduled_tasks: Vec<Task<()>>,
1336 last_open_dock_positions: Vec<DockPosition>,
1337 removing: bool,
1338 _panels_task: Option<Task<Result<()>>>,
1339}
1340
1341impl EventEmitter<Event> for Workspace {}
1342
1343#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1344pub struct ViewId {
1345 pub creator: CollaboratorId,
1346 pub id: u64,
1347}
1348
1349pub struct FollowerState {
1350 center_pane: Entity<Pane>,
1351 dock_pane: Option<Entity<Pane>>,
1352 active_view_id: Option<ViewId>,
1353 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1354}
1355
1356struct FollowerView {
1357 view: Box<dyn FollowableItemHandle>,
1358 location: Option<proto::PanelId>,
1359}
1360
1361impl Workspace {
1362 pub fn new(
1363 workspace_id: Option<WorkspaceId>,
1364 project: Entity<Project>,
1365 app_state: Arc<AppState>,
1366 window: &mut Window,
1367 cx: &mut Context<Self>,
1368 ) -> Self {
1369 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1370 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1371 if let TrustedWorktreesEvent::Trusted(..) = e {
1372 // Do not persist auto trusted worktrees
1373 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1374 worktrees_store.update(cx, |worktrees_store, cx| {
1375 worktrees_store.schedule_serialization(
1376 cx,
1377 |new_trusted_worktrees, cx| {
1378 let timeout =
1379 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1380 cx.background_spawn(async move {
1381 timeout.await;
1382 persistence::DB
1383 .save_trusted_worktrees(new_trusted_worktrees)
1384 .await
1385 .log_err();
1386 })
1387 },
1388 )
1389 });
1390 }
1391 }
1392 })
1393 .detach();
1394
1395 cx.observe_global::<SettingsStore>(|_, cx| {
1396 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1397 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1398 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1399 trusted_worktrees.auto_trust_all(cx);
1400 })
1401 }
1402 }
1403 })
1404 .detach();
1405 }
1406
1407 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1408 match event {
1409 project::Event::RemoteIdChanged(_) => {
1410 this.update_window_title(window, cx);
1411 }
1412
1413 project::Event::CollaboratorLeft(peer_id) => {
1414 this.collaborator_left(*peer_id, window, cx);
1415 }
1416
1417 &project::Event::WorktreeRemoved(id) | &project::Event::WorktreeAdded(id) => {
1418 this.update_window_title(window, cx);
1419 if this
1420 .project()
1421 .read(cx)
1422 .worktree_for_id(id, cx)
1423 .is_some_and(|wt| wt.read(cx).is_visible())
1424 {
1425 this.serialize_workspace(window, cx);
1426 this.update_history(cx);
1427 }
1428 }
1429 project::Event::WorktreeUpdatedEntries(..) => {
1430 this.update_window_title(window, cx);
1431 this.serialize_workspace(window, cx);
1432 }
1433
1434 project::Event::DisconnectedFromHost => {
1435 this.update_window_edited(window, cx);
1436 let leaders_to_unfollow =
1437 this.follower_states.keys().copied().collect::<Vec<_>>();
1438 for leader_id in leaders_to_unfollow {
1439 this.unfollow(leader_id, window, cx);
1440 }
1441 }
1442
1443 project::Event::DisconnectedFromRemote {
1444 server_not_running: _,
1445 } => {
1446 this.update_window_edited(window, cx);
1447 }
1448
1449 project::Event::Closed => {
1450 window.remove_window();
1451 }
1452
1453 project::Event::DeletedEntry(_, entry_id) => {
1454 for pane in this.panes.iter() {
1455 pane.update(cx, |pane, cx| {
1456 pane.handle_deleted_project_item(*entry_id, window, cx)
1457 });
1458 }
1459 }
1460
1461 project::Event::Toast {
1462 notification_id,
1463 message,
1464 link,
1465 } => this.show_notification(
1466 NotificationId::named(notification_id.clone()),
1467 cx,
1468 |cx| {
1469 let mut notification = MessageNotification::new(message.clone(), cx);
1470 if let Some(link) = link {
1471 notification = notification
1472 .more_info_message(link.label)
1473 .more_info_url(link.url);
1474 }
1475
1476 cx.new(|_| notification)
1477 },
1478 ),
1479
1480 project::Event::HideToast { notification_id } => {
1481 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1482 }
1483
1484 project::Event::LanguageServerPrompt(request) => {
1485 struct LanguageServerPrompt;
1486
1487 this.show_notification(
1488 NotificationId::composite::<LanguageServerPrompt>(request.id),
1489 cx,
1490 |cx| {
1491 cx.new(|cx| {
1492 notifications::LanguageServerPrompt::new(request.clone(), cx)
1493 })
1494 },
1495 );
1496 }
1497
1498 project::Event::AgentLocationChanged => {
1499 this.handle_agent_location_changed(window, cx)
1500 }
1501
1502 _ => {}
1503 }
1504 cx.notify()
1505 })
1506 .detach();
1507
1508 cx.subscribe_in(
1509 &project.read(cx).breakpoint_store(),
1510 window,
1511 |workspace, _, event, window, cx| match event {
1512 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1513 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1514 workspace.serialize_workspace(window, cx);
1515 }
1516 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1517 },
1518 )
1519 .detach();
1520 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1521 cx.subscribe_in(
1522 &toolchain_store,
1523 window,
1524 |workspace, _, event, window, cx| match event {
1525 ToolchainStoreEvent::CustomToolchainsModified => {
1526 workspace.serialize_workspace(window, cx);
1527 }
1528 _ => {}
1529 },
1530 )
1531 .detach();
1532 }
1533
1534 cx.on_focus_lost(window, |this, window, cx| {
1535 let focus_handle = this.focus_handle(cx);
1536 window.focus(&focus_handle, cx);
1537 })
1538 .detach();
1539
1540 let weak_handle = cx.entity().downgrade();
1541 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1542
1543 let center_pane = cx.new(|cx| {
1544 let mut center_pane = Pane::new(
1545 weak_handle.clone(),
1546 project.clone(),
1547 pane_history_timestamp.clone(),
1548 None,
1549 NewFile.boxed_clone(),
1550 true,
1551 window,
1552 cx,
1553 );
1554 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1555 center_pane.set_should_display_welcome_page(true);
1556 center_pane
1557 });
1558 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1559 .detach();
1560
1561 window.focus(¢er_pane.focus_handle(cx), cx);
1562
1563 cx.emit(Event::PaneAdded(center_pane.clone()));
1564
1565 let any_window_handle = window.window_handle();
1566 app_state.workspace_store.update(cx, |store, _| {
1567 store
1568 .workspaces
1569 .insert((any_window_handle, weak_handle.clone()));
1570 });
1571
1572 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1573 let mut connection_status = app_state.client.status();
1574 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1575 current_user.next().await;
1576 connection_status.next().await;
1577 let mut stream =
1578 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1579
1580 while stream.recv().await.is_some() {
1581 this.update(cx, |_, cx| cx.notify())?;
1582 }
1583 anyhow::Ok(())
1584 });
1585
1586 // All leader updates are enqueued and then processed in a single task, so
1587 // that each asynchronous operation can be run in order.
1588 let (leader_updates_tx, mut leader_updates_rx) =
1589 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1590 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1591 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1592 Self::process_leader_update(&this, leader_id, update, cx)
1593 .await
1594 .log_err();
1595 }
1596
1597 Ok(())
1598 });
1599
1600 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1601 let modal_layer = cx.new(|_| ModalLayer::new());
1602 let toast_layer = cx.new(|_| ToastLayer::new());
1603 cx.subscribe(
1604 &modal_layer,
1605 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1606 cx.emit(Event::ModalOpened);
1607 },
1608 )
1609 .detach();
1610
1611 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1612 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1613 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1614 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1615 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1616 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1617 let status_bar = cx.new(|cx| {
1618 let mut status_bar = StatusBar::new(¢er_pane.clone(), window, cx);
1619 status_bar.add_left_item(left_dock_buttons, window, cx);
1620 status_bar.add_right_item(right_dock_buttons, window, cx);
1621 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1622 status_bar
1623 });
1624
1625 let session_id = app_state.session.read(cx).id().to_owned();
1626
1627 let mut active_call = None;
1628 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1629 let subscriptions =
1630 vec![
1631 call.0
1632 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1633 ];
1634 active_call = Some((call, subscriptions));
1635 }
1636
1637 let (serializable_items_tx, serializable_items_rx) =
1638 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1639 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1640 Self::serialize_items(&this, serializable_items_rx, cx).await
1641 });
1642
1643 let subscriptions = vec![
1644 cx.observe_window_activation(window, Self::on_window_activation_changed),
1645 cx.observe_window_bounds(window, move |this, window, cx| {
1646 if this.bounds_save_task_queued.is_some() {
1647 return;
1648 }
1649 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1650 cx.background_executor()
1651 .timer(Duration::from_millis(100))
1652 .await;
1653 this.update_in(cx, |this, window, cx| {
1654 this.save_window_bounds(window, cx).detach();
1655 this.bounds_save_task_queued.take();
1656 })
1657 .ok();
1658 }));
1659 cx.notify();
1660 }),
1661 cx.observe_window_appearance(window, |_, window, cx| {
1662 let window_appearance = window.appearance();
1663
1664 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1665
1666 GlobalTheme::reload_theme(cx);
1667 GlobalTheme::reload_icon_theme(cx);
1668 }),
1669 cx.on_release({
1670 let weak_handle = weak_handle.clone();
1671 move |this, cx| {
1672 this.app_state.workspace_store.update(cx, move |store, _| {
1673 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1674 })
1675 }
1676 }),
1677 ];
1678
1679 cx.defer_in(window, move |this, window, cx| {
1680 this.update_window_title(window, cx);
1681 this.show_initial_notifications(cx);
1682 });
1683
1684 let mut center = PaneGroup::new(center_pane.clone());
1685 center.set_is_center(true);
1686 center.mark_positions(cx);
1687
1688 Workspace {
1689 weak_self: weak_handle.clone(),
1690 zoomed: None,
1691 zoomed_position: None,
1692 previous_dock_drag_coordinates: None,
1693 center,
1694 panes: vec![center_pane.clone()],
1695 panes_by_item: Default::default(),
1696 active_pane: center_pane.clone(),
1697 last_active_center_pane: Some(center_pane.downgrade()),
1698 last_active_view_id: None,
1699 status_bar,
1700 modal_layer,
1701 toast_layer,
1702 titlebar_item: None,
1703 active_worktree_override: None,
1704 notifications: Notifications::default(),
1705 suppressed_notifications: HashSet::default(),
1706 left_dock,
1707 bottom_dock,
1708 right_dock,
1709 _panels_task: None,
1710 project: project.clone(),
1711 follower_states: Default::default(),
1712 last_leaders_by_pane: Default::default(),
1713 dispatching_keystrokes: Default::default(),
1714 window_edited: false,
1715 last_window_title: None,
1716 dirty_items: Default::default(),
1717 active_call,
1718 database_id: workspace_id,
1719 app_state,
1720 _observe_current_user,
1721 _apply_leader_updates,
1722 _schedule_serialize_workspace: None,
1723 _serialize_workspace_task: None,
1724 _schedule_serialize_ssh_paths: None,
1725 leader_updates_tx,
1726 _subscriptions: subscriptions,
1727 pane_history_timestamp,
1728 workspace_actions: Default::default(),
1729 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1730 bounds: Default::default(),
1731 centered_layout: false,
1732 bounds_save_task_queued: None,
1733 on_prompt_for_new_path: None,
1734 on_prompt_for_open_path: None,
1735 terminal_provider: None,
1736 debugger_provider: None,
1737 serializable_items_tx,
1738 _items_serializer,
1739 session_id: Some(session_id),
1740
1741 scheduled_tasks: Vec::new(),
1742 last_open_dock_positions: Vec::new(),
1743 removing: false,
1744 }
1745 }
1746
1747 pub fn new_local(
1748 abs_paths: Vec<PathBuf>,
1749 app_state: Arc<AppState>,
1750 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1751 env: Option<HashMap<String, String>>,
1752 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1753 activate: bool,
1754 cx: &mut App,
1755 ) -> Task<
1756 anyhow::Result<(
1757 WindowHandle<MultiWorkspace>,
1758 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
1759 )>,
1760 > {
1761 let project_handle = Project::local(
1762 app_state.client.clone(),
1763 app_state.node_runtime.clone(),
1764 app_state.user_store.clone(),
1765 app_state.languages.clone(),
1766 app_state.fs.clone(),
1767 env,
1768 Default::default(),
1769 cx,
1770 );
1771
1772 cx.spawn(async move |cx| {
1773 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1774 for path in abs_paths.into_iter() {
1775 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1776 paths_to_open.push(canonical)
1777 } else {
1778 paths_to_open.push(path)
1779 }
1780 }
1781
1782 let serialized_workspace =
1783 persistence::DB.workspace_for_roots(paths_to_open.as_slice());
1784
1785 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1786 paths_to_open = paths.ordered_paths().cloned().collect();
1787 if !paths.is_lexicographically_ordered() {
1788 project_handle.update(cx, |project, cx| {
1789 project.set_worktrees_reordered(true, cx);
1790 });
1791 }
1792 }
1793
1794 // Get project paths for all of the abs_paths
1795 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1796 Vec::with_capacity(paths_to_open.len());
1797
1798 for path in paths_to_open.into_iter() {
1799 if let Some((_, project_entry)) = cx
1800 .update(|cx| {
1801 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1802 })
1803 .await
1804 .log_err()
1805 {
1806 project_paths.push((path, Some(project_entry)));
1807 } else {
1808 project_paths.push((path, None));
1809 }
1810 }
1811
1812 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1813 serialized_workspace.id
1814 } else {
1815 DB.next_id().await.unwrap_or_else(|_| Default::default())
1816 };
1817
1818 let toolchains = DB.toolchains(workspace_id).await?;
1819
1820 for (toolchain, worktree_path, path) in toolchains {
1821 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1822 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1823 this.find_worktree(&worktree_path, cx)
1824 .and_then(|(worktree, rel_path)| {
1825 if rel_path.is_empty() {
1826 Some(worktree.read(cx).id())
1827 } else {
1828 None
1829 }
1830 })
1831 }) else {
1832 // We did not find a worktree with a given path, but that's whatever.
1833 continue;
1834 };
1835 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1836 continue;
1837 }
1838
1839 project_handle
1840 .update(cx, |this, cx| {
1841 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1842 })
1843 .await;
1844 }
1845 if let Some(workspace) = serialized_workspace.as_ref() {
1846 project_handle.update(cx, |this, cx| {
1847 for (scope, toolchains) in &workspace.user_toolchains {
1848 for toolchain in toolchains {
1849 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1850 }
1851 }
1852 });
1853 }
1854
1855 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1856 if let Some(window) = requesting_window {
1857 let centered_layout = serialized_workspace
1858 .as_ref()
1859 .map(|w| w.centered_layout)
1860 .unwrap_or(false);
1861
1862 let workspace = window.update(cx, |multi_workspace, window, cx| {
1863 let workspace = cx.new(|cx| {
1864 let mut workspace = Workspace::new(
1865 Some(workspace_id),
1866 project_handle.clone(),
1867 app_state.clone(),
1868 window,
1869 cx,
1870 );
1871
1872 workspace.centered_layout = centered_layout;
1873
1874 // Call init callback to add items before window renders
1875 if let Some(init) = init {
1876 init(&mut workspace, window, cx);
1877 }
1878
1879 workspace
1880 });
1881 if activate {
1882 multi_workspace.activate(workspace.clone(), cx);
1883 } else {
1884 multi_workspace.add_workspace(workspace.clone(), cx);
1885 }
1886 workspace
1887 })?;
1888 (window, workspace)
1889 } else {
1890 let window_bounds_override = window_bounds_env_override();
1891
1892 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1893 (Some(WindowBounds::Windowed(bounds)), None)
1894 } else if let Some(workspace) = serialized_workspace.as_ref()
1895 && let Some(display) = workspace.display
1896 && let Some(bounds) = workspace.window_bounds.as_ref()
1897 {
1898 // Reopening an existing workspace - restore its saved bounds
1899 (Some(bounds.0), Some(display))
1900 } else if let Some((display, bounds)) =
1901 persistence::read_default_window_bounds()
1902 {
1903 // New or empty workspace - use the last known window bounds
1904 (Some(bounds), Some(display))
1905 } else {
1906 // New window - let GPUI's default_bounds() handle cascading
1907 (None, None)
1908 };
1909
1910 // Use the serialized workspace to construct the new window
1911 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1912 options.window_bounds = window_bounds;
1913 let centered_layout = serialized_workspace
1914 .as_ref()
1915 .map(|w| w.centered_layout)
1916 .unwrap_or(false);
1917 let window = cx.open_window(options, {
1918 let app_state = app_state.clone();
1919 let project_handle = project_handle.clone();
1920 move |window, cx| {
1921 let workspace = cx.new(|cx| {
1922 let mut workspace = Workspace::new(
1923 Some(workspace_id),
1924 project_handle,
1925 app_state,
1926 window,
1927 cx,
1928 );
1929 workspace.centered_layout = centered_layout;
1930
1931 // Call init callback to add items before window renders
1932 if let Some(init) = init {
1933 init(&mut workspace, window, cx);
1934 }
1935
1936 workspace
1937 });
1938 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1939 }
1940 })?;
1941 let workspace =
1942 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
1943 multi_workspace.workspace().clone()
1944 })?;
1945 (window, workspace)
1946 };
1947
1948 notify_if_database_failed(window, cx);
1949 // Check if this is an empty workspace (no paths to open)
1950 // An empty workspace is one where project_paths is empty
1951 let is_empty_workspace = project_paths.is_empty();
1952 // Check if serialized workspace has paths before it's moved
1953 let serialized_workspace_has_paths = serialized_workspace
1954 .as_ref()
1955 .map(|ws| !ws.paths.is_empty())
1956 .unwrap_or(false);
1957
1958 let opened_items = window
1959 .update(cx, |_, window, cx| {
1960 workspace.update(cx, |_workspace: &mut Workspace, cx| {
1961 open_items(serialized_workspace, project_paths, window, cx)
1962 })
1963 })?
1964 .await
1965 .unwrap_or_default();
1966
1967 // Restore default dock state for empty workspaces
1968 // Only restore if:
1969 // 1. This is an empty workspace (no paths), AND
1970 // 2. The serialized workspace either doesn't exist or has no paths
1971 if is_empty_workspace && !serialized_workspace_has_paths {
1972 if let Some(default_docks) = persistence::read_default_dock_state() {
1973 window
1974 .update(cx, |_, window, cx| {
1975 workspace.update(cx, |workspace, cx| {
1976 for (dock, serialized_dock) in [
1977 (&workspace.right_dock, &default_docks.right),
1978 (&workspace.left_dock, &default_docks.left),
1979 (&workspace.bottom_dock, &default_docks.bottom),
1980 ] {
1981 dock.update(cx, |dock, cx| {
1982 dock.serialized_dock = Some(serialized_dock.clone());
1983 dock.restore_state(window, cx);
1984 });
1985 }
1986 cx.notify();
1987 });
1988 })
1989 .log_err();
1990 }
1991 }
1992
1993 window
1994 .update(cx, |_, _window, cx| {
1995 workspace.update(cx, |this: &mut Workspace, cx| {
1996 this.update_history(cx);
1997 });
1998 })
1999 .log_err();
2000 Ok((window, opened_items))
2001 })
2002 }
2003
2004 pub fn weak_handle(&self) -> WeakEntity<Self> {
2005 self.weak_self.clone()
2006 }
2007
2008 pub fn left_dock(&self) -> &Entity<Dock> {
2009 &self.left_dock
2010 }
2011
2012 pub fn bottom_dock(&self) -> &Entity<Dock> {
2013 &self.bottom_dock
2014 }
2015
2016 pub fn set_bottom_dock_layout(
2017 &mut self,
2018 layout: BottomDockLayout,
2019 window: &mut Window,
2020 cx: &mut Context<Self>,
2021 ) {
2022 let fs = self.project().read(cx).fs();
2023 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2024 content.workspace.bottom_dock_layout = Some(layout);
2025 });
2026
2027 cx.notify();
2028 self.serialize_workspace(window, cx);
2029 }
2030
2031 pub fn right_dock(&self) -> &Entity<Dock> {
2032 &self.right_dock
2033 }
2034
2035 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2036 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2037 }
2038
2039 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2040 let left_dock = self.left_dock.read(cx);
2041 let left_visible = left_dock.is_open();
2042 let left_active_panel = left_dock
2043 .active_panel()
2044 .map(|panel| panel.persistent_name().to_string());
2045 // `zoomed_position` is kept in sync with individual panel zoom state
2046 // by the dock code in `Dock::new` and `Dock::add_panel`.
2047 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2048
2049 let right_dock = self.right_dock.read(cx);
2050 let right_visible = right_dock.is_open();
2051 let right_active_panel = right_dock
2052 .active_panel()
2053 .map(|panel| panel.persistent_name().to_string());
2054 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2055
2056 let bottom_dock = self.bottom_dock.read(cx);
2057 let bottom_visible = bottom_dock.is_open();
2058 let bottom_active_panel = bottom_dock
2059 .active_panel()
2060 .map(|panel| panel.persistent_name().to_string());
2061 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2062
2063 DockStructure {
2064 left: DockData {
2065 visible: left_visible,
2066 active_panel: left_active_panel,
2067 zoom: left_dock_zoom,
2068 },
2069 right: DockData {
2070 visible: right_visible,
2071 active_panel: right_active_panel,
2072 zoom: right_dock_zoom,
2073 },
2074 bottom: DockData {
2075 visible: bottom_visible,
2076 active_panel: bottom_active_panel,
2077 zoom: bottom_dock_zoom,
2078 },
2079 }
2080 }
2081
2082 pub fn set_dock_structure(
2083 &self,
2084 docks: DockStructure,
2085 window: &mut Window,
2086 cx: &mut Context<Self>,
2087 ) {
2088 for (dock, data) in [
2089 (&self.left_dock, docks.left),
2090 (&self.bottom_dock, docks.bottom),
2091 (&self.right_dock, docks.right),
2092 ] {
2093 dock.update(cx, |dock, cx| {
2094 dock.serialized_dock = Some(data);
2095 dock.restore_state(window, cx);
2096 });
2097 }
2098 }
2099
2100 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2101 self.items(cx)
2102 .filter_map(|item| {
2103 let project_path = item.project_path(cx)?;
2104 self.project.read(cx).absolute_path(&project_path, cx)
2105 })
2106 .collect()
2107 }
2108
2109 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2110 match position {
2111 DockPosition::Left => &self.left_dock,
2112 DockPosition::Bottom => &self.bottom_dock,
2113 DockPosition::Right => &self.right_dock,
2114 }
2115 }
2116
2117 pub fn is_edited(&self) -> bool {
2118 self.window_edited
2119 }
2120
2121 pub fn add_panel<T: Panel>(
2122 &mut self,
2123 panel: Entity<T>,
2124 window: &mut Window,
2125 cx: &mut Context<Self>,
2126 ) {
2127 let focus_handle = panel.panel_focus_handle(cx);
2128 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2129 .detach();
2130
2131 let dock_position = panel.position(window, cx);
2132 let dock = self.dock_at_position(dock_position);
2133 let any_panel = panel.to_any();
2134
2135 dock.update(cx, |dock, cx| {
2136 dock.add_panel(panel, self.weak_self.clone(), window, cx)
2137 });
2138
2139 cx.emit(Event::PanelAdded(any_panel));
2140 }
2141
2142 pub fn remove_panel<T: Panel>(
2143 &mut self,
2144 panel: &Entity<T>,
2145 window: &mut Window,
2146 cx: &mut Context<Self>,
2147 ) {
2148 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2149 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2150 }
2151 }
2152
2153 pub fn status_bar(&self) -> &Entity<StatusBar> {
2154 &self.status_bar
2155 }
2156
2157 pub fn set_workspace_sidebar_open(&self, open: bool, cx: &mut App) {
2158 self.status_bar.update(cx, |status_bar, cx| {
2159 status_bar.set_workspace_sidebar_open(open, cx);
2160 });
2161 }
2162
2163 pub fn status_bar_visible(&self, cx: &App) -> bool {
2164 StatusBarSettings::get_global(cx).show
2165 }
2166
2167 pub fn app_state(&self) -> &Arc<AppState> {
2168 &self.app_state
2169 }
2170
2171 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2172 self._panels_task = Some(task);
2173 }
2174
2175 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2176 self._panels_task.take()
2177 }
2178
2179 pub fn user_store(&self) -> &Entity<UserStore> {
2180 &self.app_state.user_store
2181 }
2182
2183 pub fn project(&self) -> &Entity<Project> {
2184 &self.project
2185 }
2186
2187 pub fn path_style(&self, cx: &App) -> PathStyle {
2188 self.project.read(cx).path_style(cx)
2189 }
2190
2191 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2192 let mut history: HashMap<EntityId, usize> = HashMap::default();
2193
2194 for pane_handle in &self.panes {
2195 let pane = pane_handle.read(cx);
2196
2197 for entry in pane.activation_history() {
2198 history.insert(
2199 entry.entity_id,
2200 history
2201 .get(&entry.entity_id)
2202 .cloned()
2203 .unwrap_or(0)
2204 .max(entry.timestamp),
2205 );
2206 }
2207 }
2208
2209 history
2210 }
2211
2212 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2213 let mut recent_item: Option<Entity<T>> = None;
2214 let mut recent_timestamp = 0;
2215 for pane_handle in &self.panes {
2216 let pane = pane_handle.read(cx);
2217 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2218 pane.items().map(|item| (item.item_id(), item)).collect();
2219 for entry in pane.activation_history() {
2220 if entry.timestamp > recent_timestamp
2221 && let Some(&item) = item_map.get(&entry.entity_id)
2222 && let Some(typed_item) = item.act_as::<T>(cx)
2223 {
2224 recent_timestamp = entry.timestamp;
2225 recent_item = Some(typed_item);
2226 }
2227 }
2228 }
2229 recent_item
2230 }
2231
2232 pub fn recent_navigation_history_iter(
2233 &self,
2234 cx: &App,
2235 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2236 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2237 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2238
2239 for pane in &self.panes {
2240 let pane = pane.read(cx);
2241
2242 pane.nav_history()
2243 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2244 if let Some(fs_path) = &fs_path {
2245 abs_paths_opened
2246 .entry(fs_path.clone())
2247 .or_default()
2248 .insert(project_path.clone());
2249 }
2250 let timestamp = entry.timestamp;
2251 match history.entry(project_path) {
2252 hash_map::Entry::Occupied(mut entry) => {
2253 let (_, old_timestamp) = entry.get();
2254 if ×tamp > old_timestamp {
2255 entry.insert((fs_path, timestamp));
2256 }
2257 }
2258 hash_map::Entry::Vacant(entry) => {
2259 entry.insert((fs_path, timestamp));
2260 }
2261 }
2262 });
2263
2264 if let Some(item) = pane.active_item()
2265 && let Some(project_path) = item.project_path(cx)
2266 {
2267 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2268
2269 if let Some(fs_path) = &fs_path {
2270 abs_paths_opened
2271 .entry(fs_path.clone())
2272 .or_default()
2273 .insert(project_path.clone());
2274 }
2275
2276 history.insert(project_path, (fs_path, std::usize::MAX));
2277 }
2278 }
2279
2280 history
2281 .into_iter()
2282 .sorted_by_key(|(_, (_, order))| *order)
2283 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2284 .rev()
2285 .filter(move |(history_path, abs_path)| {
2286 let latest_project_path_opened = abs_path
2287 .as_ref()
2288 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2289 .and_then(|project_paths| {
2290 project_paths
2291 .iter()
2292 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2293 });
2294
2295 latest_project_path_opened.is_none_or(|path| path == history_path)
2296 })
2297 }
2298
2299 pub fn recent_navigation_history(
2300 &self,
2301 limit: Option<usize>,
2302 cx: &App,
2303 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2304 self.recent_navigation_history_iter(cx)
2305 .take(limit.unwrap_or(usize::MAX))
2306 .collect()
2307 }
2308
2309 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2310 for pane in &self.panes {
2311 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2312 }
2313 }
2314
2315 fn navigate_history(
2316 &mut self,
2317 pane: WeakEntity<Pane>,
2318 mode: NavigationMode,
2319 window: &mut Window,
2320 cx: &mut Context<Workspace>,
2321 ) -> Task<Result<()>> {
2322 self.navigate_history_impl(
2323 pane,
2324 mode,
2325 window,
2326 &mut |history, cx| history.pop(mode, cx),
2327 cx,
2328 )
2329 }
2330
2331 fn navigate_tag_history(
2332 &mut self,
2333 pane: WeakEntity<Pane>,
2334 mode: TagNavigationMode,
2335 window: &mut Window,
2336 cx: &mut Context<Workspace>,
2337 ) -> Task<Result<()>> {
2338 self.navigate_history_impl(
2339 pane,
2340 NavigationMode::Normal,
2341 window,
2342 &mut |history, _cx| history.pop_tag(mode),
2343 cx,
2344 )
2345 }
2346
2347 fn navigate_history_impl(
2348 &mut self,
2349 pane: WeakEntity<Pane>,
2350 mode: NavigationMode,
2351 window: &mut Window,
2352 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2353 cx: &mut Context<Workspace>,
2354 ) -> Task<Result<()>> {
2355 let to_load = if let Some(pane) = pane.upgrade() {
2356 pane.update(cx, |pane, cx| {
2357 window.focus(&pane.focus_handle(cx), cx);
2358 loop {
2359 // Retrieve the weak item handle from the history.
2360 let entry = cb(pane.nav_history_mut(), cx)?;
2361
2362 // If the item is still present in this pane, then activate it.
2363 if let Some(index) = entry
2364 .item
2365 .upgrade()
2366 .and_then(|v| pane.index_for_item(v.as_ref()))
2367 {
2368 let prev_active_item_index = pane.active_item_index();
2369 pane.nav_history_mut().set_mode(mode);
2370 pane.activate_item(index, true, true, window, cx);
2371 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2372
2373 let mut navigated = prev_active_item_index != pane.active_item_index();
2374 if let Some(data) = entry.data {
2375 navigated |= pane.active_item()?.navigate(data, window, cx);
2376 }
2377
2378 if navigated {
2379 break None;
2380 }
2381 } else {
2382 // If the item is no longer present in this pane, then retrieve its
2383 // path info in order to reopen it.
2384 break pane
2385 .nav_history()
2386 .path_for_item(entry.item.id())
2387 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2388 }
2389 }
2390 })
2391 } else {
2392 None
2393 };
2394
2395 if let Some((project_path, abs_path, entry)) = to_load {
2396 // If the item was no longer present, then load it again from its previous path, first try the local path
2397 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2398
2399 cx.spawn_in(window, async move |workspace, cx| {
2400 let open_by_project_path = open_by_project_path.await;
2401 let mut navigated = false;
2402 match open_by_project_path
2403 .with_context(|| format!("Navigating to {project_path:?}"))
2404 {
2405 Ok((project_entry_id, build_item)) => {
2406 let prev_active_item_id = pane.update(cx, |pane, _| {
2407 pane.nav_history_mut().set_mode(mode);
2408 pane.active_item().map(|p| p.item_id())
2409 })?;
2410
2411 pane.update_in(cx, |pane, window, cx| {
2412 let item = pane.open_item(
2413 project_entry_id,
2414 project_path,
2415 true,
2416 entry.is_preview,
2417 true,
2418 None,
2419 window, cx,
2420 build_item,
2421 );
2422 navigated |= Some(item.item_id()) != prev_active_item_id;
2423 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2424 if let Some(data) = entry.data {
2425 navigated |= item.navigate(data, window, cx);
2426 }
2427 })?;
2428 }
2429 Err(open_by_project_path_e) => {
2430 // Fall back to opening by abs path, in case an external file was opened and closed,
2431 // and its worktree is now dropped
2432 if let Some(abs_path) = abs_path {
2433 let prev_active_item_id = pane.update(cx, |pane, _| {
2434 pane.nav_history_mut().set_mode(mode);
2435 pane.active_item().map(|p| p.item_id())
2436 })?;
2437 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2438 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2439 })?;
2440 match open_by_abs_path
2441 .await
2442 .with_context(|| format!("Navigating to {abs_path:?}"))
2443 {
2444 Ok(item) => {
2445 pane.update_in(cx, |pane, window, cx| {
2446 navigated |= Some(item.item_id()) != prev_active_item_id;
2447 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2448 if let Some(data) = entry.data {
2449 navigated |= item.navigate(data, window, cx);
2450 }
2451 })?;
2452 }
2453 Err(open_by_abs_path_e) => {
2454 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2455 }
2456 }
2457 }
2458 }
2459 }
2460
2461 if !navigated {
2462 workspace
2463 .update_in(cx, |workspace, window, cx| {
2464 Self::navigate_history(workspace, pane, mode, window, cx)
2465 })?
2466 .await?;
2467 }
2468
2469 Ok(())
2470 })
2471 } else {
2472 Task::ready(Ok(()))
2473 }
2474 }
2475
2476 pub fn go_back(
2477 &mut self,
2478 pane: WeakEntity<Pane>,
2479 window: &mut Window,
2480 cx: &mut Context<Workspace>,
2481 ) -> Task<Result<()>> {
2482 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2483 }
2484
2485 pub fn go_forward(
2486 &mut self,
2487 pane: WeakEntity<Pane>,
2488 window: &mut Window,
2489 cx: &mut Context<Workspace>,
2490 ) -> Task<Result<()>> {
2491 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2492 }
2493
2494 pub fn reopen_closed_item(
2495 &mut self,
2496 window: &mut Window,
2497 cx: &mut Context<Workspace>,
2498 ) -> Task<Result<()>> {
2499 self.navigate_history(
2500 self.active_pane().downgrade(),
2501 NavigationMode::ReopeningClosedItem,
2502 window,
2503 cx,
2504 )
2505 }
2506
2507 pub fn client(&self) -> &Arc<Client> {
2508 &self.app_state.client
2509 }
2510
2511 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2512 self.titlebar_item = Some(item);
2513 cx.notify();
2514 }
2515
2516 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2517 self.on_prompt_for_new_path = Some(prompt)
2518 }
2519
2520 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2521 self.on_prompt_for_open_path = Some(prompt)
2522 }
2523
2524 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2525 self.terminal_provider = Some(Box::new(provider));
2526 }
2527
2528 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2529 self.debugger_provider = Some(Arc::new(provider));
2530 }
2531
2532 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2533 self.debugger_provider.clone()
2534 }
2535
2536 pub fn prompt_for_open_path(
2537 &mut self,
2538 path_prompt_options: PathPromptOptions,
2539 lister: DirectoryLister,
2540 window: &mut Window,
2541 cx: &mut Context<Self>,
2542 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2543 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2544 let prompt = self.on_prompt_for_open_path.take().unwrap();
2545 let rx = prompt(self, lister, window, cx);
2546 self.on_prompt_for_open_path = Some(prompt);
2547 rx
2548 } else {
2549 let (tx, rx) = oneshot::channel();
2550 let abs_path = cx.prompt_for_paths(path_prompt_options);
2551
2552 cx.spawn_in(window, async move |workspace, cx| {
2553 let Ok(result) = abs_path.await else {
2554 return Ok(());
2555 };
2556
2557 match result {
2558 Ok(result) => {
2559 tx.send(result).ok();
2560 }
2561 Err(err) => {
2562 let rx = workspace.update_in(cx, |workspace, window, cx| {
2563 workspace.show_portal_error(err.to_string(), cx);
2564 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2565 let rx = prompt(workspace, lister, window, cx);
2566 workspace.on_prompt_for_open_path = Some(prompt);
2567 rx
2568 })?;
2569 if let Ok(path) = rx.await {
2570 tx.send(path).ok();
2571 }
2572 }
2573 };
2574 anyhow::Ok(())
2575 })
2576 .detach();
2577
2578 rx
2579 }
2580 }
2581
2582 pub fn prompt_for_new_path(
2583 &mut self,
2584 lister: DirectoryLister,
2585 suggested_name: Option<String>,
2586 window: &mut Window,
2587 cx: &mut Context<Self>,
2588 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2589 if self.project.read(cx).is_via_collab()
2590 || self.project.read(cx).is_via_remote_server()
2591 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2592 {
2593 let prompt = self.on_prompt_for_new_path.take().unwrap();
2594 let rx = prompt(self, lister, suggested_name, window, cx);
2595 self.on_prompt_for_new_path = Some(prompt);
2596 return rx;
2597 }
2598
2599 let (tx, rx) = oneshot::channel();
2600 cx.spawn_in(window, async move |workspace, cx| {
2601 let abs_path = workspace.update(cx, |workspace, cx| {
2602 let relative_to = workspace
2603 .most_recent_active_path(cx)
2604 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2605 .or_else(|| {
2606 let project = workspace.project.read(cx);
2607 project.visible_worktrees(cx).find_map(|worktree| {
2608 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2609 })
2610 })
2611 .or_else(std::env::home_dir)
2612 .unwrap_or_else(|| PathBuf::from(""));
2613 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2614 })?;
2615 let abs_path = match abs_path.await? {
2616 Ok(path) => path,
2617 Err(err) => {
2618 let rx = workspace.update_in(cx, |workspace, window, cx| {
2619 workspace.show_portal_error(err.to_string(), cx);
2620
2621 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2622 let rx = prompt(workspace, lister, suggested_name, window, cx);
2623 workspace.on_prompt_for_new_path = Some(prompt);
2624 rx
2625 })?;
2626 if let Ok(path) = rx.await {
2627 tx.send(path).ok();
2628 }
2629 return anyhow::Ok(());
2630 }
2631 };
2632
2633 tx.send(abs_path.map(|path| vec![path])).ok();
2634 anyhow::Ok(())
2635 })
2636 .detach();
2637
2638 rx
2639 }
2640
2641 pub fn titlebar_item(&self) -> Option<AnyView> {
2642 self.titlebar_item.clone()
2643 }
2644
2645 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2646 /// When set, git-related operations should use this worktree instead of deriving
2647 /// the active worktree from the focused file.
2648 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2649 self.active_worktree_override
2650 }
2651
2652 pub fn set_active_worktree_override(
2653 &mut self,
2654 worktree_id: Option<WorktreeId>,
2655 cx: &mut Context<Self>,
2656 ) {
2657 self.active_worktree_override = worktree_id;
2658 cx.notify();
2659 }
2660
2661 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2662 self.active_worktree_override = None;
2663 cx.notify();
2664 }
2665
2666 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2667 ///
2668 /// If the given workspace has a local project, then it will be passed
2669 /// to the callback. Otherwise, a new empty window will be created.
2670 pub fn with_local_workspace<T, F>(
2671 &mut self,
2672 window: &mut Window,
2673 cx: &mut Context<Self>,
2674 callback: F,
2675 ) -> Task<Result<T>>
2676 where
2677 T: 'static,
2678 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2679 {
2680 if self.project.read(cx).is_local() {
2681 Task::ready(Ok(callback(self, window, cx)))
2682 } else {
2683 let env = self.project.read(cx).cli_environment(cx);
2684 let task = Self::new_local(
2685 Vec::new(),
2686 self.app_state.clone(),
2687 None,
2688 env,
2689 None,
2690 true,
2691 cx,
2692 );
2693 cx.spawn_in(window, async move |_vh, cx| {
2694 let (multi_workspace_window, _) = 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 (multi_workspace_window, _) = task.await?;
2733 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2734 let workspace = multi_workspace.workspace().clone();
2735 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2736 })
2737 })
2738 }
2739 }
2740
2741 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2742 self.project.read(cx).worktrees(cx)
2743 }
2744
2745 pub fn visible_worktrees<'a>(
2746 &self,
2747 cx: &'a App,
2748 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2749 self.project.read(cx).visible_worktrees(cx)
2750 }
2751
2752 #[cfg(any(test, feature = "test-support"))]
2753 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
2754 let futures = self
2755 .worktrees(cx)
2756 .filter_map(|worktree| worktree.read(cx).as_local())
2757 .map(|worktree| worktree.scan_complete())
2758 .collect::<Vec<_>>();
2759 async move {
2760 for future in futures {
2761 future.await;
2762 }
2763 }
2764 }
2765
2766 pub fn close_global(cx: &mut App) {
2767 cx.defer(|cx| {
2768 cx.windows().iter().find(|window| {
2769 window
2770 .update(cx, |_, window, _| {
2771 if window.is_window_active() {
2772 //This can only get called when the window's project connection has been lost
2773 //so we don't need to prompt the user for anything and instead just close the window
2774 window.remove_window();
2775 true
2776 } else {
2777 false
2778 }
2779 })
2780 .unwrap_or(false)
2781 });
2782 });
2783 }
2784
2785 pub fn move_focused_panel_to_next_position(
2786 &mut self,
2787 _: &MoveFocusedPanelToNextPosition,
2788 window: &mut Window,
2789 cx: &mut Context<Self>,
2790 ) {
2791 let docks = self.all_docks();
2792 let active_dock = docks
2793 .into_iter()
2794 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
2795
2796 if let Some(dock) = active_dock {
2797 dock.update(cx, |dock, cx| {
2798 let active_panel = dock
2799 .active_panel()
2800 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
2801
2802 if let Some(panel) = active_panel {
2803 panel.move_to_next_position(window, cx);
2804 }
2805 })
2806 }
2807 }
2808
2809 pub fn prepare_to_close(
2810 &mut self,
2811 close_intent: CloseIntent,
2812 window: &mut Window,
2813 cx: &mut Context<Self>,
2814 ) -> Task<Result<bool>> {
2815 let active_call = self.active_global_call();
2816
2817 cx.spawn_in(window, async move |this, cx| {
2818 this.update(cx, |this, _| {
2819 if close_intent == CloseIntent::CloseWindow {
2820 this.removing = true;
2821 }
2822 })?;
2823
2824 let workspace_count = cx.update(|_window, cx| {
2825 cx.windows()
2826 .iter()
2827 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
2828 .count()
2829 })?;
2830
2831 #[cfg(target_os = "macos")]
2832 let save_last_workspace = false;
2833
2834 // On Linux and Windows, closing the last window should restore the last workspace.
2835 #[cfg(not(target_os = "macos"))]
2836 let save_last_workspace = {
2837 let remaining_workspaces = cx.update(|_window, cx| {
2838 cx.windows()
2839 .iter()
2840 .filter_map(|window| window.downcast::<MultiWorkspace>())
2841 .filter_map(|multi_workspace| {
2842 multi_workspace
2843 .update(cx, |multi_workspace, _, cx| {
2844 multi_workspace.workspace().read(cx).removing
2845 })
2846 .ok()
2847 })
2848 .filter(|removing| !removing)
2849 .count()
2850 })?;
2851
2852 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
2853 };
2854
2855 if let Some(active_call) = active_call
2856 && workspace_count == 1
2857 && cx
2858 .update(|_window, cx| active_call.0.is_in_room(cx))
2859 .unwrap_or(false)
2860 {
2861 if close_intent == CloseIntent::CloseWindow {
2862 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
2863 let answer = cx.update(|window, cx| {
2864 window.prompt(
2865 PromptLevel::Warning,
2866 "Do you want to leave the current call?",
2867 None,
2868 &["Close window and hang up", "Cancel"],
2869 cx,
2870 )
2871 })?;
2872
2873 if answer.await.log_err() == Some(1) {
2874 return anyhow::Ok(false);
2875 } else {
2876 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
2877 task.await.log_err();
2878 }
2879 }
2880 }
2881 if close_intent == CloseIntent::ReplaceWindow {
2882 _ = cx.update(|_window, cx| {
2883 let multi_workspace = cx
2884 .windows()
2885 .iter()
2886 .filter_map(|window| window.downcast::<MultiWorkspace>())
2887 .next()
2888 .unwrap();
2889 let project = multi_workspace
2890 .read(cx)?
2891 .workspace()
2892 .read(cx)
2893 .project
2894 .clone();
2895 if project.read(cx).is_shared() {
2896 active_call.0.unshare_project(project, cx)?;
2897 }
2898 Ok::<_, anyhow::Error>(())
2899 });
2900 }
2901 }
2902
2903 let save_result = this
2904 .update_in(cx, |this, window, cx| {
2905 this.save_all_internal(SaveIntent::Close, window, cx)
2906 })?
2907 .await;
2908
2909 // If we're not quitting, but closing, we remove the workspace from
2910 // the current session.
2911 if close_intent != CloseIntent::Quit
2912 && !save_last_workspace
2913 && save_result.as_ref().is_ok_and(|&res| res)
2914 {
2915 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
2916 .await;
2917 }
2918
2919 save_result
2920 })
2921 }
2922
2923 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
2924 self.save_all_internal(
2925 action.save_intent.unwrap_or(SaveIntent::SaveAll),
2926 window,
2927 cx,
2928 )
2929 .detach_and_log_err(cx);
2930 }
2931
2932 fn send_keystrokes(
2933 &mut self,
2934 action: &SendKeystrokes,
2935 window: &mut Window,
2936 cx: &mut Context<Self>,
2937 ) {
2938 let keystrokes: Vec<Keystroke> = action
2939 .0
2940 .split(' ')
2941 .flat_map(|k| Keystroke::parse(k).log_err())
2942 .map(|k| {
2943 cx.keyboard_mapper()
2944 .map_key_equivalent(k, false)
2945 .inner()
2946 .clone()
2947 })
2948 .collect();
2949 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
2950 }
2951
2952 pub fn send_keystrokes_impl(
2953 &mut self,
2954 keystrokes: Vec<Keystroke>,
2955 window: &mut Window,
2956 cx: &mut Context<Self>,
2957 ) -> Shared<Task<()>> {
2958 let mut state = self.dispatching_keystrokes.borrow_mut();
2959 if !state.dispatched.insert(keystrokes.clone()) {
2960 cx.propagate();
2961 return state.task.clone().unwrap();
2962 }
2963
2964 state.queue.extend(keystrokes);
2965
2966 let keystrokes = self.dispatching_keystrokes.clone();
2967 if state.task.is_none() {
2968 state.task = Some(
2969 window
2970 .spawn(cx, async move |cx| {
2971 // limit to 100 keystrokes to avoid infinite recursion.
2972 for _ in 0..100 {
2973 let keystroke = {
2974 let mut state = keystrokes.borrow_mut();
2975 let Some(keystroke) = state.queue.pop_front() else {
2976 state.dispatched.clear();
2977 state.task.take();
2978 return;
2979 };
2980 keystroke
2981 };
2982 cx.update(|window, cx| {
2983 let focused = window.focused(cx);
2984 window.dispatch_keystroke(keystroke.clone(), cx);
2985 if window.focused(cx) != focused {
2986 // dispatch_keystroke may cause the focus to change.
2987 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
2988 // And we need that to happen before the next keystroke to keep vim mode happy...
2989 // (Note that the tests always do this implicitly, so you must manually test with something like:
2990 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
2991 // )
2992 window.draw(cx).clear();
2993 }
2994 })
2995 .ok();
2996
2997 // Yield between synthetic keystrokes so deferred focus and
2998 // other effects can settle before dispatching the next key.
2999 yield_now().await;
3000 }
3001
3002 *keystrokes.borrow_mut() = Default::default();
3003 log::error!("over 100 keystrokes passed to send_keystrokes");
3004 })
3005 .shared(),
3006 );
3007 }
3008 state.task.clone().unwrap()
3009 }
3010
3011 fn save_all_internal(
3012 &mut self,
3013 mut save_intent: SaveIntent,
3014 window: &mut Window,
3015 cx: &mut Context<Self>,
3016 ) -> Task<Result<bool>> {
3017 if self.project.read(cx).is_disconnected(cx) {
3018 return Task::ready(Ok(true));
3019 }
3020 let dirty_items = self
3021 .panes
3022 .iter()
3023 .flat_map(|pane| {
3024 pane.read(cx).items().filter_map(|item| {
3025 if item.is_dirty(cx) {
3026 item.tab_content_text(0, cx);
3027 Some((pane.downgrade(), item.boxed_clone()))
3028 } else {
3029 None
3030 }
3031 })
3032 })
3033 .collect::<Vec<_>>();
3034
3035 let project = self.project.clone();
3036 cx.spawn_in(window, async move |workspace, cx| {
3037 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3038 let (serialize_tasks, remaining_dirty_items) =
3039 workspace.update_in(cx, |workspace, window, cx| {
3040 let mut remaining_dirty_items = Vec::new();
3041 let mut serialize_tasks = Vec::new();
3042 for (pane, item) in dirty_items {
3043 if let Some(task) = item
3044 .to_serializable_item_handle(cx)
3045 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3046 {
3047 serialize_tasks.push(task);
3048 } else {
3049 remaining_dirty_items.push((pane, item));
3050 }
3051 }
3052 (serialize_tasks, remaining_dirty_items)
3053 })?;
3054
3055 futures::future::try_join_all(serialize_tasks).await?;
3056
3057 if !remaining_dirty_items.is_empty() {
3058 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3059 }
3060
3061 if remaining_dirty_items.len() > 1 {
3062 let answer = workspace.update_in(cx, |_, window, cx| {
3063 let detail = Pane::file_names_for_prompt(
3064 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3065 cx,
3066 );
3067 window.prompt(
3068 PromptLevel::Warning,
3069 "Do you want to save all changes in the following files?",
3070 Some(&detail),
3071 &["Save all", "Discard all", "Cancel"],
3072 cx,
3073 )
3074 })?;
3075 match answer.await.log_err() {
3076 Some(0) => save_intent = SaveIntent::SaveAll,
3077 Some(1) => save_intent = SaveIntent::Skip,
3078 Some(2) => return Ok(false),
3079 _ => {}
3080 }
3081 }
3082
3083 remaining_dirty_items
3084 } else {
3085 dirty_items
3086 };
3087
3088 for (pane, item) in dirty_items {
3089 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3090 (
3091 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3092 item.project_entry_ids(cx),
3093 )
3094 })?;
3095 if (singleton || !project_entry_ids.is_empty())
3096 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3097 {
3098 return Ok(false);
3099 }
3100 }
3101 Ok(true)
3102 })
3103 }
3104
3105 pub fn open_workspace_for_paths(
3106 &mut self,
3107 replace_current_window: bool,
3108 paths: Vec<PathBuf>,
3109 window: &mut Window,
3110 cx: &mut Context<Self>,
3111 ) -> Task<Result<()>> {
3112 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
3113 let is_remote = self.project.read(cx).is_via_collab();
3114 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3115 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3116
3117 let window_to_replace = if replace_current_window {
3118 window_handle
3119 } else if is_remote || has_worktree || has_dirty_items {
3120 None
3121 } else {
3122 window_handle
3123 };
3124 let app_state = self.app_state.clone();
3125
3126 cx.spawn(async move |_, cx| {
3127 cx.update(|cx| {
3128 open_paths(
3129 &paths,
3130 app_state,
3131 OpenOptions {
3132 replace_window: window_to_replace,
3133 ..Default::default()
3134 },
3135 cx,
3136 )
3137 })
3138 .await?;
3139 Ok(())
3140 })
3141 }
3142
3143 #[allow(clippy::type_complexity)]
3144 pub fn open_paths(
3145 &mut self,
3146 mut abs_paths: Vec<PathBuf>,
3147 options: OpenOptions,
3148 pane: Option<WeakEntity<Pane>>,
3149 window: &mut Window,
3150 cx: &mut Context<Self>,
3151 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3152 let fs = self.app_state.fs.clone();
3153
3154 let caller_ordered_abs_paths = abs_paths.clone();
3155
3156 // Sort the paths to ensure we add worktrees for parents before their children.
3157 abs_paths.sort_unstable();
3158 cx.spawn_in(window, async move |this, cx| {
3159 let mut tasks = Vec::with_capacity(abs_paths.len());
3160
3161 for abs_path in &abs_paths {
3162 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3163 OpenVisible::All => Some(true),
3164 OpenVisible::None => Some(false),
3165 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3166 Some(Some(metadata)) => Some(!metadata.is_dir),
3167 Some(None) => Some(true),
3168 None => None,
3169 },
3170 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3171 Some(Some(metadata)) => Some(metadata.is_dir),
3172 Some(None) => Some(false),
3173 None => None,
3174 },
3175 };
3176 let project_path = match visible {
3177 Some(visible) => match this
3178 .update(cx, |this, cx| {
3179 Workspace::project_path_for_path(
3180 this.project.clone(),
3181 abs_path,
3182 visible,
3183 cx,
3184 )
3185 })
3186 .log_err()
3187 {
3188 Some(project_path) => project_path.await.log_err(),
3189 None => None,
3190 },
3191 None => None,
3192 };
3193
3194 let this = this.clone();
3195 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3196 let fs = fs.clone();
3197 let pane = pane.clone();
3198 let task = cx.spawn(async move |cx| {
3199 let (_worktree, project_path) = project_path?;
3200 if fs.is_dir(&abs_path).await {
3201 // Opening a directory should not race to update the active entry.
3202 // We'll select/reveal a deterministic final entry after all paths finish opening.
3203 None
3204 } else {
3205 Some(
3206 this.update_in(cx, |this, window, cx| {
3207 this.open_path(
3208 project_path,
3209 pane,
3210 options.focus.unwrap_or(true),
3211 window,
3212 cx,
3213 )
3214 })
3215 .ok()?
3216 .await,
3217 )
3218 }
3219 });
3220 tasks.push(task);
3221 }
3222
3223 let results = futures::future::join_all(tasks).await;
3224
3225 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3226 let mut winner: Option<(PathBuf, bool)> = None;
3227 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3228 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3229 if !metadata.is_dir {
3230 winner = Some((abs_path, false));
3231 break;
3232 }
3233 if winner.is_none() {
3234 winner = Some((abs_path, true));
3235 }
3236 } else if winner.is_none() {
3237 winner = Some((abs_path, false));
3238 }
3239 }
3240
3241 // Compute the winner entry id on the foreground thread and emit once, after all
3242 // paths finish opening. This avoids races between concurrently-opening paths
3243 // (directories in particular) and makes the resulting project panel selection
3244 // deterministic.
3245 if let Some((winner_abs_path, winner_is_dir)) = winner {
3246 'emit_winner: {
3247 let winner_abs_path: Arc<Path> =
3248 SanitizedPath::new(&winner_abs_path).as_path().into();
3249
3250 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3251 OpenVisible::All => true,
3252 OpenVisible::None => false,
3253 OpenVisible::OnlyFiles => !winner_is_dir,
3254 OpenVisible::OnlyDirectories => winner_is_dir,
3255 };
3256
3257 let Some(worktree_task) = this
3258 .update(cx, |workspace, cx| {
3259 workspace.project.update(cx, |project, cx| {
3260 project.find_or_create_worktree(
3261 winner_abs_path.as_ref(),
3262 visible,
3263 cx,
3264 )
3265 })
3266 })
3267 .ok()
3268 else {
3269 break 'emit_winner;
3270 };
3271
3272 let Ok((worktree, _)) = worktree_task.await else {
3273 break 'emit_winner;
3274 };
3275
3276 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3277 let worktree = worktree.read(cx);
3278 let worktree_abs_path = worktree.abs_path();
3279 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3280 worktree.root_entry()
3281 } else {
3282 winner_abs_path
3283 .strip_prefix(worktree_abs_path.as_ref())
3284 .ok()
3285 .and_then(|relative_path| {
3286 let relative_path =
3287 RelPath::new(relative_path, PathStyle::local())
3288 .log_err()?;
3289 worktree.entry_for_path(&relative_path)
3290 })
3291 }?;
3292 Some(entry.id)
3293 }) else {
3294 break 'emit_winner;
3295 };
3296
3297 this.update(cx, |workspace, cx| {
3298 workspace.project.update(cx, |_, cx| {
3299 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3300 });
3301 })
3302 .ok();
3303 }
3304 }
3305
3306 results
3307 })
3308 }
3309
3310 pub fn open_resolved_path(
3311 &mut self,
3312 path: ResolvedPath,
3313 window: &mut Window,
3314 cx: &mut Context<Self>,
3315 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3316 match path {
3317 ResolvedPath::ProjectPath { project_path, .. } => {
3318 self.open_path(project_path, None, true, window, cx)
3319 }
3320 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3321 PathBuf::from(path),
3322 OpenOptions {
3323 visible: Some(OpenVisible::None),
3324 ..Default::default()
3325 },
3326 window,
3327 cx,
3328 ),
3329 }
3330 }
3331
3332 pub fn absolute_path_of_worktree(
3333 &self,
3334 worktree_id: WorktreeId,
3335 cx: &mut Context<Self>,
3336 ) -> Option<PathBuf> {
3337 self.project
3338 .read(cx)
3339 .worktree_for_id(worktree_id, cx)
3340 // TODO: use `abs_path` or `root_dir`
3341 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3342 }
3343
3344 fn add_folder_to_project(
3345 &mut self,
3346 _: &AddFolderToProject,
3347 window: &mut Window,
3348 cx: &mut Context<Self>,
3349 ) {
3350 let project = self.project.read(cx);
3351 if project.is_via_collab() {
3352 self.show_error(
3353 &anyhow!("You cannot add folders to someone else's project"),
3354 cx,
3355 );
3356 return;
3357 }
3358 let paths = self.prompt_for_open_path(
3359 PathPromptOptions {
3360 files: false,
3361 directories: true,
3362 multiple: true,
3363 prompt: None,
3364 },
3365 DirectoryLister::Project(self.project.clone()),
3366 window,
3367 cx,
3368 );
3369 cx.spawn_in(window, async move |this, cx| {
3370 if let Some(paths) = paths.await.log_err().flatten() {
3371 let results = this
3372 .update_in(cx, |this, window, cx| {
3373 this.open_paths(
3374 paths,
3375 OpenOptions {
3376 visible: Some(OpenVisible::All),
3377 ..Default::default()
3378 },
3379 None,
3380 window,
3381 cx,
3382 )
3383 })?
3384 .await;
3385 for result in results.into_iter().flatten() {
3386 result.log_err();
3387 }
3388 }
3389 anyhow::Ok(())
3390 })
3391 .detach_and_log_err(cx);
3392 }
3393
3394 pub fn project_path_for_path(
3395 project: Entity<Project>,
3396 abs_path: &Path,
3397 visible: bool,
3398 cx: &mut App,
3399 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3400 let entry = project.update(cx, |project, cx| {
3401 project.find_or_create_worktree(abs_path, visible, cx)
3402 });
3403 cx.spawn(async move |cx| {
3404 let (worktree, path) = entry.await?;
3405 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3406 Ok((worktree, ProjectPath { worktree_id, path }))
3407 })
3408 }
3409
3410 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3411 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3412 }
3413
3414 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3415 self.items_of_type(cx).max_by_key(|item| item.item_id())
3416 }
3417
3418 pub fn items_of_type<'a, T: Item>(
3419 &'a self,
3420 cx: &'a App,
3421 ) -> impl 'a + Iterator<Item = Entity<T>> {
3422 self.panes
3423 .iter()
3424 .flat_map(|pane| pane.read(cx).items_of_type())
3425 }
3426
3427 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3428 self.active_pane().read(cx).active_item()
3429 }
3430
3431 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3432 let item = self.active_item(cx)?;
3433 item.to_any_view().downcast::<I>().ok()
3434 }
3435
3436 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3437 self.active_item(cx).and_then(|item| item.project_path(cx))
3438 }
3439
3440 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3441 self.recent_navigation_history_iter(cx)
3442 .filter_map(|(path, abs_path)| {
3443 let worktree = self
3444 .project
3445 .read(cx)
3446 .worktree_for_id(path.worktree_id, cx)?;
3447 if worktree.read(cx).is_visible() {
3448 abs_path
3449 } else {
3450 None
3451 }
3452 })
3453 .next()
3454 }
3455
3456 pub fn save_active_item(
3457 &mut self,
3458 save_intent: SaveIntent,
3459 window: &mut Window,
3460 cx: &mut App,
3461 ) -> Task<Result<()>> {
3462 let project = self.project.clone();
3463 let pane = self.active_pane();
3464 let item = pane.read(cx).active_item();
3465 let pane = pane.downgrade();
3466
3467 window.spawn(cx, async move |cx| {
3468 if let Some(item) = item {
3469 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3470 .await
3471 .map(|_| ())
3472 } else {
3473 Ok(())
3474 }
3475 })
3476 }
3477
3478 pub fn close_inactive_items_and_panes(
3479 &mut self,
3480 action: &CloseInactiveTabsAndPanes,
3481 window: &mut Window,
3482 cx: &mut Context<Self>,
3483 ) {
3484 if let Some(task) = self.close_all_internal(
3485 true,
3486 action.save_intent.unwrap_or(SaveIntent::Close),
3487 window,
3488 cx,
3489 ) {
3490 task.detach_and_log_err(cx)
3491 }
3492 }
3493
3494 pub fn close_all_items_and_panes(
3495 &mut self,
3496 action: &CloseAllItemsAndPanes,
3497 window: &mut Window,
3498 cx: &mut Context<Self>,
3499 ) {
3500 if let Some(task) = self.close_all_internal(
3501 false,
3502 action.save_intent.unwrap_or(SaveIntent::Close),
3503 window,
3504 cx,
3505 ) {
3506 task.detach_and_log_err(cx)
3507 }
3508 }
3509
3510 /// Closes the active item across all panes.
3511 pub fn close_item_in_all_panes(
3512 &mut self,
3513 action: &CloseItemInAllPanes,
3514 window: &mut Window,
3515 cx: &mut Context<Self>,
3516 ) {
3517 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3518 return;
3519 };
3520
3521 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3522 let close_pinned = action.close_pinned;
3523
3524 if let Some(project_path) = active_item.project_path(cx) {
3525 self.close_items_with_project_path(
3526 &project_path,
3527 save_intent,
3528 close_pinned,
3529 window,
3530 cx,
3531 );
3532 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3533 let item_id = active_item.item_id();
3534 self.active_pane().update(cx, |pane, cx| {
3535 pane.close_item_by_id(item_id, save_intent, window, cx)
3536 .detach_and_log_err(cx);
3537 });
3538 }
3539 }
3540
3541 /// Closes all items with the given project path across all panes.
3542 pub fn close_items_with_project_path(
3543 &mut self,
3544 project_path: &ProjectPath,
3545 save_intent: SaveIntent,
3546 close_pinned: bool,
3547 window: &mut Window,
3548 cx: &mut Context<Self>,
3549 ) {
3550 let panes = self.panes().to_vec();
3551 for pane in panes {
3552 pane.update(cx, |pane, cx| {
3553 pane.close_items_for_project_path(
3554 project_path,
3555 save_intent,
3556 close_pinned,
3557 window,
3558 cx,
3559 )
3560 .detach_and_log_err(cx);
3561 });
3562 }
3563 }
3564
3565 fn close_all_internal(
3566 &mut self,
3567 retain_active_pane: bool,
3568 save_intent: SaveIntent,
3569 window: &mut Window,
3570 cx: &mut Context<Self>,
3571 ) -> Option<Task<Result<()>>> {
3572 let current_pane = self.active_pane();
3573
3574 let mut tasks = Vec::new();
3575
3576 if retain_active_pane {
3577 let current_pane_close = current_pane.update(cx, |pane, cx| {
3578 pane.close_other_items(
3579 &CloseOtherItems {
3580 save_intent: None,
3581 close_pinned: false,
3582 },
3583 None,
3584 window,
3585 cx,
3586 )
3587 });
3588
3589 tasks.push(current_pane_close);
3590 }
3591
3592 for pane in self.panes() {
3593 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3594 continue;
3595 }
3596
3597 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3598 pane.close_all_items(
3599 &CloseAllItems {
3600 save_intent: Some(save_intent),
3601 close_pinned: false,
3602 },
3603 window,
3604 cx,
3605 )
3606 });
3607
3608 tasks.push(close_pane_items)
3609 }
3610
3611 if tasks.is_empty() {
3612 None
3613 } else {
3614 Some(cx.spawn_in(window, async move |_, _| {
3615 for task in tasks {
3616 task.await?
3617 }
3618 Ok(())
3619 }))
3620 }
3621 }
3622
3623 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3624 self.dock_at_position(position).read(cx).is_open()
3625 }
3626
3627 pub fn toggle_dock(
3628 &mut self,
3629 dock_side: DockPosition,
3630 window: &mut Window,
3631 cx: &mut Context<Self>,
3632 ) {
3633 let mut focus_center = false;
3634 let mut reveal_dock = false;
3635
3636 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3637 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3638
3639 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3640 telemetry::event!(
3641 "Panel Button Clicked",
3642 name = panel.persistent_name(),
3643 toggle_state = !was_visible
3644 );
3645 }
3646 if was_visible {
3647 self.save_open_dock_positions(cx);
3648 }
3649
3650 let dock = self.dock_at_position(dock_side);
3651 dock.update(cx, |dock, cx| {
3652 dock.set_open(!was_visible, window, cx);
3653
3654 if dock.active_panel().is_none() {
3655 let Some(panel_ix) = dock
3656 .first_enabled_panel_idx(cx)
3657 .log_with_level(log::Level::Info)
3658 else {
3659 return;
3660 };
3661 dock.activate_panel(panel_ix, window, cx);
3662 }
3663
3664 if let Some(active_panel) = dock.active_panel() {
3665 if was_visible {
3666 if active_panel
3667 .panel_focus_handle(cx)
3668 .contains_focused(window, cx)
3669 {
3670 focus_center = true;
3671 }
3672 } else {
3673 let focus_handle = &active_panel.panel_focus_handle(cx);
3674 window.focus(focus_handle, cx);
3675 reveal_dock = true;
3676 }
3677 }
3678 });
3679
3680 if reveal_dock {
3681 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3682 }
3683
3684 if focus_center {
3685 self.active_pane
3686 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3687 }
3688
3689 cx.notify();
3690 self.serialize_workspace(window, cx);
3691 }
3692
3693 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3694 self.all_docks().into_iter().find(|&dock| {
3695 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3696 })
3697 }
3698
3699 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3700 if let Some(dock) = self.active_dock(window, cx).cloned() {
3701 self.save_open_dock_positions(cx);
3702 dock.update(cx, |dock, cx| {
3703 dock.set_open(false, window, cx);
3704 });
3705 return true;
3706 }
3707 false
3708 }
3709
3710 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3711 self.save_open_dock_positions(cx);
3712 for dock in self.all_docks() {
3713 dock.update(cx, |dock, cx| {
3714 dock.set_open(false, window, cx);
3715 });
3716 }
3717
3718 cx.focus_self(window);
3719 cx.notify();
3720 self.serialize_workspace(window, cx);
3721 }
3722
3723 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
3724 self.all_docks()
3725 .into_iter()
3726 .filter_map(|dock| {
3727 let dock_ref = dock.read(cx);
3728 if dock_ref.is_open() {
3729 Some(dock_ref.position())
3730 } else {
3731 None
3732 }
3733 })
3734 .collect()
3735 }
3736
3737 /// Saves the positions of currently open docks.
3738 ///
3739 /// Updates `last_open_dock_positions` with positions of all currently open
3740 /// docks, to later be restored by the 'Toggle All Docks' action.
3741 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
3742 let open_dock_positions = self.get_open_dock_positions(cx);
3743 if !open_dock_positions.is_empty() {
3744 self.last_open_dock_positions = open_dock_positions;
3745 }
3746 }
3747
3748 /// Toggles all docks between open and closed states.
3749 ///
3750 /// If any docks are open, closes all and remembers their positions. If all
3751 /// docks are closed, restores the last remembered dock configuration.
3752 fn toggle_all_docks(
3753 &mut self,
3754 _: &ToggleAllDocks,
3755 window: &mut Window,
3756 cx: &mut Context<Self>,
3757 ) {
3758 let open_dock_positions = self.get_open_dock_positions(cx);
3759
3760 if !open_dock_positions.is_empty() {
3761 self.close_all_docks(window, cx);
3762 } else if !self.last_open_dock_positions.is_empty() {
3763 self.restore_last_open_docks(window, cx);
3764 }
3765 }
3766
3767 /// Reopens docks from the most recently remembered configuration.
3768 ///
3769 /// Opens all docks whose positions are stored in `last_open_dock_positions`
3770 /// and clears the stored positions.
3771 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3772 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
3773
3774 for position in positions_to_open {
3775 let dock = self.dock_at_position(position);
3776 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
3777 }
3778
3779 cx.focus_self(window);
3780 cx.notify();
3781 self.serialize_workspace(window, cx);
3782 }
3783
3784 /// Transfer focus to the panel of the given type.
3785 pub fn focus_panel<T: Panel>(
3786 &mut self,
3787 window: &mut Window,
3788 cx: &mut Context<Self>,
3789 ) -> Option<Entity<T>> {
3790 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
3791 panel.to_any().downcast().ok()
3792 }
3793
3794 /// Focus the panel of the given type if it isn't already focused. If it is
3795 /// already focused, then transfer focus back to the workspace center.
3796 /// When the `close_panel_on_toggle` setting is enabled, also closes the
3797 /// panel when transferring focus back to the center.
3798 pub fn toggle_panel_focus<T: Panel>(
3799 &mut self,
3800 window: &mut Window,
3801 cx: &mut Context<Self>,
3802 ) -> bool {
3803 let mut did_focus_panel = false;
3804 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
3805 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
3806 did_focus_panel
3807 });
3808
3809 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
3810 self.close_panel::<T>(window, cx);
3811 }
3812
3813 telemetry::event!(
3814 "Panel Button Clicked",
3815 name = T::persistent_name(),
3816 toggle_state = did_focus_panel
3817 );
3818
3819 did_focus_panel
3820 }
3821
3822 pub fn activate_panel_for_proto_id(
3823 &mut self,
3824 panel_id: PanelId,
3825 window: &mut Window,
3826 cx: &mut Context<Self>,
3827 ) -> Option<Arc<dyn PanelHandle>> {
3828 let mut panel = None;
3829 for dock in self.all_docks() {
3830 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
3831 panel = dock.update(cx, |dock, cx| {
3832 dock.activate_panel(panel_index, window, cx);
3833 dock.set_open(true, window, cx);
3834 dock.active_panel().cloned()
3835 });
3836 break;
3837 }
3838 }
3839
3840 if panel.is_some() {
3841 cx.notify();
3842 self.serialize_workspace(window, cx);
3843 }
3844
3845 panel
3846 }
3847
3848 /// Focus or unfocus the given panel type, depending on the given callback.
3849 fn focus_or_unfocus_panel<T: Panel>(
3850 &mut self,
3851 window: &mut Window,
3852 cx: &mut Context<Self>,
3853 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
3854 ) -> Option<Arc<dyn PanelHandle>> {
3855 let mut result_panel = None;
3856 let mut serialize = false;
3857 for dock in self.all_docks() {
3858 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3859 let mut focus_center = false;
3860 let panel = dock.update(cx, |dock, cx| {
3861 dock.activate_panel(panel_index, window, cx);
3862
3863 let panel = dock.active_panel().cloned();
3864 if let Some(panel) = panel.as_ref() {
3865 if should_focus(&**panel, window, cx) {
3866 dock.set_open(true, window, cx);
3867 panel.panel_focus_handle(cx).focus(window, cx);
3868 } else {
3869 focus_center = true;
3870 }
3871 }
3872 panel
3873 });
3874
3875 if focus_center {
3876 self.active_pane
3877 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3878 }
3879
3880 result_panel = panel;
3881 serialize = true;
3882 break;
3883 }
3884 }
3885
3886 if serialize {
3887 self.serialize_workspace(window, cx);
3888 }
3889
3890 cx.notify();
3891 result_panel
3892 }
3893
3894 /// Open the panel of the given type
3895 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3896 for dock in self.all_docks() {
3897 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3898 dock.update(cx, |dock, cx| {
3899 dock.activate_panel(panel_index, window, cx);
3900 dock.set_open(true, window, cx);
3901 });
3902 }
3903 }
3904 }
3905
3906 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
3907 for dock in self.all_docks().iter() {
3908 dock.update(cx, |dock, cx| {
3909 if dock.panel::<T>().is_some() {
3910 dock.set_open(false, window, cx)
3911 }
3912 })
3913 }
3914 }
3915
3916 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
3917 self.all_docks()
3918 .iter()
3919 .find_map(|dock| dock.read(cx).panel::<T>())
3920 }
3921
3922 fn dismiss_zoomed_items_to_reveal(
3923 &mut self,
3924 dock_to_reveal: Option<DockPosition>,
3925 window: &mut Window,
3926 cx: &mut Context<Self>,
3927 ) {
3928 // If a center pane is zoomed, unzoom it.
3929 for pane in &self.panes {
3930 if pane != &self.active_pane || dock_to_reveal.is_some() {
3931 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
3932 }
3933 }
3934
3935 // If another dock is zoomed, hide it.
3936 let mut focus_center = false;
3937 for dock in self.all_docks() {
3938 dock.update(cx, |dock, cx| {
3939 if Some(dock.position()) != dock_to_reveal
3940 && let Some(panel) = dock.active_panel()
3941 && panel.is_zoomed(window, cx)
3942 {
3943 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
3944 dock.set_open(false, window, cx);
3945 }
3946 });
3947 }
3948
3949 if focus_center {
3950 self.active_pane
3951 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3952 }
3953
3954 if self.zoomed_position != dock_to_reveal {
3955 self.zoomed = None;
3956 self.zoomed_position = None;
3957 cx.emit(Event::ZoomChanged);
3958 }
3959
3960 cx.notify();
3961 }
3962
3963 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
3964 let pane = cx.new(|cx| {
3965 let mut pane = Pane::new(
3966 self.weak_handle(),
3967 self.project.clone(),
3968 self.pane_history_timestamp.clone(),
3969 None,
3970 NewFile.boxed_clone(),
3971 true,
3972 window,
3973 cx,
3974 );
3975 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
3976 pane
3977 });
3978 cx.subscribe_in(&pane, window, Self::handle_pane_event)
3979 .detach();
3980 self.panes.push(pane.clone());
3981
3982 window.focus(&pane.focus_handle(cx), cx);
3983
3984 cx.emit(Event::PaneAdded(pane.clone()));
3985 pane
3986 }
3987
3988 pub fn add_item_to_center(
3989 &mut self,
3990 item: Box<dyn ItemHandle>,
3991 window: &mut Window,
3992 cx: &mut Context<Self>,
3993 ) -> bool {
3994 if let Some(center_pane) = self.last_active_center_pane.clone() {
3995 if let Some(center_pane) = center_pane.upgrade() {
3996 center_pane.update(cx, |pane, cx| {
3997 pane.add_item(item, true, true, None, window, cx)
3998 });
3999 true
4000 } else {
4001 false
4002 }
4003 } else {
4004 false
4005 }
4006 }
4007
4008 pub fn add_item_to_active_pane(
4009 &mut self,
4010 item: Box<dyn ItemHandle>,
4011 destination_index: Option<usize>,
4012 focus_item: bool,
4013 window: &mut Window,
4014 cx: &mut App,
4015 ) {
4016 self.add_item(
4017 self.active_pane.clone(),
4018 item,
4019 destination_index,
4020 false,
4021 focus_item,
4022 window,
4023 cx,
4024 )
4025 }
4026
4027 pub fn add_item(
4028 &mut self,
4029 pane: Entity<Pane>,
4030 item: Box<dyn ItemHandle>,
4031 destination_index: Option<usize>,
4032 activate_pane: bool,
4033 focus_item: bool,
4034 window: &mut Window,
4035 cx: &mut App,
4036 ) {
4037 pane.update(cx, |pane, cx| {
4038 pane.add_item(
4039 item,
4040 activate_pane,
4041 focus_item,
4042 destination_index,
4043 window,
4044 cx,
4045 )
4046 });
4047 }
4048
4049 pub fn split_item(
4050 &mut self,
4051 split_direction: SplitDirection,
4052 item: Box<dyn ItemHandle>,
4053 window: &mut Window,
4054 cx: &mut Context<Self>,
4055 ) {
4056 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4057 self.add_item(new_pane, item, None, true, true, window, cx);
4058 }
4059
4060 pub fn open_abs_path(
4061 &mut self,
4062 abs_path: PathBuf,
4063 options: OpenOptions,
4064 window: &mut Window,
4065 cx: &mut Context<Self>,
4066 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4067 cx.spawn_in(window, async move |workspace, cx| {
4068 let open_paths_task_result = workspace
4069 .update_in(cx, |workspace, window, cx| {
4070 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4071 })
4072 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4073 .await;
4074 anyhow::ensure!(
4075 open_paths_task_result.len() == 1,
4076 "open abs path {abs_path:?} task returned incorrect number of results"
4077 );
4078 match open_paths_task_result
4079 .into_iter()
4080 .next()
4081 .expect("ensured single task result")
4082 {
4083 Some(open_result) => {
4084 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4085 }
4086 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4087 }
4088 })
4089 }
4090
4091 pub fn split_abs_path(
4092 &mut self,
4093 abs_path: PathBuf,
4094 visible: bool,
4095 window: &mut Window,
4096 cx: &mut Context<Self>,
4097 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4098 let project_path_task =
4099 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4100 cx.spawn_in(window, async move |this, cx| {
4101 let (_, path) = project_path_task.await?;
4102 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4103 .await
4104 })
4105 }
4106
4107 pub fn open_path(
4108 &mut self,
4109 path: impl Into<ProjectPath>,
4110 pane: Option<WeakEntity<Pane>>,
4111 focus_item: bool,
4112 window: &mut Window,
4113 cx: &mut App,
4114 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4115 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4116 }
4117
4118 pub fn open_path_preview(
4119 &mut self,
4120 path: impl Into<ProjectPath>,
4121 pane: Option<WeakEntity<Pane>>,
4122 focus_item: bool,
4123 allow_preview: bool,
4124 activate: bool,
4125 window: &mut Window,
4126 cx: &mut App,
4127 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4128 let pane = pane.unwrap_or_else(|| {
4129 self.last_active_center_pane.clone().unwrap_or_else(|| {
4130 self.panes
4131 .first()
4132 .expect("There must be an active pane")
4133 .downgrade()
4134 })
4135 });
4136
4137 let project_path = path.into();
4138 let task = self.load_path(project_path.clone(), window, cx);
4139 window.spawn(cx, async move |cx| {
4140 let (project_entry_id, build_item) = task.await?;
4141
4142 pane.update_in(cx, |pane, window, cx| {
4143 pane.open_item(
4144 project_entry_id,
4145 project_path,
4146 focus_item,
4147 allow_preview,
4148 activate,
4149 None,
4150 window,
4151 cx,
4152 build_item,
4153 )
4154 })
4155 })
4156 }
4157
4158 pub fn split_path(
4159 &mut self,
4160 path: impl Into<ProjectPath>,
4161 window: &mut Window,
4162 cx: &mut Context<Self>,
4163 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4164 self.split_path_preview(path, false, None, window, cx)
4165 }
4166
4167 pub fn split_path_preview(
4168 &mut self,
4169 path: impl Into<ProjectPath>,
4170 allow_preview: bool,
4171 split_direction: Option<SplitDirection>,
4172 window: &mut Window,
4173 cx: &mut Context<Self>,
4174 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4175 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4176 self.panes
4177 .first()
4178 .expect("There must be an active pane")
4179 .downgrade()
4180 });
4181
4182 if let Member::Pane(center_pane) = &self.center.root
4183 && center_pane.read(cx).items_len() == 0
4184 {
4185 return self.open_path(path, Some(pane), true, window, cx);
4186 }
4187
4188 let project_path = path.into();
4189 let task = self.load_path(project_path.clone(), window, cx);
4190 cx.spawn_in(window, async move |this, cx| {
4191 let (project_entry_id, build_item) = task.await?;
4192 this.update_in(cx, move |this, window, cx| -> Option<_> {
4193 let pane = pane.upgrade()?;
4194 let new_pane = this.split_pane(
4195 pane,
4196 split_direction.unwrap_or(SplitDirection::Right),
4197 window,
4198 cx,
4199 );
4200 new_pane.update(cx, |new_pane, cx| {
4201 Some(new_pane.open_item(
4202 project_entry_id,
4203 project_path,
4204 true,
4205 allow_preview,
4206 true,
4207 None,
4208 window,
4209 cx,
4210 build_item,
4211 ))
4212 })
4213 })
4214 .map(|option| option.context("pane was dropped"))?
4215 })
4216 }
4217
4218 fn load_path(
4219 &mut self,
4220 path: ProjectPath,
4221 window: &mut Window,
4222 cx: &mut App,
4223 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4224 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4225 registry.open_path(self.project(), &path, window, cx)
4226 }
4227
4228 pub fn find_project_item<T>(
4229 &self,
4230 pane: &Entity<Pane>,
4231 project_item: &Entity<T::Item>,
4232 cx: &App,
4233 ) -> Option<Entity<T>>
4234 where
4235 T: ProjectItem,
4236 {
4237 use project::ProjectItem as _;
4238 let project_item = project_item.read(cx);
4239 let entry_id = project_item.entry_id(cx);
4240 let project_path = project_item.project_path(cx);
4241
4242 let mut item = None;
4243 if let Some(entry_id) = entry_id {
4244 item = pane.read(cx).item_for_entry(entry_id, cx);
4245 }
4246 if item.is_none()
4247 && let Some(project_path) = project_path
4248 {
4249 item = pane.read(cx).item_for_path(project_path, cx);
4250 }
4251
4252 item.and_then(|item| item.downcast::<T>())
4253 }
4254
4255 pub fn is_project_item_open<T>(
4256 &self,
4257 pane: &Entity<Pane>,
4258 project_item: &Entity<T::Item>,
4259 cx: &App,
4260 ) -> bool
4261 where
4262 T: ProjectItem,
4263 {
4264 self.find_project_item::<T>(pane, project_item, cx)
4265 .is_some()
4266 }
4267
4268 pub fn open_project_item<T>(
4269 &mut self,
4270 pane: Entity<Pane>,
4271 project_item: Entity<T::Item>,
4272 activate_pane: bool,
4273 focus_item: bool,
4274 keep_old_preview: bool,
4275 allow_new_preview: bool,
4276 window: &mut Window,
4277 cx: &mut Context<Self>,
4278 ) -> Entity<T>
4279 where
4280 T: ProjectItem,
4281 {
4282 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4283
4284 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4285 if !keep_old_preview
4286 && let Some(old_id) = old_item_id
4287 && old_id != item.item_id()
4288 {
4289 // switching to a different item, so unpreview old active item
4290 pane.update(cx, |pane, _| {
4291 pane.unpreview_item_if_preview(old_id);
4292 });
4293 }
4294
4295 self.activate_item(&item, activate_pane, focus_item, window, cx);
4296 if !allow_new_preview {
4297 pane.update(cx, |pane, _| {
4298 pane.unpreview_item_if_preview(item.item_id());
4299 });
4300 }
4301 return item;
4302 }
4303
4304 let item = pane.update(cx, |pane, cx| {
4305 cx.new(|cx| {
4306 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4307 })
4308 });
4309 let mut destination_index = None;
4310 pane.update(cx, |pane, cx| {
4311 if !keep_old_preview && let Some(old_id) = old_item_id {
4312 pane.unpreview_item_if_preview(old_id);
4313 }
4314 if allow_new_preview {
4315 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4316 }
4317 });
4318
4319 self.add_item(
4320 pane,
4321 Box::new(item.clone()),
4322 destination_index,
4323 activate_pane,
4324 focus_item,
4325 window,
4326 cx,
4327 );
4328 item
4329 }
4330
4331 pub fn open_shared_screen(
4332 &mut self,
4333 peer_id: PeerId,
4334 window: &mut Window,
4335 cx: &mut Context<Self>,
4336 ) {
4337 if let Some(shared_screen) =
4338 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4339 {
4340 self.active_pane.update(cx, |pane, cx| {
4341 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4342 });
4343 }
4344 }
4345
4346 pub fn activate_item(
4347 &mut self,
4348 item: &dyn ItemHandle,
4349 activate_pane: bool,
4350 focus_item: bool,
4351 window: &mut Window,
4352 cx: &mut App,
4353 ) -> bool {
4354 let result = self.panes.iter().find_map(|pane| {
4355 pane.read(cx)
4356 .index_for_item(item)
4357 .map(|ix| (pane.clone(), ix))
4358 });
4359 if let Some((pane, ix)) = result {
4360 pane.update(cx, |pane, cx| {
4361 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4362 });
4363 true
4364 } else {
4365 false
4366 }
4367 }
4368
4369 fn activate_pane_at_index(
4370 &mut self,
4371 action: &ActivatePane,
4372 window: &mut Window,
4373 cx: &mut Context<Self>,
4374 ) {
4375 let panes = self.center.panes();
4376 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4377 window.focus(&pane.focus_handle(cx), cx);
4378 } else {
4379 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4380 .detach();
4381 }
4382 }
4383
4384 fn move_item_to_pane_at_index(
4385 &mut self,
4386 action: &MoveItemToPane,
4387 window: &mut Window,
4388 cx: &mut Context<Self>,
4389 ) {
4390 let panes = self.center.panes();
4391 let destination = match panes.get(action.destination) {
4392 Some(&destination) => destination.clone(),
4393 None => {
4394 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4395 return;
4396 }
4397 let direction = SplitDirection::Right;
4398 let split_off_pane = self
4399 .find_pane_in_direction(direction, cx)
4400 .unwrap_or_else(|| self.active_pane.clone());
4401 let new_pane = self.add_pane(window, cx);
4402 self.center.split(&split_off_pane, &new_pane, direction, cx);
4403 new_pane
4404 }
4405 };
4406
4407 if action.clone {
4408 if self
4409 .active_pane
4410 .read(cx)
4411 .active_item()
4412 .is_some_and(|item| item.can_split(cx))
4413 {
4414 clone_active_item(
4415 self.database_id(),
4416 &self.active_pane,
4417 &destination,
4418 action.focus,
4419 window,
4420 cx,
4421 );
4422 return;
4423 }
4424 }
4425 move_active_item(
4426 &self.active_pane,
4427 &destination,
4428 action.focus,
4429 true,
4430 window,
4431 cx,
4432 )
4433 }
4434
4435 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4436 let panes = self.center.panes();
4437 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4438 let next_ix = (ix + 1) % panes.len();
4439 let next_pane = panes[next_ix].clone();
4440 window.focus(&next_pane.focus_handle(cx), cx);
4441 }
4442 }
4443
4444 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4445 let panes = self.center.panes();
4446 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4447 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4448 let prev_pane = panes[prev_ix].clone();
4449 window.focus(&prev_pane.focus_handle(cx), cx);
4450 }
4451 }
4452
4453 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4454 let last_pane = self.center.last_pane();
4455 window.focus(&last_pane.focus_handle(cx), cx);
4456 }
4457
4458 pub fn activate_pane_in_direction(
4459 &mut self,
4460 direction: SplitDirection,
4461 window: &mut Window,
4462 cx: &mut App,
4463 ) {
4464 use ActivateInDirectionTarget as Target;
4465 enum Origin {
4466 LeftDock,
4467 RightDock,
4468 BottomDock,
4469 Center,
4470 }
4471
4472 let origin: Origin = [
4473 (&self.left_dock, Origin::LeftDock),
4474 (&self.right_dock, Origin::RightDock),
4475 (&self.bottom_dock, Origin::BottomDock),
4476 ]
4477 .into_iter()
4478 .find_map(|(dock, origin)| {
4479 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4480 Some(origin)
4481 } else {
4482 None
4483 }
4484 })
4485 .unwrap_or(Origin::Center);
4486
4487 let get_last_active_pane = || {
4488 let pane = self
4489 .last_active_center_pane
4490 .clone()
4491 .unwrap_or_else(|| {
4492 self.panes
4493 .first()
4494 .expect("There must be an active pane")
4495 .downgrade()
4496 })
4497 .upgrade()?;
4498 (pane.read(cx).items_len() != 0).then_some(pane)
4499 };
4500
4501 let try_dock =
4502 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4503
4504 let target = match (origin, direction) {
4505 // We're in the center, so we first try to go to a different pane,
4506 // otherwise try to go to a dock.
4507 (Origin::Center, direction) => {
4508 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4509 Some(Target::Pane(pane))
4510 } else {
4511 match direction {
4512 SplitDirection::Up => None,
4513 SplitDirection::Down => try_dock(&self.bottom_dock),
4514 SplitDirection::Left => try_dock(&self.left_dock),
4515 SplitDirection::Right => try_dock(&self.right_dock),
4516 }
4517 }
4518 }
4519
4520 (Origin::LeftDock, SplitDirection::Right) => {
4521 if let Some(last_active_pane) = get_last_active_pane() {
4522 Some(Target::Pane(last_active_pane))
4523 } else {
4524 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4525 }
4526 }
4527
4528 (Origin::LeftDock, SplitDirection::Down)
4529 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4530
4531 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4532 (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
4533 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4534
4535 (Origin::RightDock, SplitDirection::Left) => {
4536 if let Some(last_active_pane) = get_last_active_pane() {
4537 Some(Target::Pane(last_active_pane))
4538 } else {
4539 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
4540 }
4541 }
4542
4543 _ => None,
4544 };
4545
4546 match target {
4547 Some(ActivateInDirectionTarget::Pane(pane)) => {
4548 let pane = pane.read(cx);
4549 if let Some(item) = pane.active_item() {
4550 item.item_focus_handle(cx).focus(window, cx);
4551 } else {
4552 log::error!(
4553 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4554 );
4555 }
4556 }
4557 Some(ActivateInDirectionTarget::Dock(dock)) => {
4558 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4559 window.defer(cx, move |window, cx| {
4560 let dock = dock.read(cx);
4561 if let Some(panel) = dock.active_panel() {
4562 panel.panel_focus_handle(cx).focus(window, cx);
4563 } else {
4564 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4565 }
4566 })
4567 }
4568 None => {}
4569 }
4570 }
4571
4572 pub fn move_item_to_pane_in_direction(
4573 &mut self,
4574 action: &MoveItemToPaneInDirection,
4575 window: &mut Window,
4576 cx: &mut Context<Self>,
4577 ) {
4578 let destination = match self.find_pane_in_direction(action.direction, cx) {
4579 Some(destination) => destination,
4580 None => {
4581 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4582 return;
4583 }
4584 let new_pane = self.add_pane(window, cx);
4585 self.center
4586 .split(&self.active_pane, &new_pane, action.direction, cx);
4587 new_pane
4588 }
4589 };
4590
4591 if action.clone {
4592 if self
4593 .active_pane
4594 .read(cx)
4595 .active_item()
4596 .is_some_and(|item| item.can_split(cx))
4597 {
4598 clone_active_item(
4599 self.database_id(),
4600 &self.active_pane,
4601 &destination,
4602 action.focus,
4603 window,
4604 cx,
4605 );
4606 return;
4607 }
4608 }
4609 move_active_item(
4610 &self.active_pane,
4611 &destination,
4612 action.focus,
4613 true,
4614 window,
4615 cx,
4616 );
4617 }
4618
4619 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4620 self.center.bounding_box_for_pane(pane)
4621 }
4622
4623 pub fn find_pane_in_direction(
4624 &mut self,
4625 direction: SplitDirection,
4626 cx: &App,
4627 ) -> Option<Entity<Pane>> {
4628 self.center
4629 .find_pane_in_direction(&self.active_pane, direction, cx)
4630 .cloned()
4631 }
4632
4633 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4634 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4635 self.center.swap(&self.active_pane, &to, cx);
4636 cx.notify();
4637 }
4638 }
4639
4640 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4641 if self
4642 .center
4643 .move_to_border(&self.active_pane, direction, cx)
4644 .unwrap()
4645 {
4646 cx.notify();
4647 }
4648 }
4649
4650 pub fn resize_pane(
4651 &mut self,
4652 axis: gpui::Axis,
4653 amount: Pixels,
4654 window: &mut Window,
4655 cx: &mut Context<Self>,
4656 ) {
4657 let docks = self.all_docks();
4658 let active_dock = docks
4659 .into_iter()
4660 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4661
4662 if let Some(dock) = active_dock {
4663 let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
4664 return;
4665 };
4666 match dock.read(cx).position() {
4667 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4668 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4669 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4670 }
4671 } else {
4672 self.center
4673 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
4674 }
4675 cx.notify();
4676 }
4677
4678 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
4679 self.center.reset_pane_sizes(cx);
4680 cx.notify();
4681 }
4682
4683 fn handle_pane_focused(
4684 &mut self,
4685 pane: Entity<Pane>,
4686 window: &mut Window,
4687 cx: &mut Context<Self>,
4688 ) {
4689 // This is explicitly hoisted out of the following check for pane identity as
4690 // terminal panel panes are not registered as a center panes.
4691 self.status_bar.update(cx, |status_bar, cx| {
4692 status_bar.set_active_pane(&pane, window, cx);
4693 });
4694 if self.active_pane != pane {
4695 self.set_active_pane(&pane, window, cx);
4696 }
4697
4698 if self.last_active_center_pane.is_none() {
4699 self.last_active_center_pane = Some(pane.downgrade());
4700 }
4701
4702 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
4703 // This prevents the dock from closing when focus events fire during window activation.
4704 // We also preserve any dock whose active panel itself has focus — this covers
4705 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
4706 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
4707 let dock_read = dock.read(cx);
4708 if let Some(panel) = dock_read.active_panel() {
4709 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
4710 || panel.panel_focus_handle(cx).contains_focused(window, cx)
4711 {
4712 return Some(dock_read.position());
4713 }
4714 }
4715 None
4716 });
4717
4718 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
4719 if pane.read(cx).is_zoomed() {
4720 self.zoomed = Some(pane.downgrade().into());
4721 } else {
4722 self.zoomed = None;
4723 }
4724 self.zoomed_position = None;
4725 cx.emit(Event::ZoomChanged);
4726 self.update_active_view_for_followers(window, cx);
4727 pane.update(cx, |pane, _| {
4728 pane.track_alternate_file_items();
4729 });
4730
4731 cx.notify();
4732 }
4733
4734 fn set_active_pane(
4735 &mut self,
4736 pane: &Entity<Pane>,
4737 window: &mut Window,
4738 cx: &mut Context<Self>,
4739 ) {
4740 self.active_pane = pane.clone();
4741 self.active_item_path_changed(true, window, cx);
4742 self.last_active_center_pane = Some(pane.downgrade());
4743 }
4744
4745 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4746 self.update_active_view_for_followers(window, cx);
4747 }
4748
4749 fn handle_pane_event(
4750 &mut self,
4751 pane: &Entity<Pane>,
4752 event: &pane::Event,
4753 window: &mut Window,
4754 cx: &mut Context<Self>,
4755 ) {
4756 let mut serialize_workspace = true;
4757 match event {
4758 pane::Event::AddItem { item } => {
4759 item.added_to_pane(self, pane.clone(), window, cx);
4760 cx.emit(Event::ItemAdded {
4761 item: item.boxed_clone(),
4762 });
4763 }
4764 pane::Event::Split { direction, mode } => {
4765 match mode {
4766 SplitMode::ClonePane => {
4767 self.split_and_clone(pane.clone(), *direction, window, cx)
4768 .detach();
4769 }
4770 SplitMode::EmptyPane => {
4771 self.split_pane(pane.clone(), *direction, window, cx);
4772 }
4773 SplitMode::MovePane => {
4774 self.split_and_move(pane.clone(), *direction, window, cx);
4775 }
4776 };
4777 }
4778 pane::Event::JoinIntoNext => {
4779 self.join_pane_into_next(pane.clone(), window, cx);
4780 }
4781 pane::Event::JoinAll => {
4782 self.join_all_panes(window, cx);
4783 }
4784 pane::Event::Remove { focus_on_pane } => {
4785 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
4786 }
4787 pane::Event::ActivateItem {
4788 local,
4789 focus_changed,
4790 } => {
4791 window.invalidate_character_coordinates();
4792
4793 pane.update(cx, |pane, _| {
4794 pane.track_alternate_file_items();
4795 });
4796 if *local {
4797 self.unfollow_in_pane(pane, window, cx);
4798 }
4799 serialize_workspace = *focus_changed || pane != self.active_pane();
4800 if pane == self.active_pane() {
4801 self.active_item_path_changed(*focus_changed, window, cx);
4802 self.update_active_view_for_followers(window, cx);
4803 } else if *local {
4804 self.set_active_pane(pane, window, cx);
4805 }
4806 }
4807 pane::Event::UserSavedItem { item, save_intent } => {
4808 cx.emit(Event::UserSavedItem {
4809 pane: pane.downgrade(),
4810 item: item.boxed_clone(),
4811 save_intent: *save_intent,
4812 });
4813 serialize_workspace = false;
4814 }
4815 pane::Event::ChangeItemTitle => {
4816 if *pane == self.active_pane {
4817 self.active_item_path_changed(false, window, cx);
4818 }
4819 serialize_workspace = false;
4820 }
4821 pane::Event::RemovedItem { item } => {
4822 cx.emit(Event::ActiveItemChanged);
4823 self.update_window_edited(window, cx);
4824 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
4825 && entry.get().entity_id() == pane.entity_id()
4826 {
4827 entry.remove();
4828 }
4829 cx.emit(Event::ItemRemoved {
4830 item_id: item.item_id(),
4831 });
4832 }
4833 pane::Event::Focus => {
4834 window.invalidate_character_coordinates();
4835 self.handle_pane_focused(pane.clone(), window, cx);
4836 }
4837 pane::Event::ZoomIn => {
4838 if *pane == self.active_pane {
4839 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
4840 if pane.read(cx).has_focus(window, cx) {
4841 self.zoomed = Some(pane.downgrade().into());
4842 self.zoomed_position = None;
4843 cx.emit(Event::ZoomChanged);
4844 }
4845 cx.notify();
4846 }
4847 }
4848 pane::Event::ZoomOut => {
4849 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4850 if self.zoomed_position.is_none() {
4851 self.zoomed = None;
4852 cx.emit(Event::ZoomChanged);
4853 }
4854 cx.notify();
4855 }
4856 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
4857 }
4858
4859 if serialize_workspace {
4860 self.serialize_workspace(window, cx);
4861 }
4862 }
4863
4864 pub fn unfollow_in_pane(
4865 &mut self,
4866 pane: &Entity<Pane>,
4867 window: &mut Window,
4868 cx: &mut Context<Workspace>,
4869 ) -> Option<CollaboratorId> {
4870 let leader_id = self.leader_for_pane(pane)?;
4871 self.unfollow(leader_id, window, cx);
4872 Some(leader_id)
4873 }
4874
4875 pub fn split_pane(
4876 &mut self,
4877 pane_to_split: Entity<Pane>,
4878 split_direction: SplitDirection,
4879 window: &mut Window,
4880 cx: &mut Context<Self>,
4881 ) -> Entity<Pane> {
4882 let new_pane = self.add_pane(window, cx);
4883 self.center
4884 .split(&pane_to_split, &new_pane, split_direction, cx);
4885 cx.notify();
4886 new_pane
4887 }
4888
4889 pub fn split_and_move(
4890 &mut self,
4891 pane: Entity<Pane>,
4892 direction: SplitDirection,
4893 window: &mut Window,
4894 cx: &mut Context<Self>,
4895 ) {
4896 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
4897 return;
4898 };
4899 let new_pane = self.add_pane(window, cx);
4900 new_pane.update(cx, |pane, cx| {
4901 pane.add_item(item, true, true, None, window, cx)
4902 });
4903 self.center.split(&pane, &new_pane, direction, cx);
4904 cx.notify();
4905 }
4906
4907 pub fn split_and_clone(
4908 &mut self,
4909 pane: Entity<Pane>,
4910 direction: SplitDirection,
4911 window: &mut Window,
4912 cx: &mut Context<Self>,
4913 ) -> Task<Option<Entity<Pane>>> {
4914 let Some(item) = pane.read(cx).active_item() else {
4915 return Task::ready(None);
4916 };
4917 if !item.can_split(cx) {
4918 return Task::ready(None);
4919 }
4920 let task = item.clone_on_split(self.database_id(), window, cx);
4921 cx.spawn_in(window, async move |this, cx| {
4922 if let Some(clone) = task.await {
4923 this.update_in(cx, |this, window, cx| {
4924 let new_pane = this.add_pane(window, cx);
4925 let nav_history = pane.read(cx).fork_nav_history();
4926 new_pane.update(cx, |pane, cx| {
4927 pane.set_nav_history(nav_history, cx);
4928 pane.add_item(clone, true, true, None, window, cx)
4929 });
4930 this.center.split(&pane, &new_pane, direction, cx);
4931 cx.notify();
4932 new_pane
4933 })
4934 .ok()
4935 } else {
4936 None
4937 }
4938 })
4939 }
4940
4941 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4942 let active_item = self.active_pane.read(cx).active_item();
4943 for pane in &self.panes {
4944 join_pane_into_active(&self.active_pane, pane, window, cx);
4945 }
4946 if let Some(active_item) = active_item {
4947 self.activate_item(active_item.as_ref(), true, true, window, cx);
4948 }
4949 cx.notify();
4950 }
4951
4952 pub fn join_pane_into_next(
4953 &mut self,
4954 pane: Entity<Pane>,
4955 window: &mut Window,
4956 cx: &mut Context<Self>,
4957 ) {
4958 let next_pane = self
4959 .find_pane_in_direction(SplitDirection::Right, cx)
4960 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
4961 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
4962 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
4963 let Some(next_pane) = next_pane else {
4964 return;
4965 };
4966 move_all_items(&pane, &next_pane, window, cx);
4967 cx.notify();
4968 }
4969
4970 fn remove_pane(
4971 &mut self,
4972 pane: Entity<Pane>,
4973 focus_on: Option<Entity<Pane>>,
4974 window: &mut Window,
4975 cx: &mut Context<Self>,
4976 ) {
4977 if self.center.remove(&pane, cx).unwrap() {
4978 self.force_remove_pane(&pane, &focus_on, window, cx);
4979 self.unfollow_in_pane(&pane, window, cx);
4980 self.last_leaders_by_pane.remove(&pane.downgrade());
4981 for removed_item in pane.read(cx).items() {
4982 self.panes_by_item.remove(&removed_item.item_id());
4983 }
4984
4985 cx.notify();
4986 } else {
4987 self.active_item_path_changed(true, window, cx);
4988 }
4989 cx.emit(Event::PaneRemoved);
4990 }
4991
4992 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
4993 &mut self.panes
4994 }
4995
4996 pub fn panes(&self) -> &[Entity<Pane>] {
4997 &self.panes
4998 }
4999
5000 pub fn active_pane(&self) -> &Entity<Pane> {
5001 &self.active_pane
5002 }
5003
5004 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5005 for dock in self.all_docks() {
5006 if dock.focus_handle(cx).contains_focused(window, cx)
5007 && let Some(pane) = dock
5008 .read(cx)
5009 .active_panel()
5010 .and_then(|panel| panel.pane(cx))
5011 {
5012 return pane;
5013 }
5014 }
5015 self.active_pane().clone()
5016 }
5017
5018 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5019 self.find_pane_in_direction(SplitDirection::Right, cx)
5020 .unwrap_or_else(|| {
5021 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5022 })
5023 }
5024
5025 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5026 self.pane_for_item_id(handle.item_id())
5027 }
5028
5029 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5030 let weak_pane = self.panes_by_item.get(&item_id)?;
5031 weak_pane.upgrade()
5032 }
5033
5034 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5035 self.panes
5036 .iter()
5037 .find(|pane| pane.entity_id() == entity_id)
5038 .cloned()
5039 }
5040
5041 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5042 self.follower_states.retain(|leader_id, state| {
5043 if *leader_id == CollaboratorId::PeerId(peer_id) {
5044 for item in state.items_by_leader_view_id.values() {
5045 item.view.set_leader_id(None, window, cx);
5046 }
5047 false
5048 } else {
5049 true
5050 }
5051 });
5052 cx.notify();
5053 }
5054
5055 pub fn start_following(
5056 &mut self,
5057 leader_id: impl Into<CollaboratorId>,
5058 window: &mut Window,
5059 cx: &mut Context<Self>,
5060 ) -> Option<Task<Result<()>>> {
5061 let leader_id = leader_id.into();
5062 let pane = self.active_pane().clone();
5063
5064 self.last_leaders_by_pane
5065 .insert(pane.downgrade(), leader_id);
5066 self.unfollow(leader_id, window, cx);
5067 self.unfollow_in_pane(&pane, window, cx);
5068 self.follower_states.insert(
5069 leader_id,
5070 FollowerState {
5071 center_pane: pane.clone(),
5072 dock_pane: None,
5073 active_view_id: None,
5074 items_by_leader_view_id: Default::default(),
5075 },
5076 );
5077 cx.notify();
5078
5079 match leader_id {
5080 CollaboratorId::PeerId(leader_peer_id) => {
5081 let room_id = self.active_call()?.room_id(cx)?;
5082 let project_id = self.project.read(cx).remote_id();
5083 let request = self.app_state.client.request(proto::Follow {
5084 room_id,
5085 project_id,
5086 leader_id: Some(leader_peer_id),
5087 });
5088
5089 Some(cx.spawn_in(window, async move |this, cx| {
5090 let response = request.await?;
5091 this.update(cx, |this, _| {
5092 let state = this
5093 .follower_states
5094 .get_mut(&leader_id)
5095 .context("following interrupted")?;
5096 state.active_view_id = response
5097 .active_view
5098 .as_ref()
5099 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5100 anyhow::Ok(())
5101 })??;
5102 if let Some(view) = response.active_view {
5103 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5104 }
5105 this.update_in(cx, |this, window, cx| {
5106 this.leader_updated(leader_id, window, cx)
5107 })?;
5108 Ok(())
5109 }))
5110 }
5111 CollaboratorId::Agent => {
5112 self.leader_updated(leader_id, window, cx)?;
5113 Some(Task::ready(Ok(())))
5114 }
5115 }
5116 }
5117
5118 pub fn follow_next_collaborator(
5119 &mut self,
5120 _: &FollowNextCollaborator,
5121 window: &mut Window,
5122 cx: &mut Context<Self>,
5123 ) {
5124 let collaborators = self.project.read(cx).collaborators();
5125 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5126 let mut collaborators = collaborators.keys().copied();
5127 for peer_id in collaborators.by_ref() {
5128 if CollaboratorId::PeerId(peer_id) == leader_id {
5129 break;
5130 }
5131 }
5132 collaborators.next().map(CollaboratorId::PeerId)
5133 } else if let Some(last_leader_id) =
5134 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5135 {
5136 match last_leader_id {
5137 CollaboratorId::PeerId(peer_id) => {
5138 if collaborators.contains_key(peer_id) {
5139 Some(*last_leader_id)
5140 } else {
5141 None
5142 }
5143 }
5144 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5145 }
5146 } else {
5147 None
5148 };
5149
5150 let pane = self.active_pane.clone();
5151 let Some(leader_id) = next_leader_id.or_else(|| {
5152 Some(CollaboratorId::PeerId(
5153 collaborators.keys().copied().next()?,
5154 ))
5155 }) else {
5156 return;
5157 };
5158 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5159 return;
5160 }
5161 if let Some(task) = self.start_following(leader_id, window, cx) {
5162 task.detach_and_log_err(cx)
5163 }
5164 }
5165
5166 pub fn follow(
5167 &mut self,
5168 leader_id: impl Into<CollaboratorId>,
5169 window: &mut Window,
5170 cx: &mut Context<Self>,
5171 ) {
5172 let leader_id = leader_id.into();
5173
5174 if let CollaboratorId::PeerId(peer_id) = leader_id {
5175 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5176 return;
5177 };
5178 let Some(remote_participant) =
5179 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5180 else {
5181 return;
5182 };
5183
5184 let project = self.project.read(cx);
5185
5186 let other_project_id = match remote_participant.location {
5187 ParticipantLocation::External => None,
5188 ParticipantLocation::UnsharedProject => None,
5189 ParticipantLocation::SharedProject { project_id } => {
5190 if Some(project_id) == project.remote_id() {
5191 None
5192 } else {
5193 Some(project_id)
5194 }
5195 }
5196 };
5197
5198 // if they are active in another project, follow there.
5199 if let Some(project_id) = other_project_id {
5200 let app_state = self.app_state.clone();
5201 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5202 .detach_and_log_err(cx);
5203 }
5204 }
5205
5206 // if you're already following, find the right pane and focus it.
5207 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5208 window.focus(&follower_state.pane().focus_handle(cx), cx);
5209
5210 return;
5211 }
5212
5213 // Otherwise, follow.
5214 if let Some(task) = self.start_following(leader_id, window, cx) {
5215 task.detach_and_log_err(cx)
5216 }
5217 }
5218
5219 pub fn unfollow(
5220 &mut self,
5221 leader_id: impl Into<CollaboratorId>,
5222 window: &mut Window,
5223 cx: &mut Context<Self>,
5224 ) -> Option<()> {
5225 cx.notify();
5226
5227 let leader_id = leader_id.into();
5228 let state = self.follower_states.remove(&leader_id)?;
5229 for (_, item) in state.items_by_leader_view_id {
5230 item.view.set_leader_id(None, window, cx);
5231 }
5232
5233 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5234 let project_id = self.project.read(cx).remote_id();
5235 let room_id = self.active_call()?.room_id(cx)?;
5236 self.app_state
5237 .client
5238 .send(proto::Unfollow {
5239 room_id,
5240 project_id,
5241 leader_id: Some(leader_peer_id),
5242 })
5243 .log_err();
5244 }
5245
5246 Some(())
5247 }
5248
5249 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5250 self.follower_states.contains_key(&id.into())
5251 }
5252
5253 fn active_item_path_changed(
5254 &mut self,
5255 focus_changed: bool,
5256 window: &mut Window,
5257 cx: &mut Context<Self>,
5258 ) {
5259 cx.emit(Event::ActiveItemChanged);
5260 let active_entry = self.active_project_path(cx);
5261 self.project.update(cx, |project, cx| {
5262 project.set_active_path(active_entry.clone(), cx)
5263 });
5264
5265 if focus_changed && let Some(project_path) = &active_entry {
5266 let git_store_entity = self.project.read(cx).git_store().clone();
5267 git_store_entity.update(cx, |git_store, cx| {
5268 git_store.set_active_repo_for_path(project_path, cx);
5269 });
5270 }
5271
5272 self.update_window_title(window, cx);
5273 }
5274
5275 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5276 let project = self.project().read(cx);
5277 let mut title = String::new();
5278
5279 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5280 let name = {
5281 let settings_location = SettingsLocation {
5282 worktree_id: worktree.read(cx).id(),
5283 path: RelPath::empty(),
5284 };
5285
5286 let settings = WorktreeSettings::get(Some(settings_location), cx);
5287 match &settings.project_name {
5288 Some(name) => name.as_str(),
5289 None => worktree.read(cx).root_name_str(),
5290 }
5291 };
5292 if i > 0 {
5293 title.push_str(", ");
5294 }
5295 title.push_str(name);
5296 }
5297
5298 if title.is_empty() {
5299 title = "empty project".to_string();
5300 }
5301
5302 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5303 let filename = path.path.file_name().or_else(|| {
5304 Some(
5305 project
5306 .worktree_for_id(path.worktree_id, cx)?
5307 .read(cx)
5308 .root_name_str(),
5309 )
5310 });
5311
5312 if let Some(filename) = filename {
5313 title.push_str(" — ");
5314 title.push_str(filename.as_ref());
5315 }
5316 }
5317
5318 if project.is_via_collab() {
5319 title.push_str(" ↙");
5320 } else if project.is_shared() {
5321 title.push_str(" ↗");
5322 }
5323
5324 if let Some(last_title) = self.last_window_title.as_ref()
5325 && &title == last_title
5326 {
5327 return;
5328 }
5329 window.set_window_title(&title);
5330 SystemWindowTabController::update_tab_title(
5331 cx,
5332 window.window_handle().window_id(),
5333 SharedString::from(&title),
5334 );
5335 self.last_window_title = Some(title);
5336 }
5337
5338 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5339 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5340 if is_edited != self.window_edited {
5341 self.window_edited = is_edited;
5342 window.set_window_edited(self.window_edited)
5343 }
5344 }
5345
5346 fn update_item_dirty_state(
5347 &mut self,
5348 item: &dyn ItemHandle,
5349 window: &mut Window,
5350 cx: &mut App,
5351 ) {
5352 let is_dirty = item.is_dirty(cx);
5353 let item_id = item.item_id();
5354 let was_dirty = self.dirty_items.contains_key(&item_id);
5355 if is_dirty == was_dirty {
5356 return;
5357 }
5358 if was_dirty {
5359 self.dirty_items.remove(&item_id);
5360 self.update_window_edited(window, cx);
5361 return;
5362 }
5363
5364 let workspace = self.weak_handle();
5365 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5366 return;
5367 };
5368 let on_release_callback = Box::new(move |cx: &mut App| {
5369 window_handle
5370 .update(cx, |_, window, cx| {
5371 workspace
5372 .update(cx, |workspace, cx| {
5373 workspace.dirty_items.remove(&item_id);
5374 workspace.update_window_edited(window, cx)
5375 })
5376 .ok();
5377 })
5378 .ok();
5379 });
5380
5381 let s = item.on_release(cx, on_release_callback);
5382 self.dirty_items.insert(item_id, s);
5383 self.update_window_edited(window, cx);
5384 }
5385
5386 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5387 if self.notifications.is_empty() {
5388 None
5389 } else {
5390 Some(
5391 div()
5392 .absolute()
5393 .right_3()
5394 .bottom_3()
5395 .w_112()
5396 .h_full()
5397 .flex()
5398 .flex_col()
5399 .justify_end()
5400 .gap_2()
5401 .children(
5402 self.notifications
5403 .iter()
5404 .map(|(_, notification)| notification.clone().into_any()),
5405 ),
5406 )
5407 }
5408 }
5409
5410 // RPC handlers
5411
5412 fn active_view_for_follower(
5413 &self,
5414 follower_project_id: Option<u64>,
5415 window: &mut Window,
5416 cx: &mut Context<Self>,
5417 ) -> Option<proto::View> {
5418 let (item, panel_id) = self.active_item_for_followers(window, cx);
5419 let item = item?;
5420 let leader_id = self
5421 .pane_for(&*item)
5422 .and_then(|pane| self.leader_for_pane(&pane));
5423 let leader_peer_id = match leader_id {
5424 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5425 Some(CollaboratorId::Agent) | None => None,
5426 };
5427
5428 let item_handle = item.to_followable_item_handle(cx)?;
5429 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5430 let variant = item_handle.to_state_proto(window, cx)?;
5431
5432 if item_handle.is_project_item(window, cx)
5433 && (follower_project_id.is_none()
5434 || follower_project_id != self.project.read(cx).remote_id())
5435 {
5436 return None;
5437 }
5438
5439 Some(proto::View {
5440 id: id.to_proto(),
5441 leader_id: leader_peer_id,
5442 variant: Some(variant),
5443 panel_id: panel_id.map(|id| id as i32),
5444 })
5445 }
5446
5447 fn handle_follow(
5448 &mut self,
5449 follower_project_id: Option<u64>,
5450 window: &mut Window,
5451 cx: &mut Context<Self>,
5452 ) -> proto::FollowResponse {
5453 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5454
5455 cx.notify();
5456 proto::FollowResponse {
5457 views: active_view.iter().cloned().collect(),
5458 active_view,
5459 }
5460 }
5461
5462 fn handle_update_followers(
5463 &mut self,
5464 leader_id: PeerId,
5465 message: proto::UpdateFollowers,
5466 _window: &mut Window,
5467 _cx: &mut Context<Self>,
5468 ) {
5469 self.leader_updates_tx
5470 .unbounded_send((leader_id, message))
5471 .ok();
5472 }
5473
5474 async fn process_leader_update(
5475 this: &WeakEntity<Self>,
5476 leader_id: PeerId,
5477 update: proto::UpdateFollowers,
5478 cx: &mut AsyncWindowContext,
5479 ) -> Result<()> {
5480 match update.variant.context("invalid update")? {
5481 proto::update_followers::Variant::CreateView(view) => {
5482 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5483 let should_add_view = this.update(cx, |this, _| {
5484 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5485 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5486 } else {
5487 anyhow::Ok(false)
5488 }
5489 })??;
5490
5491 if should_add_view {
5492 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5493 }
5494 }
5495 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5496 let should_add_view = this.update(cx, |this, _| {
5497 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5498 state.active_view_id = update_active_view
5499 .view
5500 .as_ref()
5501 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5502
5503 if state.active_view_id.is_some_and(|view_id| {
5504 !state.items_by_leader_view_id.contains_key(&view_id)
5505 }) {
5506 anyhow::Ok(true)
5507 } else {
5508 anyhow::Ok(false)
5509 }
5510 } else {
5511 anyhow::Ok(false)
5512 }
5513 })??;
5514
5515 if should_add_view && let Some(view) = update_active_view.view {
5516 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5517 }
5518 }
5519 proto::update_followers::Variant::UpdateView(update_view) => {
5520 let variant = update_view.variant.context("missing update view variant")?;
5521 let id = update_view.id.context("missing update view id")?;
5522 let mut tasks = Vec::new();
5523 this.update_in(cx, |this, window, cx| {
5524 let project = this.project.clone();
5525 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5526 let view_id = ViewId::from_proto(id.clone())?;
5527 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5528 tasks.push(item.view.apply_update_proto(
5529 &project,
5530 variant.clone(),
5531 window,
5532 cx,
5533 ));
5534 }
5535 }
5536 anyhow::Ok(())
5537 })??;
5538 try_join_all(tasks).await.log_err();
5539 }
5540 }
5541 this.update_in(cx, |this, window, cx| {
5542 this.leader_updated(leader_id, window, cx)
5543 })?;
5544 Ok(())
5545 }
5546
5547 async fn add_view_from_leader(
5548 this: WeakEntity<Self>,
5549 leader_id: PeerId,
5550 view: &proto::View,
5551 cx: &mut AsyncWindowContext,
5552 ) -> Result<()> {
5553 let this = this.upgrade().context("workspace dropped")?;
5554
5555 let Some(id) = view.id.clone() else {
5556 anyhow::bail!("no id for view");
5557 };
5558 let id = ViewId::from_proto(id)?;
5559 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5560
5561 let pane = this.update(cx, |this, _cx| {
5562 let state = this
5563 .follower_states
5564 .get(&leader_id.into())
5565 .context("stopped following")?;
5566 anyhow::Ok(state.pane().clone())
5567 })?;
5568 let existing_item = pane.update_in(cx, |pane, window, cx| {
5569 let client = this.read(cx).client().clone();
5570 pane.items().find_map(|item| {
5571 let item = item.to_followable_item_handle(cx)?;
5572 if item.remote_id(&client, window, cx) == Some(id) {
5573 Some(item)
5574 } else {
5575 None
5576 }
5577 })
5578 })?;
5579 let item = if let Some(existing_item) = existing_item {
5580 existing_item
5581 } else {
5582 let variant = view.variant.clone();
5583 anyhow::ensure!(variant.is_some(), "missing view variant");
5584
5585 let task = cx.update(|window, cx| {
5586 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5587 })?;
5588
5589 let Some(task) = task else {
5590 anyhow::bail!(
5591 "failed to construct view from leader (maybe from a different version of zed?)"
5592 );
5593 };
5594
5595 let mut new_item = task.await?;
5596 pane.update_in(cx, |pane, window, cx| {
5597 let mut item_to_remove = None;
5598 for (ix, item) in pane.items().enumerate() {
5599 if let Some(item) = item.to_followable_item_handle(cx) {
5600 match new_item.dedup(item.as_ref(), window, cx) {
5601 Some(item::Dedup::KeepExisting) => {
5602 new_item =
5603 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5604 break;
5605 }
5606 Some(item::Dedup::ReplaceExisting) => {
5607 item_to_remove = Some((ix, item.item_id()));
5608 break;
5609 }
5610 None => {}
5611 }
5612 }
5613 }
5614
5615 if let Some((ix, id)) = item_to_remove {
5616 pane.remove_item(id, false, false, window, cx);
5617 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5618 }
5619 })?;
5620
5621 new_item
5622 };
5623
5624 this.update_in(cx, |this, window, cx| {
5625 let state = this.follower_states.get_mut(&leader_id.into())?;
5626 item.set_leader_id(Some(leader_id.into()), window, cx);
5627 state.items_by_leader_view_id.insert(
5628 id,
5629 FollowerView {
5630 view: item,
5631 location: panel_id,
5632 },
5633 );
5634
5635 Some(())
5636 })
5637 .context("no follower state")?;
5638
5639 Ok(())
5640 }
5641
5642 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5643 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5644 return;
5645 };
5646
5647 if let Some(agent_location) = self.project.read(cx).agent_location() {
5648 let buffer_entity_id = agent_location.buffer.entity_id();
5649 let view_id = ViewId {
5650 creator: CollaboratorId::Agent,
5651 id: buffer_entity_id.as_u64(),
5652 };
5653 follower_state.active_view_id = Some(view_id);
5654
5655 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5656 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5657 hash_map::Entry::Vacant(entry) => {
5658 let existing_view =
5659 follower_state
5660 .center_pane
5661 .read(cx)
5662 .items()
5663 .find_map(|item| {
5664 let item = item.to_followable_item_handle(cx)?;
5665 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5666 && item.project_item_model_ids(cx).as_slice()
5667 == [buffer_entity_id]
5668 {
5669 Some(item)
5670 } else {
5671 None
5672 }
5673 });
5674 let view = existing_view.or_else(|| {
5675 agent_location.buffer.upgrade().and_then(|buffer| {
5676 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
5677 registry.build_item(buffer, self.project.clone(), None, window, cx)
5678 })?
5679 .to_followable_item_handle(cx)
5680 })
5681 });
5682
5683 view.map(|view| {
5684 entry.insert(FollowerView {
5685 view,
5686 location: None,
5687 })
5688 })
5689 }
5690 };
5691
5692 if let Some(item) = item {
5693 item.view
5694 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
5695 item.view
5696 .update_agent_location(agent_location.position, window, cx);
5697 }
5698 } else {
5699 follower_state.active_view_id = None;
5700 }
5701
5702 self.leader_updated(CollaboratorId::Agent, window, cx);
5703 }
5704
5705 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
5706 let mut is_project_item = true;
5707 let mut update = proto::UpdateActiveView::default();
5708 if window.is_window_active() {
5709 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
5710
5711 if let Some(item) = active_item
5712 && item.item_focus_handle(cx).contains_focused(window, cx)
5713 {
5714 let leader_id = self
5715 .pane_for(&*item)
5716 .and_then(|pane| self.leader_for_pane(&pane));
5717 let leader_peer_id = match leader_id {
5718 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5719 Some(CollaboratorId::Agent) | None => None,
5720 };
5721
5722 if let Some(item) = item.to_followable_item_handle(cx) {
5723 let id = item
5724 .remote_id(&self.app_state.client, window, cx)
5725 .map(|id| id.to_proto());
5726
5727 if let Some(id) = id
5728 && let Some(variant) = item.to_state_proto(window, cx)
5729 {
5730 let view = Some(proto::View {
5731 id,
5732 leader_id: leader_peer_id,
5733 variant: Some(variant),
5734 panel_id: panel_id.map(|id| id as i32),
5735 });
5736
5737 is_project_item = item.is_project_item(window, cx);
5738 update = proto::UpdateActiveView { view };
5739 };
5740 }
5741 }
5742 }
5743
5744 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
5745 if active_view_id != self.last_active_view_id.as_ref() {
5746 self.last_active_view_id = active_view_id.cloned();
5747 self.update_followers(
5748 is_project_item,
5749 proto::update_followers::Variant::UpdateActiveView(update),
5750 window,
5751 cx,
5752 );
5753 }
5754 }
5755
5756 fn active_item_for_followers(
5757 &self,
5758 window: &mut Window,
5759 cx: &mut App,
5760 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
5761 let mut active_item = None;
5762 let mut panel_id = None;
5763 for dock in self.all_docks() {
5764 if dock.focus_handle(cx).contains_focused(window, cx)
5765 && let Some(panel) = dock.read(cx).active_panel()
5766 && let Some(pane) = panel.pane(cx)
5767 && let Some(item) = pane.read(cx).active_item()
5768 {
5769 active_item = Some(item);
5770 panel_id = panel.remote_id();
5771 break;
5772 }
5773 }
5774
5775 if active_item.is_none() {
5776 active_item = self.active_pane().read(cx).active_item();
5777 }
5778 (active_item, panel_id)
5779 }
5780
5781 fn update_followers(
5782 &self,
5783 project_only: bool,
5784 update: proto::update_followers::Variant,
5785 _: &mut Window,
5786 cx: &mut App,
5787 ) -> Option<()> {
5788 // If this update only applies to for followers in the current project,
5789 // then skip it unless this project is shared. If it applies to all
5790 // followers, regardless of project, then set `project_id` to none,
5791 // indicating that it goes to all followers.
5792 let project_id = if project_only {
5793 Some(self.project.read(cx).remote_id()?)
5794 } else {
5795 None
5796 };
5797 self.app_state().workspace_store.update(cx, |store, cx| {
5798 store.update_followers(project_id, update, cx)
5799 })
5800 }
5801
5802 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
5803 self.follower_states.iter().find_map(|(leader_id, state)| {
5804 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
5805 Some(*leader_id)
5806 } else {
5807 None
5808 }
5809 })
5810 }
5811
5812 fn leader_updated(
5813 &mut self,
5814 leader_id: impl Into<CollaboratorId>,
5815 window: &mut Window,
5816 cx: &mut Context<Self>,
5817 ) -> Option<Box<dyn ItemHandle>> {
5818 cx.notify();
5819
5820 let leader_id = leader_id.into();
5821 let (panel_id, item) = match leader_id {
5822 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
5823 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
5824 };
5825
5826 let state = self.follower_states.get(&leader_id)?;
5827 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
5828 let pane;
5829 if let Some(panel_id) = panel_id {
5830 pane = self
5831 .activate_panel_for_proto_id(panel_id, window, cx)?
5832 .pane(cx)?;
5833 let state = self.follower_states.get_mut(&leader_id)?;
5834 state.dock_pane = Some(pane.clone());
5835 } else {
5836 pane = state.center_pane.clone();
5837 let state = self.follower_states.get_mut(&leader_id)?;
5838 if let Some(dock_pane) = state.dock_pane.take() {
5839 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
5840 }
5841 }
5842
5843 pane.update(cx, |pane, cx| {
5844 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
5845 if let Some(index) = pane.index_for_item(item.as_ref()) {
5846 pane.activate_item(index, false, false, window, cx);
5847 } else {
5848 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
5849 }
5850
5851 if focus_active_item {
5852 pane.focus_active_item(window, cx)
5853 }
5854 });
5855
5856 Some(item)
5857 }
5858
5859 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
5860 let state = self.follower_states.get(&CollaboratorId::Agent)?;
5861 let active_view_id = state.active_view_id?;
5862 Some(
5863 state
5864 .items_by_leader_view_id
5865 .get(&active_view_id)?
5866 .view
5867 .boxed_clone(),
5868 )
5869 }
5870
5871 fn active_item_for_peer(
5872 &self,
5873 peer_id: PeerId,
5874 window: &mut Window,
5875 cx: &mut Context<Self>,
5876 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
5877 let call = self.active_call()?;
5878 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
5879 let leader_in_this_app;
5880 let leader_in_this_project;
5881 match participant.location {
5882 ParticipantLocation::SharedProject { project_id } => {
5883 leader_in_this_app = true;
5884 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
5885 }
5886 ParticipantLocation::UnsharedProject => {
5887 leader_in_this_app = true;
5888 leader_in_this_project = false;
5889 }
5890 ParticipantLocation::External => {
5891 leader_in_this_app = false;
5892 leader_in_this_project = false;
5893 }
5894 };
5895 let state = self.follower_states.get(&peer_id.into())?;
5896 let mut item_to_activate = None;
5897 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
5898 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
5899 && (leader_in_this_project || !item.view.is_project_item(window, cx))
5900 {
5901 item_to_activate = Some((item.location, item.view.boxed_clone()));
5902 }
5903 } else if let Some(shared_screen) =
5904 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
5905 {
5906 item_to_activate = Some((None, Box::new(shared_screen)));
5907 }
5908 item_to_activate
5909 }
5910
5911 fn shared_screen_for_peer(
5912 &self,
5913 peer_id: PeerId,
5914 pane: &Entity<Pane>,
5915 window: &mut Window,
5916 cx: &mut App,
5917 ) -> Option<Entity<SharedScreen>> {
5918 self.active_call()?
5919 .create_shared_screen(peer_id, pane, window, cx)
5920 }
5921
5922 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5923 if window.is_window_active() {
5924 self.update_active_view_for_followers(window, cx);
5925
5926 if let Some(database_id) = self.database_id {
5927 cx.background_spawn(persistence::DB.update_timestamp(database_id))
5928 .detach();
5929 }
5930 } else {
5931 for pane in &self.panes {
5932 pane.update(cx, |pane, cx| {
5933 if let Some(item) = pane.active_item() {
5934 item.workspace_deactivated(window, cx);
5935 }
5936 for item in pane.items() {
5937 if matches!(
5938 item.workspace_settings(cx).autosave,
5939 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
5940 ) {
5941 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
5942 .detach_and_log_err(cx);
5943 }
5944 }
5945 });
5946 }
5947 }
5948 }
5949
5950 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
5951 self.active_call.as_ref().map(|(call, _)| &*call.0)
5952 }
5953
5954 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
5955 self.active_call.as_ref().map(|(call, _)| call.clone())
5956 }
5957
5958 fn on_active_call_event(
5959 &mut self,
5960 event: &ActiveCallEvent,
5961 window: &mut Window,
5962 cx: &mut Context<Self>,
5963 ) {
5964 match event {
5965 ActiveCallEvent::ParticipantLocationChanged { participant_id }
5966 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
5967 self.leader_updated(participant_id, window, cx);
5968 }
5969 }
5970 }
5971
5972 pub fn database_id(&self) -> Option<WorkspaceId> {
5973 self.database_id
5974 }
5975
5976 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
5977 self.database_id = Some(id);
5978 }
5979
5980 pub fn session_id(&self) -> Option<String> {
5981 self.session_id.clone()
5982 }
5983
5984 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
5985 let Some(display) = window.display(cx) else {
5986 return Task::ready(());
5987 };
5988 let Ok(display_uuid) = display.uuid() else {
5989 return Task::ready(());
5990 };
5991
5992 let window_bounds = window.inner_window_bounds();
5993 let database_id = self.database_id;
5994 let has_paths = !self.root_paths(cx).is_empty();
5995
5996 cx.background_executor().spawn(async move {
5997 if !has_paths {
5998 persistence::write_default_window_bounds(window_bounds, display_uuid)
5999 .await
6000 .log_err();
6001 }
6002 if let Some(database_id) = database_id {
6003 DB.set_window_open_status(
6004 database_id,
6005 SerializedWindowBounds(window_bounds),
6006 display_uuid,
6007 )
6008 .await
6009 .log_err();
6010 } else {
6011 persistence::write_default_window_bounds(window_bounds, display_uuid)
6012 .await
6013 .log_err();
6014 }
6015 })
6016 }
6017
6018 /// Bypass the 200ms serialization throttle and write workspace state to
6019 /// the DB immediately. Returns a task the caller can await to ensure the
6020 /// write completes. Used by the quit handler so the most recent state
6021 /// isn't lost to a pending throttle timer when the process exits.
6022 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6023 self._schedule_serialize_workspace.take();
6024 self._serialize_workspace_task.take();
6025 self.bounds_save_task_queued.take();
6026
6027 let bounds_task = self.save_window_bounds(window, cx);
6028 let serialize_task = self.serialize_workspace_internal(window, cx);
6029 cx.spawn(async move |_| {
6030 bounds_task.await;
6031 serialize_task.await;
6032 })
6033 }
6034
6035 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6036 let project = self.project().read(cx);
6037 project
6038 .visible_worktrees(cx)
6039 .map(|worktree| worktree.read(cx).abs_path())
6040 .collect::<Vec<_>>()
6041 }
6042
6043 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6044 match member {
6045 Member::Axis(PaneAxis { members, .. }) => {
6046 for child in members.iter() {
6047 self.remove_panes(child.clone(), window, cx)
6048 }
6049 }
6050 Member::Pane(pane) => {
6051 self.force_remove_pane(&pane, &None, window, cx);
6052 }
6053 }
6054 }
6055
6056 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6057 self.session_id.take();
6058 self.serialize_workspace_internal(window, cx)
6059 }
6060
6061 fn force_remove_pane(
6062 &mut self,
6063 pane: &Entity<Pane>,
6064 focus_on: &Option<Entity<Pane>>,
6065 window: &mut Window,
6066 cx: &mut Context<Workspace>,
6067 ) {
6068 self.panes.retain(|p| p != pane);
6069 if let Some(focus_on) = focus_on {
6070 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6071 } else if self.active_pane() == pane {
6072 self.panes
6073 .last()
6074 .unwrap()
6075 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6076 }
6077 if self.last_active_center_pane == Some(pane.downgrade()) {
6078 self.last_active_center_pane = None;
6079 }
6080 cx.notify();
6081 }
6082
6083 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6084 if self._schedule_serialize_workspace.is_none() {
6085 self._schedule_serialize_workspace =
6086 Some(cx.spawn_in(window, async move |this, cx| {
6087 cx.background_executor()
6088 .timer(SERIALIZATION_THROTTLE_TIME)
6089 .await;
6090 this.update_in(cx, |this, window, cx| {
6091 this._serialize_workspace_task =
6092 Some(this.serialize_workspace_internal(window, cx));
6093 this._schedule_serialize_workspace.take();
6094 })
6095 .log_err();
6096 }));
6097 }
6098 }
6099
6100 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6101 let Some(database_id) = self.database_id() else {
6102 return Task::ready(());
6103 };
6104
6105 fn serialize_pane_handle(
6106 pane_handle: &Entity<Pane>,
6107 window: &mut Window,
6108 cx: &mut App,
6109 ) -> SerializedPane {
6110 let (items, active, pinned_count) = {
6111 let pane = pane_handle.read(cx);
6112 let active_item_id = pane.active_item().map(|item| item.item_id());
6113 (
6114 pane.items()
6115 .filter_map(|handle| {
6116 let handle = handle.to_serializable_item_handle(cx)?;
6117
6118 Some(SerializedItem {
6119 kind: Arc::from(handle.serialized_item_kind()),
6120 item_id: handle.item_id().as_u64(),
6121 active: Some(handle.item_id()) == active_item_id,
6122 preview: pane.is_active_preview_item(handle.item_id()),
6123 })
6124 })
6125 .collect::<Vec<_>>(),
6126 pane.has_focus(window, cx),
6127 pane.pinned_count(),
6128 )
6129 };
6130
6131 SerializedPane::new(items, active, pinned_count)
6132 }
6133
6134 fn build_serialized_pane_group(
6135 pane_group: &Member,
6136 window: &mut Window,
6137 cx: &mut App,
6138 ) -> SerializedPaneGroup {
6139 match pane_group {
6140 Member::Axis(PaneAxis {
6141 axis,
6142 members,
6143 flexes,
6144 bounding_boxes: _,
6145 }) => SerializedPaneGroup::Group {
6146 axis: SerializedAxis(*axis),
6147 children: members
6148 .iter()
6149 .map(|member| build_serialized_pane_group(member, window, cx))
6150 .collect::<Vec<_>>(),
6151 flexes: Some(flexes.lock().clone()),
6152 },
6153 Member::Pane(pane_handle) => {
6154 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6155 }
6156 }
6157 }
6158
6159 fn build_serialized_docks(
6160 this: &Workspace,
6161 window: &mut Window,
6162 cx: &mut App,
6163 ) -> DockStructure {
6164 this.capture_dock_state(window, cx)
6165 }
6166
6167 match self.workspace_location(cx) {
6168 WorkspaceLocation::Location(location, paths) => {
6169 let breakpoints = self.project.update(cx, |project, cx| {
6170 project
6171 .breakpoint_store()
6172 .read(cx)
6173 .all_source_breakpoints(cx)
6174 });
6175 let user_toolchains = self
6176 .project
6177 .read(cx)
6178 .user_toolchains(cx)
6179 .unwrap_or_default();
6180
6181 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6182 let docks = build_serialized_docks(self, window, cx);
6183 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6184
6185 let serialized_workspace = SerializedWorkspace {
6186 id: database_id,
6187 location,
6188 paths,
6189 center_group,
6190 window_bounds,
6191 display: Default::default(),
6192 docks,
6193 centered_layout: self.centered_layout,
6194 session_id: self.session_id.clone(),
6195 breakpoints,
6196 window_id: Some(window.window_handle().window_id().as_u64()),
6197 user_toolchains,
6198 };
6199
6200 window.spawn(cx, async move |_| {
6201 persistence::DB.save_workspace(serialized_workspace).await;
6202 })
6203 }
6204 WorkspaceLocation::DetachFromSession => {
6205 let window_bounds = SerializedWindowBounds(window.window_bounds());
6206 let display = window.display(cx).and_then(|d| d.uuid().ok());
6207 // Save dock state for empty local workspaces
6208 let docks = build_serialized_docks(self, window, cx);
6209 window.spawn(cx, async move |_| {
6210 persistence::DB
6211 .set_window_open_status(
6212 database_id,
6213 window_bounds,
6214 display.unwrap_or_default(),
6215 )
6216 .await
6217 .log_err();
6218 persistence::DB
6219 .set_session_id(database_id, None)
6220 .await
6221 .log_err();
6222 persistence::write_default_dock_state(docks).await.log_err();
6223 })
6224 }
6225 WorkspaceLocation::None => {
6226 // Save dock state for empty non-local workspaces
6227 let docks = build_serialized_docks(self, window, cx);
6228 window.spawn(cx, async move |_| {
6229 persistence::write_default_dock_state(docks).await.log_err();
6230 })
6231 }
6232 }
6233 }
6234
6235 fn has_any_items_open(&self, cx: &App) -> bool {
6236 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6237 }
6238
6239 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6240 let paths = PathList::new(&self.root_paths(cx));
6241 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6242 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6243 } else if self.project.read(cx).is_local() {
6244 if !paths.is_empty() || self.has_any_items_open(cx) {
6245 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6246 } else {
6247 WorkspaceLocation::DetachFromSession
6248 }
6249 } else {
6250 WorkspaceLocation::None
6251 }
6252 }
6253
6254 fn update_history(&self, cx: &mut App) {
6255 let Some(id) = self.database_id() else {
6256 return;
6257 };
6258 if !self.project.read(cx).is_local() {
6259 return;
6260 }
6261 if let Some(manager) = HistoryManager::global(cx) {
6262 let paths = PathList::new(&self.root_paths(cx));
6263 manager.update(cx, |this, cx| {
6264 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6265 });
6266 }
6267 }
6268
6269 async fn serialize_items(
6270 this: &WeakEntity<Self>,
6271 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6272 cx: &mut AsyncWindowContext,
6273 ) -> Result<()> {
6274 const CHUNK_SIZE: usize = 200;
6275
6276 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6277
6278 while let Some(items_received) = serializable_items.next().await {
6279 let unique_items =
6280 items_received
6281 .into_iter()
6282 .fold(HashMap::default(), |mut acc, item| {
6283 acc.entry(item.item_id()).or_insert(item);
6284 acc
6285 });
6286
6287 // We use into_iter() here so that the references to the items are moved into
6288 // the tasks and not kept alive while we're sleeping.
6289 for (_, item) in unique_items.into_iter() {
6290 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6291 item.serialize(workspace, false, window, cx)
6292 }) {
6293 cx.background_spawn(async move { task.await.log_err() })
6294 .detach();
6295 }
6296 }
6297
6298 cx.background_executor()
6299 .timer(SERIALIZATION_THROTTLE_TIME)
6300 .await;
6301 }
6302
6303 Ok(())
6304 }
6305
6306 pub(crate) fn enqueue_item_serialization(
6307 &mut self,
6308 item: Box<dyn SerializableItemHandle>,
6309 ) -> Result<()> {
6310 self.serializable_items_tx
6311 .unbounded_send(item)
6312 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6313 }
6314
6315 pub(crate) fn load_workspace(
6316 serialized_workspace: SerializedWorkspace,
6317 paths_to_open: Vec<Option<ProjectPath>>,
6318 window: &mut Window,
6319 cx: &mut Context<Workspace>,
6320 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6321 cx.spawn_in(window, async move |workspace, cx| {
6322 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6323
6324 let mut center_group = None;
6325 let mut center_items = None;
6326
6327 // Traverse the splits tree and add to things
6328 if let Some((group, active_pane, items)) = serialized_workspace
6329 .center_group
6330 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6331 .await
6332 {
6333 center_items = Some(items);
6334 center_group = Some((group, active_pane))
6335 }
6336
6337 let mut items_by_project_path = HashMap::default();
6338 let mut item_ids_by_kind = HashMap::default();
6339 let mut all_deserialized_items = Vec::default();
6340 cx.update(|_, cx| {
6341 for item in center_items.unwrap_or_default().into_iter().flatten() {
6342 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6343 item_ids_by_kind
6344 .entry(serializable_item_handle.serialized_item_kind())
6345 .or_insert(Vec::new())
6346 .push(item.item_id().as_u64() as ItemId);
6347 }
6348
6349 if let Some(project_path) = item.project_path(cx) {
6350 items_by_project_path.insert(project_path, item.clone());
6351 }
6352 all_deserialized_items.push(item);
6353 }
6354 })?;
6355
6356 let opened_items = paths_to_open
6357 .into_iter()
6358 .map(|path_to_open| {
6359 path_to_open
6360 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6361 })
6362 .collect::<Vec<_>>();
6363
6364 // Remove old panes from workspace panes list
6365 workspace.update_in(cx, |workspace, window, cx| {
6366 if let Some((center_group, active_pane)) = center_group {
6367 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6368
6369 // Swap workspace center group
6370 workspace.center = PaneGroup::with_root(center_group);
6371 workspace.center.set_is_center(true);
6372 workspace.center.mark_positions(cx);
6373
6374 if let Some(active_pane) = active_pane {
6375 workspace.set_active_pane(&active_pane, window, cx);
6376 cx.focus_self(window);
6377 } else {
6378 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6379 }
6380 }
6381
6382 let docks = serialized_workspace.docks;
6383
6384 for (dock, serialized_dock) in [
6385 (&mut workspace.right_dock, docks.right),
6386 (&mut workspace.left_dock, docks.left),
6387 (&mut workspace.bottom_dock, docks.bottom),
6388 ]
6389 .iter_mut()
6390 {
6391 dock.update(cx, |dock, cx| {
6392 dock.serialized_dock = Some(serialized_dock.clone());
6393 dock.restore_state(window, cx);
6394 });
6395 }
6396
6397 cx.notify();
6398 })?;
6399
6400 let _ = project
6401 .update(cx, |project, cx| {
6402 project
6403 .breakpoint_store()
6404 .update(cx, |breakpoint_store, cx| {
6405 breakpoint_store
6406 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6407 })
6408 })
6409 .await;
6410
6411 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6412 // after loading the items, we might have different items and in order to avoid
6413 // the database filling up, we delete items that haven't been loaded now.
6414 //
6415 // The items that have been loaded, have been saved after they've been added to the workspace.
6416 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6417 item_ids_by_kind
6418 .into_iter()
6419 .map(|(item_kind, loaded_items)| {
6420 SerializableItemRegistry::cleanup(
6421 item_kind,
6422 serialized_workspace.id,
6423 loaded_items,
6424 window,
6425 cx,
6426 )
6427 .log_err()
6428 })
6429 .collect::<Vec<_>>()
6430 })?;
6431
6432 futures::future::join_all(clean_up_tasks).await;
6433
6434 workspace
6435 .update_in(cx, |workspace, window, cx| {
6436 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6437 workspace.serialize_workspace_internal(window, cx).detach();
6438
6439 // Ensure that we mark the window as edited if we did load dirty items
6440 workspace.update_window_edited(window, cx);
6441 })
6442 .ok();
6443
6444 Ok(opened_items)
6445 })
6446 }
6447
6448 pub fn key_context(&self, cx: &App) -> KeyContext {
6449 let mut context = KeyContext::new_with_defaults();
6450 context.add("Workspace");
6451 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6452 if let Some(status) = self
6453 .debugger_provider
6454 .as_ref()
6455 .and_then(|provider| provider.active_thread_state(cx))
6456 {
6457 match status {
6458 ThreadStatus::Running | ThreadStatus::Stepping => {
6459 context.add("debugger_running");
6460 }
6461 ThreadStatus::Stopped => context.add("debugger_stopped"),
6462 ThreadStatus::Exited | ThreadStatus::Ended => {}
6463 }
6464 }
6465
6466 if self.left_dock.read(cx).is_open() {
6467 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6468 context.set("left_dock", active_panel.panel_key());
6469 }
6470 }
6471
6472 if self.right_dock.read(cx).is_open() {
6473 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6474 context.set("right_dock", active_panel.panel_key());
6475 }
6476 }
6477
6478 if self.bottom_dock.read(cx).is_open() {
6479 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6480 context.set("bottom_dock", active_panel.panel_key());
6481 }
6482 }
6483
6484 context
6485 }
6486
6487 /// Multiworkspace uses this to add workspace action handling to itself
6488 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6489 self.add_workspace_actions_listeners(div, window, cx)
6490 .on_action(cx.listener(
6491 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6492 for action in &action_sequence.0 {
6493 window.dispatch_action(action.boxed_clone(), cx);
6494 }
6495 },
6496 ))
6497 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6498 .on_action(cx.listener(Self::close_all_items_and_panes))
6499 .on_action(cx.listener(Self::close_item_in_all_panes))
6500 .on_action(cx.listener(Self::save_all))
6501 .on_action(cx.listener(Self::send_keystrokes))
6502 .on_action(cx.listener(Self::add_folder_to_project))
6503 .on_action(cx.listener(Self::follow_next_collaborator))
6504 .on_action(cx.listener(Self::activate_pane_at_index))
6505 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6506 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6507 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6508 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6509 let pane = workspace.active_pane().clone();
6510 workspace.unfollow_in_pane(&pane, window, cx);
6511 }))
6512 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6513 workspace
6514 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6515 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6516 }))
6517 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6518 workspace
6519 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6520 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6521 }))
6522 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6523 workspace
6524 .save_active_item(SaveIntent::SaveAs, window, cx)
6525 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6526 }))
6527 .on_action(
6528 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6529 workspace.activate_previous_pane(window, cx)
6530 }),
6531 )
6532 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6533 workspace.activate_next_pane(window, cx)
6534 }))
6535 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6536 workspace.activate_last_pane(window, cx)
6537 }))
6538 .on_action(
6539 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6540 workspace.activate_next_window(cx)
6541 }),
6542 )
6543 .on_action(
6544 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6545 workspace.activate_previous_window(cx)
6546 }),
6547 )
6548 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6549 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6550 }))
6551 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6552 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6553 }))
6554 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6555 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6556 }))
6557 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6558 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6559 }))
6560 .on_action(cx.listener(
6561 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6562 workspace.move_item_to_pane_in_direction(action, window, cx)
6563 },
6564 ))
6565 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6566 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6567 }))
6568 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6569 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6570 }))
6571 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6572 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6573 }))
6574 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6575 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6576 }))
6577 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6578 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6579 SplitDirection::Down,
6580 SplitDirection::Up,
6581 SplitDirection::Right,
6582 SplitDirection::Left,
6583 ];
6584 for dir in DIRECTION_PRIORITY {
6585 if workspace.find_pane_in_direction(dir, cx).is_some() {
6586 workspace.swap_pane_in_direction(dir, cx);
6587 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6588 break;
6589 }
6590 }
6591 }))
6592 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6593 workspace.move_pane_to_border(SplitDirection::Left, cx)
6594 }))
6595 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6596 workspace.move_pane_to_border(SplitDirection::Right, cx)
6597 }))
6598 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6599 workspace.move_pane_to_border(SplitDirection::Up, cx)
6600 }))
6601 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6602 workspace.move_pane_to_border(SplitDirection::Down, cx)
6603 }))
6604 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6605 this.toggle_dock(DockPosition::Left, window, cx);
6606 }))
6607 .on_action(cx.listener(
6608 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6609 workspace.toggle_dock(DockPosition::Right, window, cx);
6610 },
6611 ))
6612 .on_action(cx.listener(
6613 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6614 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6615 },
6616 ))
6617 .on_action(cx.listener(
6618 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6619 if !workspace.close_active_dock(window, cx) {
6620 cx.propagate();
6621 }
6622 },
6623 ))
6624 .on_action(
6625 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6626 workspace.close_all_docks(window, cx);
6627 }),
6628 )
6629 .on_action(cx.listener(Self::toggle_all_docks))
6630 .on_action(cx.listener(
6631 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6632 workspace.clear_all_notifications(cx);
6633 },
6634 ))
6635 .on_action(cx.listener(
6636 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6637 workspace.clear_navigation_history(window, cx);
6638 },
6639 ))
6640 .on_action(cx.listener(
6641 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6642 if let Some((notification_id, _)) = workspace.notifications.pop() {
6643 workspace.suppress_notification(¬ification_id, cx);
6644 }
6645 },
6646 ))
6647 .on_action(cx.listener(
6648 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6649 workspace.show_worktree_trust_security_modal(true, window, cx);
6650 },
6651 ))
6652 .on_action(
6653 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6654 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6655 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6656 trusted_worktrees.clear_trusted_paths()
6657 });
6658 let clear_task = persistence::DB.clear_trusted_worktrees();
6659 cx.spawn(async move |_, cx| {
6660 if clear_task.await.log_err().is_some() {
6661 cx.update(|cx| reload(cx));
6662 }
6663 })
6664 .detach();
6665 }
6666 }),
6667 )
6668 .on_action(cx.listener(
6669 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
6670 workspace.reopen_closed_item(window, cx).detach();
6671 },
6672 ))
6673 .on_action(cx.listener(
6674 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
6675 for dock in workspace.all_docks() {
6676 if dock.focus_handle(cx).contains_focused(window, cx) {
6677 let Some(panel) = dock.read(cx).active_panel() else {
6678 return;
6679 };
6680
6681 // Set to `None`, then the size will fall back to the default.
6682 panel.clone().set_size(None, window, cx);
6683
6684 return;
6685 }
6686 }
6687 },
6688 ))
6689 .on_action(cx.listener(
6690 |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
6691 for dock in workspace.all_docks() {
6692 if let Some(panel) = dock.read(cx).visible_panel() {
6693 // Set to `None`, then the size will fall back to the default.
6694 panel.clone().set_size(None, window, cx);
6695 }
6696 }
6697 },
6698 ))
6699 .on_action(cx.listener(
6700 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
6701 adjust_active_dock_size_by_px(
6702 px_with_ui_font_fallback(act.px, cx),
6703 workspace,
6704 window,
6705 cx,
6706 );
6707 },
6708 ))
6709 .on_action(cx.listener(
6710 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
6711 adjust_active_dock_size_by_px(
6712 px_with_ui_font_fallback(act.px, cx) * -1.,
6713 workspace,
6714 window,
6715 cx,
6716 );
6717 },
6718 ))
6719 .on_action(cx.listener(
6720 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
6721 adjust_open_docks_size_by_px(
6722 px_with_ui_font_fallback(act.px, cx),
6723 workspace,
6724 window,
6725 cx,
6726 );
6727 },
6728 ))
6729 .on_action(cx.listener(
6730 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
6731 adjust_open_docks_size_by_px(
6732 px_with_ui_font_fallback(act.px, cx) * -1.,
6733 workspace,
6734 window,
6735 cx,
6736 );
6737 },
6738 ))
6739 .on_action(cx.listener(Workspace::toggle_centered_layout))
6740 .on_action(cx.listener(
6741 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
6742 if let Some(active_dock) = workspace.active_dock(window, cx) {
6743 let dock = active_dock.read(cx);
6744 if let Some(active_panel) = dock.active_panel() {
6745 if active_panel.pane(cx).is_none() {
6746 let mut recent_pane: Option<Entity<Pane>> = None;
6747 let mut recent_timestamp = 0;
6748 for pane_handle in workspace.panes() {
6749 let pane = pane_handle.read(cx);
6750 for entry in pane.activation_history() {
6751 if entry.timestamp > recent_timestamp {
6752 recent_timestamp = entry.timestamp;
6753 recent_pane = Some(pane_handle.clone());
6754 }
6755 }
6756 }
6757
6758 if let Some(pane) = recent_pane {
6759 pane.update(cx, |pane, cx| {
6760 let current_index = pane.active_item_index();
6761 let items_len = pane.items_len();
6762 if items_len > 0 {
6763 let next_index = if current_index + 1 < items_len {
6764 current_index + 1
6765 } else {
6766 0
6767 };
6768 pane.activate_item(
6769 next_index, false, false, window, cx,
6770 );
6771 }
6772 });
6773 return;
6774 }
6775 }
6776 }
6777 }
6778 cx.propagate();
6779 },
6780 ))
6781 .on_action(cx.listener(
6782 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
6783 if let Some(active_dock) = workspace.active_dock(window, cx) {
6784 let dock = active_dock.read(cx);
6785 if let Some(active_panel) = dock.active_panel() {
6786 if active_panel.pane(cx).is_none() {
6787 let mut recent_pane: Option<Entity<Pane>> = None;
6788 let mut recent_timestamp = 0;
6789 for pane_handle in workspace.panes() {
6790 let pane = pane_handle.read(cx);
6791 for entry in pane.activation_history() {
6792 if entry.timestamp > recent_timestamp {
6793 recent_timestamp = entry.timestamp;
6794 recent_pane = Some(pane_handle.clone());
6795 }
6796 }
6797 }
6798
6799 if let Some(pane) = recent_pane {
6800 pane.update(cx, |pane, cx| {
6801 let current_index = pane.active_item_index();
6802 let items_len = pane.items_len();
6803 if items_len > 0 {
6804 let prev_index = if current_index > 0 {
6805 current_index - 1
6806 } else {
6807 items_len.saturating_sub(1)
6808 };
6809 pane.activate_item(
6810 prev_index, false, false, window, cx,
6811 );
6812 }
6813 });
6814 return;
6815 }
6816 }
6817 }
6818 }
6819 cx.propagate();
6820 },
6821 ))
6822 .on_action(cx.listener(
6823 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
6824 if let Some(active_dock) = workspace.active_dock(window, cx) {
6825 let dock = active_dock.read(cx);
6826 if let Some(active_panel) = dock.active_panel() {
6827 if active_panel.pane(cx).is_none() {
6828 let active_pane = workspace.active_pane().clone();
6829 active_pane.update(cx, |pane, cx| {
6830 pane.close_active_item(action, window, cx)
6831 .detach_and_log_err(cx);
6832 });
6833 return;
6834 }
6835 }
6836 }
6837 cx.propagate();
6838 },
6839 ))
6840 .on_action(
6841 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
6842 let pane = workspace.active_pane().clone();
6843 if let Some(item) = pane.read(cx).active_item() {
6844 item.toggle_read_only(window, cx);
6845 }
6846 }),
6847 )
6848 .on_action(cx.listener(Workspace::cancel))
6849 }
6850
6851 #[cfg(any(test, feature = "test-support"))]
6852 pub fn set_random_database_id(&mut self) {
6853 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
6854 }
6855
6856 #[cfg(any(test, feature = "test-support"))]
6857 pub(crate) fn test_new(
6858 project: Entity<Project>,
6859 window: &mut Window,
6860 cx: &mut Context<Self>,
6861 ) -> Self {
6862 use node_runtime::NodeRuntime;
6863 use session::Session;
6864
6865 let client = project.read(cx).client();
6866 let user_store = project.read(cx).user_store();
6867 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
6868 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
6869 window.activate_window();
6870 let app_state = Arc::new(AppState {
6871 languages: project.read(cx).languages().clone(),
6872 workspace_store,
6873 client,
6874 user_store,
6875 fs: project.read(cx).fs().clone(),
6876 build_window_options: |_, _| Default::default(),
6877 node_runtime: NodeRuntime::unavailable(),
6878 session,
6879 });
6880 let workspace = Self::new(Default::default(), project, app_state, window, cx);
6881 workspace
6882 .active_pane
6883 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6884 workspace
6885 }
6886
6887 pub fn register_action<A: Action>(
6888 &mut self,
6889 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
6890 ) -> &mut Self {
6891 let callback = Arc::new(callback);
6892
6893 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
6894 let callback = callback.clone();
6895 div.on_action(cx.listener(move |workspace, event, window, cx| {
6896 (callback)(workspace, event, window, cx)
6897 }))
6898 }));
6899 self
6900 }
6901 pub fn register_action_renderer(
6902 &mut self,
6903 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
6904 ) -> &mut Self {
6905 self.workspace_actions.push(Box::new(callback));
6906 self
6907 }
6908
6909 fn add_workspace_actions_listeners(
6910 &self,
6911 mut div: Div,
6912 window: &mut Window,
6913 cx: &mut Context<Self>,
6914 ) -> Div {
6915 for action in self.workspace_actions.iter() {
6916 div = (action)(div, self, window, cx)
6917 }
6918 div
6919 }
6920
6921 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
6922 self.modal_layer.read(cx).has_active_modal()
6923 }
6924
6925 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
6926 self.modal_layer.read(cx).active_modal()
6927 }
6928
6929 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
6930 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
6931 /// If no modal is active, the new modal will be shown.
6932 ///
6933 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
6934 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
6935 /// will not be shown.
6936 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
6937 where
6938 B: FnOnce(&mut Window, &mut Context<V>) -> V,
6939 {
6940 self.modal_layer.update(cx, |modal_layer, cx| {
6941 modal_layer.toggle_modal(window, cx, build)
6942 })
6943 }
6944
6945 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
6946 self.modal_layer
6947 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
6948 }
6949
6950 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
6951 self.toast_layer
6952 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
6953 }
6954
6955 pub fn toggle_centered_layout(
6956 &mut self,
6957 _: &ToggleCenteredLayout,
6958 _: &mut Window,
6959 cx: &mut Context<Self>,
6960 ) {
6961 self.centered_layout = !self.centered_layout;
6962 if let Some(database_id) = self.database_id() {
6963 cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
6964 .detach_and_log_err(cx);
6965 }
6966 cx.notify();
6967 }
6968
6969 fn adjust_padding(padding: Option<f32>) -> f32 {
6970 padding
6971 .unwrap_or(CenteredPaddingSettings::default().0)
6972 .clamp(
6973 CenteredPaddingSettings::MIN_PADDING,
6974 CenteredPaddingSettings::MAX_PADDING,
6975 )
6976 }
6977
6978 fn render_dock(
6979 &self,
6980 position: DockPosition,
6981 dock: &Entity<Dock>,
6982 window: &mut Window,
6983 cx: &mut App,
6984 ) -> Option<Div> {
6985 if self.zoomed_position == Some(position) {
6986 return None;
6987 }
6988
6989 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
6990 let pane = panel.pane(cx)?;
6991 let follower_states = &self.follower_states;
6992 leader_border_for_pane(follower_states, &pane, window, cx)
6993 });
6994
6995 Some(
6996 div()
6997 .flex()
6998 .flex_none()
6999 .overflow_hidden()
7000 .child(dock.clone())
7001 .children(leader_border),
7002 )
7003 }
7004
7005 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7006 window
7007 .root::<MultiWorkspace>()
7008 .flatten()
7009 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7010 }
7011
7012 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7013 self.zoomed.as_ref()
7014 }
7015
7016 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7017 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7018 return;
7019 };
7020 let windows = cx.windows();
7021 let next_window =
7022 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7023 || {
7024 windows
7025 .iter()
7026 .cycle()
7027 .skip_while(|window| window.window_id() != current_window_id)
7028 .nth(1)
7029 },
7030 );
7031
7032 if let Some(window) = next_window {
7033 window
7034 .update(cx, |_, window, _| window.activate_window())
7035 .ok();
7036 }
7037 }
7038
7039 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7040 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7041 return;
7042 };
7043 let windows = cx.windows();
7044 let prev_window =
7045 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7046 || {
7047 windows
7048 .iter()
7049 .rev()
7050 .cycle()
7051 .skip_while(|window| window.window_id() != current_window_id)
7052 .nth(1)
7053 },
7054 );
7055
7056 if let Some(window) = prev_window {
7057 window
7058 .update(cx, |_, window, _| window.activate_window())
7059 .ok();
7060 }
7061 }
7062
7063 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7064 if cx.stop_active_drag(window) {
7065 } else if let Some((notification_id, _)) = self.notifications.pop() {
7066 dismiss_app_notification(¬ification_id, cx);
7067 } else {
7068 cx.propagate();
7069 }
7070 }
7071
7072 fn adjust_dock_size_by_px(
7073 &mut self,
7074 panel_size: Pixels,
7075 dock_pos: DockPosition,
7076 px: Pixels,
7077 window: &mut Window,
7078 cx: &mut Context<Self>,
7079 ) {
7080 match dock_pos {
7081 DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
7082 DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
7083 DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
7084 }
7085 }
7086
7087 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7088 let size = new_size.min(self.bounds.right() - RESIZE_HANDLE_SIZE);
7089
7090 self.left_dock.update(cx, |left_dock, cx| {
7091 if WorkspaceSettings::get_global(cx)
7092 .resize_all_panels_in_dock
7093 .contains(&DockPosition::Left)
7094 {
7095 left_dock.resize_all_panels(Some(size), window, cx);
7096 } else {
7097 left_dock.resize_active_panel(Some(size), window, cx);
7098 }
7099 });
7100 }
7101
7102 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7103 let mut size = new_size.max(self.bounds.left() - RESIZE_HANDLE_SIZE);
7104 self.left_dock.read_with(cx, |left_dock, cx| {
7105 let left_dock_size = left_dock
7106 .active_panel_size(window, cx)
7107 .unwrap_or(Pixels::ZERO);
7108 if left_dock_size + size > self.bounds.right() {
7109 size = self.bounds.right() - left_dock_size
7110 }
7111 });
7112 self.right_dock.update(cx, |right_dock, cx| {
7113 if WorkspaceSettings::get_global(cx)
7114 .resize_all_panels_in_dock
7115 .contains(&DockPosition::Right)
7116 {
7117 right_dock.resize_all_panels(Some(size), window, cx);
7118 } else {
7119 right_dock.resize_active_panel(Some(size), window, cx);
7120 }
7121 });
7122 }
7123
7124 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7125 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7126 self.bottom_dock.update(cx, |bottom_dock, cx| {
7127 if WorkspaceSettings::get_global(cx)
7128 .resize_all_panels_in_dock
7129 .contains(&DockPosition::Bottom)
7130 {
7131 bottom_dock.resize_all_panels(Some(size), window, cx);
7132 } else {
7133 bottom_dock.resize_active_panel(Some(size), window, cx);
7134 }
7135 });
7136 }
7137
7138 fn toggle_edit_predictions_all_files(
7139 &mut self,
7140 _: &ToggleEditPrediction,
7141 _window: &mut Window,
7142 cx: &mut Context<Self>,
7143 ) {
7144 let fs = self.project().read(cx).fs().clone();
7145 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7146 update_settings_file(fs, cx, move |file, _| {
7147 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7148 });
7149 }
7150
7151 pub fn show_worktree_trust_security_modal(
7152 &mut self,
7153 toggle: bool,
7154 window: &mut Window,
7155 cx: &mut Context<Self>,
7156 ) {
7157 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7158 if toggle {
7159 security_modal.update(cx, |security_modal, cx| {
7160 security_modal.dismiss(cx);
7161 })
7162 } else {
7163 security_modal.update(cx, |security_modal, cx| {
7164 security_modal.refresh_restricted_paths(cx);
7165 });
7166 }
7167 } else {
7168 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7169 .map(|trusted_worktrees| {
7170 trusted_worktrees
7171 .read(cx)
7172 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7173 })
7174 .unwrap_or(false);
7175 if has_restricted_worktrees {
7176 let project = self.project().read(cx);
7177 let remote_host = project
7178 .remote_connection_options(cx)
7179 .map(RemoteHostLocation::from);
7180 let worktree_store = project.worktree_store().downgrade();
7181 self.toggle_modal(window, cx, |_, cx| {
7182 SecurityModal::new(worktree_store, remote_host, cx)
7183 });
7184 }
7185 }
7186 }
7187}
7188
7189pub trait AnyActiveCall {
7190 fn entity(&self) -> AnyEntity;
7191 fn is_in_room(&self, _: &App) -> bool;
7192 fn room_id(&self, _: &App) -> Option<u64>;
7193 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7194 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7195 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7196 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7197 fn is_sharing_project(&self, _: &App) -> bool;
7198 fn has_remote_participants(&self, _: &App) -> bool;
7199 fn local_participant_is_guest(&self, _: &App) -> bool;
7200 fn client(&self, _: &App) -> Arc<Client>;
7201 fn share_on_join(&self, _: &App) -> bool;
7202 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7203 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7204 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7205 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7206 fn join_project(
7207 &self,
7208 _: u64,
7209 _: Arc<LanguageRegistry>,
7210 _: Arc<dyn Fs>,
7211 _: &mut App,
7212 ) -> Task<Result<Entity<Project>>>;
7213 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7214 fn subscribe(
7215 &self,
7216 _: &mut Window,
7217 _: &mut Context<Workspace>,
7218 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7219 ) -> Subscription;
7220 fn create_shared_screen(
7221 &self,
7222 _: PeerId,
7223 _: &Entity<Pane>,
7224 _: &mut Window,
7225 _: &mut App,
7226 ) -> Option<Entity<SharedScreen>>;
7227}
7228
7229#[derive(Clone)]
7230pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7231impl Global for GlobalAnyActiveCall {}
7232
7233impl GlobalAnyActiveCall {
7234 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7235 cx.try_global()
7236 }
7237
7238 pub(crate) fn global(cx: &App) -> &Self {
7239 cx.global()
7240 }
7241}
7242/// Workspace-local view of a remote participant's location.
7243#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7244pub enum ParticipantLocation {
7245 SharedProject { project_id: u64 },
7246 UnsharedProject,
7247 External,
7248}
7249
7250impl ParticipantLocation {
7251 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7252 match location
7253 .and_then(|l| l.variant)
7254 .context("participant location was not provided")?
7255 {
7256 proto::participant_location::Variant::SharedProject(project) => {
7257 Ok(Self::SharedProject {
7258 project_id: project.id,
7259 })
7260 }
7261 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7262 proto::participant_location::Variant::External(_) => Ok(Self::External),
7263 }
7264 }
7265}
7266/// Workspace-local view of a remote collaborator's state.
7267/// This is the subset of `call::RemoteParticipant` that workspace needs.
7268#[derive(Clone)]
7269pub struct RemoteCollaborator {
7270 pub user: Arc<User>,
7271 pub peer_id: PeerId,
7272 pub location: ParticipantLocation,
7273 pub participant_index: ParticipantIndex,
7274}
7275
7276pub enum ActiveCallEvent {
7277 ParticipantLocationChanged { participant_id: PeerId },
7278 RemoteVideoTracksChanged { participant_id: PeerId },
7279}
7280
7281fn leader_border_for_pane(
7282 follower_states: &HashMap<CollaboratorId, FollowerState>,
7283 pane: &Entity<Pane>,
7284 _: &Window,
7285 cx: &App,
7286) -> Option<Div> {
7287 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7288 if state.pane() == pane {
7289 Some((*leader_id, state))
7290 } else {
7291 None
7292 }
7293 })?;
7294
7295 let mut leader_color = match leader_id {
7296 CollaboratorId::PeerId(leader_peer_id) => {
7297 let leader = GlobalAnyActiveCall::try_global(cx)?
7298 .0
7299 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7300
7301 cx.theme()
7302 .players()
7303 .color_for_participant(leader.participant_index.0)
7304 .cursor
7305 }
7306 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7307 };
7308 leader_color.fade_out(0.3);
7309 Some(
7310 div()
7311 .absolute()
7312 .size_full()
7313 .left_0()
7314 .top_0()
7315 .border_2()
7316 .border_color(leader_color),
7317 )
7318}
7319
7320fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7321 ZED_WINDOW_POSITION
7322 .zip(*ZED_WINDOW_SIZE)
7323 .map(|(position, size)| Bounds {
7324 origin: position,
7325 size,
7326 })
7327}
7328
7329fn open_items(
7330 serialized_workspace: Option<SerializedWorkspace>,
7331 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7332 window: &mut Window,
7333 cx: &mut Context<Workspace>,
7334) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7335 let restored_items = serialized_workspace.map(|serialized_workspace| {
7336 Workspace::load_workspace(
7337 serialized_workspace,
7338 project_paths_to_open
7339 .iter()
7340 .map(|(_, project_path)| project_path)
7341 .cloned()
7342 .collect(),
7343 window,
7344 cx,
7345 )
7346 });
7347
7348 cx.spawn_in(window, async move |workspace, cx| {
7349 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7350
7351 if let Some(restored_items) = restored_items {
7352 let restored_items = restored_items.await?;
7353
7354 let restored_project_paths = restored_items
7355 .iter()
7356 .filter_map(|item| {
7357 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7358 .ok()
7359 .flatten()
7360 })
7361 .collect::<HashSet<_>>();
7362
7363 for restored_item in restored_items {
7364 opened_items.push(restored_item.map(Ok));
7365 }
7366
7367 project_paths_to_open
7368 .iter_mut()
7369 .for_each(|(_, project_path)| {
7370 if let Some(project_path_to_open) = project_path
7371 && restored_project_paths.contains(project_path_to_open)
7372 {
7373 *project_path = None;
7374 }
7375 });
7376 } else {
7377 for _ in 0..project_paths_to_open.len() {
7378 opened_items.push(None);
7379 }
7380 }
7381 assert!(opened_items.len() == project_paths_to_open.len());
7382
7383 let tasks =
7384 project_paths_to_open
7385 .into_iter()
7386 .enumerate()
7387 .map(|(ix, (abs_path, project_path))| {
7388 let workspace = workspace.clone();
7389 cx.spawn(async move |cx| {
7390 let file_project_path = project_path?;
7391 let abs_path_task = workspace.update(cx, |workspace, cx| {
7392 workspace.project().update(cx, |project, cx| {
7393 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7394 })
7395 });
7396
7397 // We only want to open file paths here. If one of the items
7398 // here is a directory, it was already opened further above
7399 // with a `find_or_create_worktree`.
7400 if let Ok(task) = abs_path_task
7401 && task.await.is_none_or(|p| p.is_file())
7402 {
7403 return Some((
7404 ix,
7405 workspace
7406 .update_in(cx, |workspace, window, cx| {
7407 workspace.open_path(
7408 file_project_path,
7409 None,
7410 true,
7411 window,
7412 cx,
7413 )
7414 })
7415 .log_err()?
7416 .await,
7417 ));
7418 }
7419 None
7420 })
7421 });
7422
7423 let tasks = tasks.collect::<Vec<_>>();
7424
7425 let tasks = futures::future::join_all(tasks);
7426 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7427 opened_items[ix] = Some(path_open_result);
7428 }
7429
7430 Ok(opened_items)
7431 })
7432}
7433
7434enum ActivateInDirectionTarget {
7435 Pane(Entity<Pane>),
7436 Dock(Entity<Dock>),
7437}
7438
7439fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7440 window
7441 .update(cx, |multi_workspace, _, cx| {
7442 let workspace = multi_workspace.workspace().clone();
7443 workspace.update(cx, |workspace, cx| {
7444 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7445 struct DatabaseFailedNotification;
7446
7447 workspace.show_notification(
7448 NotificationId::unique::<DatabaseFailedNotification>(),
7449 cx,
7450 |cx| {
7451 cx.new(|cx| {
7452 MessageNotification::new("Failed to load the database file.", cx)
7453 .primary_message("File an Issue")
7454 .primary_icon(IconName::Plus)
7455 .primary_on_click(|window, cx| {
7456 window.dispatch_action(Box::new(FileBugReport), cx)
7457 })
7458 })
7459 },
7460 );
7461 }
7462 });
7463 })
7464 .log_err();
7465}
7466
7467fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7468 if val == 0 {
7469 ThemeSettings::get_global(cx).ui_font_size(cx)
7470 } else {
7471 px(val as f32)
7472 }
7473}
7474
7475fn adjust_active_dock_size_by_px(
7476 px: Pixels,
7477 workspace: &mut Workspace,
7478 window: &mut Window,
7479 cx: &mut Context<Workspace>,
7480) {
7481 let Some(active_dock) = workspace
7482 .all_docks()
7483 .into_iter()
7484 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7485 else {
7486 return;
7487 };
7488 let dock = active_dock.read(cx);
7489 let Some(panel_size) = dock.active_panel_size(window, cx) else {
7490 return;
7491 };
7492 let dock_pos = dock.position();
7493 workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
7494}
7495
7496fn adjust_open_docks_size_by_px(
7497 px: Pixels,
7498 workspace: &mut Workspace,
7499 window: &mut Window,
7500 cx: &mut Context<Workspace>,
7501) {
7502 let docks = workspace
7503 .all_docks()
7504 .into_iter()
7505 .filter_map(|dock| {
7506 if dock.read(cx).is_open() {
7507 let dock = dock.read(cx);
7508 let panel_size = dock.active_panel_size(window, cx)?;
7509 let dock_pos = dock.position();
7510 Some((panel_size, dock_pos, px))
7511 } else {
7512 None
7513 }
7514 })
7515 .collect::<Vec<_>>();
7516
7517 docks
7518 .into_iter()
7519 .for_each(|(panel_size, dock_pos, offset)| {
7520 workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
7521 });
7522}
7523
7524impl Focusable for Workspace {
7525 fn focus_handle(&self, cx: &App) -> FocusHandle {
7526 self.active_pane.focus_handle(cx)
7527 }
7528}
7529
7530#[derive(Clone)]
7531struct DraggedDock(DockPosition);
7532
7533impl Render for DraggedDock {
7534 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7535 gpui::Empty
7536 }
7537}
7538
7539impl Render for Workspace {
7540 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7541 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7542 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7543 log::info!("Rendered first frame");
7544 }
7545
7546 let centered_layout = self.centered_layout
7547 && self.center.panes().len() == 1
7548 && self.active_item(cx).is_some();
7549 let render_padding = |size| {
7550 (size > 0.0).then(|| {
7551 div()
7552 .h_full()
7553 .w(relative(size))
7554 .bg(cx.theme().colors().editor_background)
7555 .border_color(cx.theme().colors().pane_group_border)
7556 })
7557 };
7558 let paddings = if centered_layout {
7559 let settings = WorkspaceSettings::get_global(cx).centered_layout;
7560 (
7561 render_padding(Self::adjust_padding(
7562 settings.left_padding.map(|padding| padding.0),
7563 )),
7564 render_padding(Self::adjust_padding(
7565 settings.right_padding.map(|padding| padding.0),
7566 )),
7567 )
7568 } else {
7569 (None, None)
7570 };
7571 let ui_font = theme::setup_ui_font(window, cx);
7572
7573 let theme = cx.theme().clone();
7574 let colors = theme.colors();
7575 let notification_entities = self
7576 .notifications
7577 .iter()
7578 .map(|(_, notification)| notification.entity_id())
7579 .collect::<Vec<_>>();
7580 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
7581
7582 div()
7583 .relative()
7584 .size_full()
7585 .flex()
7586 .flex_col()
7587 .font(ui_font)
7588 .gap_0()
7589 .justify_start()
7590 .items_start()
7591 .text_color(colors.text)
7592 .overflow_hidden()
7593 .children(self.titlebar_item.clone())
7594 .on_modifiers_changed(move |_, _, cx| {
7595 for &id in ¬ification_entities {
7596 cx.notify(id);
7597 }
7598 })
7599 .child(
7600 div()
7601 .size_full()
7602 .relative()
7603 .flex_1()
7604 .flex()
7605 .flex_col()
7606 .child(
7607 div()
7608 .id("workspace")
7609 .bg(colors.background)
7610 .relative()
7611 .flex_1()
7612 .w_full()
7613 .flex()
7614 .flex_col()
7615 .overflow_hidden()
7616 .border_t_1()
7617 .border_b_1()
7618 .border_color(colors.border)
7619 .child({
7620 let this = cx.entity();
7621 canvas(
7622 move |bounds, window, cx| {
7623 this.update(cx, |this, cx| {
7624 let bounds_changed = this.bounds != bounds;
7625 this.bounds = bounds;
7626
7627 if bounds_changed {
7628 this.left_dock.update(cx, |dock, cx| {
7629 dock.clamp_panel_size(
7630 bounds.size.width,
7631 window,
7632 cx,
7633 )
7634 });
7635
7636 this.right_dock.update(cx, |dock, cx| {
7637 dock.clamp_panel_size(
7638 bounds.size.width,
7639 window,
7640 cx,
7641 )
7642 });
7643
7644 this.bottom_dock.update(cx, |dock, cx| {
7645 dock.clamp_panel_size(
7646 bounds.size.height,
7647 window,
7648 cx,
7649 )
7650 });
7651 }
7652 })
7653 },
7654 |_, _, _, _| {},
7655 )
7656 .absolute()
7657 .size_full()
7658 })
7659 .when(self.zoomed.is_none(), |this| {
7660 this.on_drag_move(cx.listener(
7661 move |workspace,
7662 e: &DragMoveEvent<DraggedDock>,
7663 window,
7664 cx| {
7665 if workspace.previous_dock_drag_coordinates
7666 != Some(e.event.position)
7667 {
7668 workspace.previous_dock_drag_coordinates =
7669 Some(e.event.position);
7670 match e.drag(cx).0 {
7671 DockPosition::Left => {
7672 workspace.resize_left_dock(
7673 e.event.position.x
7674 - workspace.bounds.left(),
7675 window,
7676 cx,
7677 );
7678 }
7679 DockPosition::Right => {
7680 workspace.resize_right_dock(
7681 workspace.bounds.right()
7682 - e.event.position.x,
7683 window,
7684 cx,
7685 );
7686 }
7687 DockPosition::Bottom => {
7688 workspace.resize_bottom_dock(
7689 workspace.bounds.bottom()
7690 - e.event.position.y,
7691 window,
7692 cx,
7693 );
7694 }
7695 };
7696 workspace.serialize_workspace(window, cx);
7697 }
7698 },
7699 ))
7700
7701 })
7702 .child({
7703 match bottom_dock_layout {
7704 BottomDockLayout::Full => div()
7705 .flex()
7706 .flex_col()
7707 .h_full()
7708 .child(
7709 div()
7710 .flex()
7711 .flex_row()
7712 .flex_1()
7713 .overflow_hidden()
7714 .children(self.render_dock(
7715 DockPosition::Left,
7716 &self.left_dock,
7717 window,
7718 cx,
7719 ))
7720
7721 .child(
7722 div()
7723 .flex()
7724 .flex_col()
7725 .flex_1()
7726 .overflow_hidden()
7727 .child(
7728 h_flex()
7729 .flex_1()
7730 .when_some(
7731 paddings.0,
7732 |this, p| {
7733 this.child(
7734 p.border_r_1(),
7735 )
7736 },
7737 )
7738 .child(self.center.render(
7739 self.zoomed.as_ref(),
7740 &PaneRenderContext {
7741 follower_states:
7742 &self.follower_states,
7743 active_call: self.active_call(),
7744 active_pane: &self.active_pane,
7745 app_state: &self.app_state,
7746 project: &self.project,
7747 workspace: &self.weak_self,
7748 },
7749 window,
7750 cx,
7751 ))
7752 .when_some(
7753 paddings.1,
7754 |this, p| {
7755 this.child(
7756 p.border_l_1(),
7757 )
7758 },
7759 ),
7760 ),
7761 )
7762
7763 .children(self.render_dock(
7764 DockPosition::Right,
7765 &self.right_dock,
7766 window,
7767 cx,
7768 )),
7769 )
7770 .child(div().w_full().children(self.render_dock(
7771 DockPosition::Bottom,
7772 &self.bottom_dock,
7773 window,
7774 cx
7775 ))),
7776
7777 BottomDockLayout::LeftAligned => div()
7778 .flex()
7779 .flex_row()
7780 .h_full()
7781 .child(
7782 div()
7783 .flex()
7784 .flex_col()
7785 .flex_1()
7786 .h_full()
7787 .child(
7788 div()
7789 .flex()
7790 .flex_row()
7791 .flex_1()
7792 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
7793
7794 .child(
7795 div()
7796 .flex()
7797 .flex_col()
7798 .flex_1()
7799 .overflow_hidden()
7800 .child(
7801 h_flex()
7802 .flex_1()
7803 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7804 .child(self.center.render(
7805 self.zoomed.as_ref(),
7806 &PaneRenderContext {
7807 follower_states:
7808 &self.follower_states,
7809 active_call: self.active_call(),
7810 active_pane: &self.active_pane,
7811 app_state: &self.app_state,
7812 project: &self.project,
7813 workspace: &self.weak_self,
7814 },
7815 window,
7816 cx,
7817 ))
7818 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7819 )
7820 )
7821
7822 )
7823 .child(
7824 div()
7825 .w_full()
7826 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7827 ),
7828 )
7829 .children(self.render_dock(
7830 DockPosition::Right,
7831 &self.right_dock,
7832 window,
7833 cx,
7834 )),
7835
7836 BottomDockLayout::RightAligned => div()
7837 .flex()
7838 .flex_row()
7839 .h_full()
7840 .children(self.render_dock(
7841 DockPosition::Left,
7842 &self.left_dock,
7843 window,
7844 cx,
7845 ))
7846
7847 .child(
7848 div()
7849 .flex()
7850 .flex_col()
7851 .flex_1()
7852 .h_full()
7853 .child(
7854 div()
7855 .flex()
7856 .flex_row()
7857 .flex_1()
7858 .child(
7859 div()
7860 .flex()
7861 .flex_col()
7862 .flex_1()
7863 .overflow_hidden()
7864 .child(
7865 h_flex()
7866 .flex_1()
7867 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7868 .child(self.center.render(
7869 self.zoomed.as_ref(),
7870 &PaneRenderContext {
7871 follower_states:
7872 &self.follower_states,
7873 active_call: self.active_call(),
7874 active_pane: &self.active_pane,
7875 app_state: &self.app_state,
7876 project: &self.project,
7877 workspace: &self.weak_self,
7878 },
7879 window,
7880 cx,
7881 ))
7882 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7883 )
7884 )
7885
7886 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
7887 )
7888 .child(
7889 div()
7890 .w_full()
7891 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7892 ),
7893 ),
7894
7895 BottomDockLayout::Contained => div()
7896 .flex()
7897 .flex_row()
7898 .h_full()
7899 .children(self.render_dock(
7900 DockPosition::Left,
7901 &self.left_dock,
7902 window,
7903 cx,
7904 ))
7905
7906 .child(
7907 div()
7908 .flex()
7909 .flex_col()
7910 .flex_1()
7911 .overflow_hidden()
7912 .child(
7913 h_flex()
7914 .flex_1()
7915 .when_some(paddings.0, |this, p| {
7916 this.child(p.border_r_1())
7917 })
7918 .child(self.center.render(
7919 self.zoomed.as_ref(),
7920 &PaneRenderContext {
7921 follower_states:
7922 &self.follower_states,
7923 active_call: self.active_call(),
7924 active_pane: &self.active_pane,
7925 app_state: &self.app_state,
7926 project: &self.project,
7927 workspace: &self.weak_self,
7928 },
7929 window,
7930 cx,
7931 ))
7932 .when_some(paddings.1, |this, p| {
7933 this.child(p.border_l_1())
7934 }),
7935 )
7936 .children(self.render_dock(
7937 DockPosition::Bottom,
7938 &self.bottom_dock,
7939 window,
7940 cx,
7941 )),
7942 )
7943
7944 .children(self.render_dock(
7945 DockPosition::Right,
7946 &self.right_dock,
7947 window,
7948 cx,
7949 )),
7950 }
7951 })
7952 .children(self.zoomed.as_ref().and_then(|view| {
7953 let zoomed_view = view.upgrade()?;
7954 let div = div()
7955 .occlude()
7956 .absolute()
7957 .overflow_hidden()
7958 .border_color(colors.border)
7959 .bg(colors.background)
7960 .child(zoomed_view)
7961 .inset_0()
7962 .shadow_lg();
7963
7964 if !WorkspaceSettings::get_global(cx).zoomed_padding {
7965 return Some(div);
7966 }
7967
7968 Some(match self.zoomed_position {
7969 Some(DockPosition::Left) => div.right_2().border_r_1(),
7970 Some(DockPosition::Right) => div.left_2().border_l_1(),
7971 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
7972 None => {
7973 div.top_2().bottom_2().left_2().right_2().border_1()
7974 }
7975 })
7976 }))
7977 .children(self.render_notifications(window, cx)),
7978 )
7979 .when(self.status_bar_visible(cx), |parent| {
7980 parent.child(self.status_bar.clone())
7981 })
7982 .child(self.toast_layer.clone()),
7983 )
7984 }
7985}
7986
7987impl WorkspaceStore {
7988 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
7989 Self {
7990 workspaces: Default::default(),
7991 _subscriptions: vec![
7992 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
7993 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
7994 ],
7995 client,
7996 }
7997 }
7998
7999 pub fn update_followers(
8000 &self,
8001 project_id: Option<u64>,
8002 update: proto::update_followers::Variant,
8003 cx: &App,
8004 ) -> Option<()> {
8005 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8006 let room_id = active_call.0.room_id(cx)?;
8007 self.client
8008 .send(proto::UpdateFollowers {
8009 room_id,
8010 project_id,
8011 variant: Some(update),
8012 })
8013 .log_err()
8014 }
8015
8016 pub async fn handle_follow(
8017 this: Entity<Self>,
8018 envelope: TypedEnvelope<proto::Follow>,
8019 mut cx: AsyncApp,
8020 ) -> Result<proto::FollowResponse> {
8021 this.update(&mut cx, |this, cx| {
8022 let follower = Follower {
8023 project_id: envelope.payload.project_id,
8024 peer_id: envelope.original_sender_id()?,
8025 };
8026
8027 let mut response = proto::FollowResponse::default();
8028
8029 this.workspaces.retain(|(window_handle, weak_workspace)| {
8030 let Some(workspace) = weak_workspace.upgrade() else {
8031 return false;
8032 };
8033 window_handle
8034 .update(cx, |_, window, cx| {
8035 workspace.update(cx, |workspace, cx| {
8036 let handler_response =
8037 workspace.handle_follow(follower.project_id, window, cx);
8038 if let Some(active_view) = handler_response.active_view
8039 && workspace.project.read(cx).remote_id() == follower.project_id
8040 {
8041 response.active_view = Some(active_view)
8042 }
8043 });
8044 })
8045 .is_ok()
8046 });
8047
8048 Ok(response)
8049 })
8050 }
8051
8052 async fn handle_update_followers(
8053 this: Entity<Self>,
8054 envelope: TypedEnvelope<proto::UpdateFollowers>,
8055 mut cx: AsyncApp,
8056 ) -> Result<()> {
8057 let leader_id = envelope.original_sender_id()?;
8058 let update = envelope.payload;
8059
8060 this.update(&mut cx, |this, cx| {
8061 this.workspaces.retain(|(window_handle, weak_workspace)| {
8062 let Some(workspace) = weak_workspace.upgrade() else {
8063 return false;
8064 };
8065 window_handle
8066 .update(cx, |_, window, cx| {
8067 workspace.update(cx, |workspace, cx| {
8068 let project_id = workspace.project.read(cx).remote_id();
8069 if update.project_id != project_id && update.project_id.is_some() {
8070 return;
8071 }
8072 workspace.handle_update_followers(
8073 leader_id,
8074 update.clone(),
8075 window,
8076 cx,
8077 );
8078 });
8079 })
8080 .is_ok()
8081 });
8082 Ok(())
8083 })
8084 }
8085
8086 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8087 self.workspaces.iter().map(|(_, weak)| weak)
8088 }
8089
8090 pub fn workspaces_with_windows(
8091 &self,
8092 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8093 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8094 }
8095}
8096
8097impl ViewId {
8098 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8099 Ok(Self {
8100 creator: message
8101 .creator
8102 .map(CollaboratorId::PeerId)
8103 .context("creator is missing")?,
8104 id: message.id,
8105 })
8106 }
8107
8108 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8109 if let CollaboratorId::PeerId(peer_id) = self.creator {
8110 Some(proto::ViewId {
8111 creator: Some(peer_id),
8112 id: self.id,
8113 })
8114 } else {
8115 None
8116 }
8117 }
8118}
8119
8120impl FollowerState {
8121 fn pane(&self) -> &Entity<Pane> {
8122 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8123 }
8124}
8125
8126pub trait WorkspaceHandle {
8127 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8128}
8129
8130impl WorkspaceHandle for Entity<Workspace> {
8131 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8132 self.read(cx)
8133 .worktrees(cx)
8134 .flat_map(|worktree| {
8135 let worktree_id = worktree.read(cx).id();
8136 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8137 worktree_id,
8138 path: f.path.clone(),
8139 })
8140 })
8141 .collect::<Vec<_>>()
8142 }
8143}
8144
8145pub async fn last_opened_workspace_location(
8146 fs: &dyn fs::Fs,
8147) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8148 DB.last_workspace(fs)
8149 .await
8150 .log_err()
8151 .flatten()
8152 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8153}
8154
8155pub async fn last_session_workspace_locations(
8156 last_session_id: &str,
8157 last_session_window_stack: Option<Vec<WindowId>>,
8158 fs: &dyn fs::Fs,
8159) -> Option<Vec<SessionWorkspace>> {
8160 DB.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8161 .await
8162 .log_err()
8163}
8164
8165pub struct MultiWorkspaceRestoreResult {
8166 pub window_handle: WindowHandle<MultiWorkspace>,
8167 pub errors: Vec<anyhow::Error>,
8168}
8169
8170pub async fn restore_multiworkspace(
8171 multi_workspace: SerializedMultiWorkspace,
8172 app_state: Arc<AppState>,
8173 cx: &mut AsyncApp,
8174) -> anyhow::Result<MultiWorkspaceRestoreResult> {
8175 let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
8176 let mut group_iter = workspaces.into_iter();
8177 let first = group_iter
8178 .next()
8179 .context("window group must not be empty")?;
8180
8181 let window_handle = if first.paths.is_empty() {
8182 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
8183 .await?
8184 } else {
8185 let (window, _items) = cx
8186 .update(|cx| {
8187 Workspace::new_local(
8188 first.paths.paths().to_vec(),
8189 app_state.clone(),
8190 None,
8191 None,
8192 None,
8193 true,
8194 cx,
8195 )
8196 })
8197 .await?;
8198 window
8199 };
8200
8201 let mut errors = Vec::new();
8202
8203 for session_workspace in group_iter {
8204 let error = if session_workspace.paths.is_empty() {
8205 cx.update(|cx| {
8206 open_workspace_by_id(
8207 session_workspace.workspace_id,
8208 app_state.clone(),
8209 Some(window_handle),
8210 cx,
8211 )
8212 })
8213 .await
8214 .err()
8215 } else {
8216 cx.update(|cx| {
8217 Workspace::new_local(
8218 session_workspace.paths.paths().to_vec(),
8219 app_state.clone(),
8220 Some(window_handle),
8221 None,
8222 None,
8223 true,
8224 cx,
8225 )
8226 })
8227 .await
8228 .err()
8229 };
8230
8231 if let Some(error) = error {
8232 errors.push(error);
8233 }
8234 }
8235
8236 if let Some(target_id) = state.active_workspace_id {
8237 window_handle
8238 .update(cx, |multi_workspace, window, cx| {
8239 let target_index = multi_workspace
8240 .workspaces()
8241 .iter()
8242 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8243 if let Some(index) = target_index {
8244 multi_workspace.activate_index(index, window, cx);
8245 } else if !multi_workspace.workspaces().is_empty() {
8246 multi_workspace.activate_index(0, window, cx);
8247 }
8248 })
8249 .ok();
8250 } else {
8251 window_handle
8252 .update(cx, |multi_workspace, window, cx| {
8253 if !multi_workspace.workspaces().is_empty() {
8254 multi_workspace.activate_index(0, window, cx);
8255 }
8256 })
8257 .ok();
8258 }
8259
8260 if state.sidebar_open {
8261 window_handle
8262 .update(cx, |multi_workspace, _, cx| {
8263 multi_workspace.open_sidebar(cx);
8264 })
8265 .ok();
8266 }
8267
8268 window_handle
8269 .update(cx, |_, window, _cx| {
8270 window.activate_window();
8271 })
8272 .ok();
8273
8274 Ok(MultiWorkspaceRestoreResult {
8275 window_handle,
8276 errors,
8277 })
8278}
8279
8280actions!(
8281 collab,
8282 [
8283 /// Opens the channel notes for the current call.
8284 ///
8285 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8286 /// channel in the collab panel.
8287 ///
8288 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8289 /// can be copied via "Copy link to section" in the context menu of the channel notes
8290 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8291 OpenChannelNotes,
8292 /// Mutes your microphone.
8293 Mute,
8294 /// Deafens yourself (mute both microphone and speakers).
8295 Deafen,
8296 /// Leaves the current call.
8297 LeaveCall,
8298 /// Shares the current project with collaborators.
8299 ShareProject,
8300 /// Shares your screen with collaborators.
8301 ScreenShare,
8302 /// Copies the current room name and session id for debugging purposes.
8303 CopyRoomId,
8304 ]
8305);
8306actions!(
8307 zed,
8308 [
8309 /// Opens the Zed log file.
8310 OpenLog,
8311 /// Reveals the Zed log file in the system file manager.
8312 RevealLogInFileManager
8313 ]
8314);
8315
8316async fn join_channel_internal(
8317 channel_id: ChannelId,
8318 app_state: &Arc<AppState>,
8319 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8320 requesting_workspace: Option<WeakEntity<Workspace>>,
8321 active_call: &dyn AnyActiveCall,
8322 cx: &mut AsyncApp,
8323) -> Result<bool> {
8324 let (should_prompt, already_in_channel) = cx.update(|cx| {
8325 if !active_call.is_in_room(cx) {
8326 return (false, false);
8327 }
8328
8329 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8330 let should_prompt = active_call.is_sharing_project(cx)
8331 && active_call.has_remote_participants(cx)
8332 && !already_in_channel;
8333 (should_prompt, already_in_channel)
8334 });
8335
8336 if already_in_channel {
8337 let task = cx.update(|cx| {
8338 if let Some((project, host)) = active_call.most_active_project(cx) {
8339 Some(join_in_room_project(project, host, app_state.clone(), cx))
8340 } else {
8341 None
8342 }
8343 });
8344 if let Some(task) = task {
8345 task.await?;
8346 }
8347 return anyhow::Ok(true);
8348 }
8349
8350 if should_prompt {
8351 if let Some(multi_workspace) = requesting_window {
8352 let answer = multi_workspace
8353 .update(cx, |_, window, cx| {
8354 window.prompt(
8355 PromptLevel::Warning,
8356 "Do you want to switch channels?",
8357 Some("Leaving this call will unshare your current project."),
8358 &["Yes, Join Channel", "Cancel"],
8359 cx,
8360 )
8361 })?
8362 .await;
8363
8364 if answer == Ok(1) {
8365 return Ok(false);
8366 }
8367 } else {
8368 return Ok(false);
8369 }
8370 }
8371
8372 let client = cx.update(|cx| active_call.client(cx));
8373
8374 let mut client_status = client.status();
8375
8376 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8377 'outer: loop {
8378 let Some(status) = client_status.recv().await else {
8379 anyhow::bail!("error connecting");
8380 };
8381
8382 match status {
8383 Status::Connecting
8384 | Status::Authenticating
8385 | Status::Authenticated
8386 | Status::Reconnecting
8387 | Status::Reauthenticating
8388 | Status::Reauthenticated => continue,
8389 Status::Connected { .. } => break 'outer,
8390 Status::SignedOut | Status::AuthenticationError => {
8391 return Err(ErrorCode::SignedOut.into());
8392 }
8393 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8394 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8395 return Err(ErrorCode::Disconnected.into());
8396 }
8397 }
8398 }
8399
8400 let joined = cx
8401 .update(|cx| active_call.join_channel(channel_id, cx))
8402 .await?;
8403
8404 if !joined {
8405 return anyhow::Ok(true);
8406 }
8407
8408 cx.update(|cx| active_call.room_update_completed(cx)).await;
8409
8410 let task = cx.update(|cx| {
8411 if let Some((project, host)) = active_call.most_active_project(cx) {
8412 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8413 }
8414
8415 // If you are the first to join a channel, see if you should share your project.
8416 if !active_call.has_remote_participants(cx)
8417 && !active_call.local_participant_is_guest(cx)
8418 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8419 {
8420 let project = workspace.update(cx, |workspace, cx| {
8421 let project = workspace.project.read(cx);
8422
8423 if !active_call.share_on_join(cx) {
8424 return None;
8425 }
8426
8427 if (project.is_local() || project.is_via_remote_server())
8428 && project.visible_worktrees(cx).any(|tree| {
8429 tree.read(cx)
8430 .root_entry()
8431 .is_some_and(|entry| entry.is_dir())
8432 })
8433 {
8434 Some(workspace.project.clone())
8435 } else {
8436 None
8437 }
8438 });
8439 if let Some(project) = project {
8440 let share_task = active_call.share_project(project, cx);
8441 return Some(cx.spawn(async move |_cx| -> Result<()> {
8442 share_task.await?;
8443 Ok(())
8444 }));
8445 }
8446 }
8447
8448 None
8449 });
8450 if let Some(task) = task {
8451 task.await?;
8452 return anyhow::Ok(true);
8453 }
8454 anyhow::Ok(false)
8455}
8456
8457pub fn join_channel(
8458 channel_id: ChannelId,
8459 app_state: Arc<AppState>,
8460 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8461 requesting_workspace: Option<WeakEntity<Workspace>>,
8462 cx: &mut App,
8463) -> Task<Result<()>> {
8464 let active_call = GlobalAnyActiveCall::global(cx).clone();
8465 cx.spawn(async move |cx| {
8466 let result = join_channel_internal(
8467 channel_id,
8468 &app_state,
8469 requesting_window,
8470 requesting_workspace,
8471 &*active_call.0,
8472 cx,
8473 )
8474 .await;
8475
8476 // join channel succeeded, and opened a window
8477 if matches!(result, Ok(true)) {
8478 return anyhow::Ok(());
8479 }
8480
8481 // find an existing workspace to focus and show call controls
8482 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8483 if active_window.is_none() {
8484 // no open workspaces, make one to show the error in (blergh)
8485 let (window_handle, _) = cx
8486 .update(|cx| {
8487 Workspace::new_local(
8488 vec![],
8489 app_state.clone(),
8490 requesting_window,
8491 None,
8492 None,
8493 true,
8494 cx,
8495 )
8496 })
8497 .await?;
8498
8499 window_handle
8500 .update(cx, |_, window, _cx| {
8501 window.activate_window();
8502 })
8503 .ok();
8504
8505 if result.is_ok() {
8506 cx.update(|cx| {
8507 cx.dispatch_action(&OpenChannelNotes);
8508 });
8509 }
8510
8511 active_window = Some(window_handle);
8512 }
8513
8514 if let Err(err) = result {
8515 log::error!("failed to join channel: {}", err);
8516 if let Some(active_window) = active_window {
8517 active_window
8518 .update(cx, |_, window, cx| {
8519 let detail: SharedString = match err.error_code() {
8520 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8521 ErrorCode::UpgradeRequired => concat!(
8522 "Your are running an unsupported version of Zed. ",
8523 "Please update to continue."
8524 )
8525 .into(),
8526 ErrorCode::NoSuchChannel => concat!(
8527 "No matching channel was found. ",
8528 "Please check the link and try again."
8529 )
8530 .into(),
8531 ErrorCode::Forbidden => concat!(
8532 "This channel is private, and you do not have access. ",
8533 "Please ask someone to add you and try again."
8534 )
8535 .into(),
8536 ErrorCode::Disconnected => {
8537 "Please check your internet connection and try again.".into()
8538 }
8539 _ => format!("{}\n\nPlease try again.", err).into(),
8540 };
8541 window.prompt(
8542 PromptLevel::Critical,
8543 "Failed to join channel",
8544 Some(&detail),
8545 &["Ok"],
8546 cx,
8547 )
8548 })?
8549 .await
8550 .ok();
8551 }
8552 }
8553
8554 // return ok, we showed the error to the user.
8555 anyhow::Ok(())
8556 })
8557}
8558
8559pub async fn get_any_active_multi_workspace(
8560 app_state: Arc<AppState>,
8561 mut cx: AsyncApp,
8562) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8563 // find an existing workspace to focus and show call controls
8564 let active_window = activate_any_workspace_window(&mut cx);
8565 if active_window.is_none() {
8566 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
8567 .await?;
8568 }
8569 activate_any_workspace_window(&mut cx).context("could not open zed")
8570}
8571
8572fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
8573 cx.update(|cx| {
8574 if let Some(workspace_window) = cx
8575 .active_window()
8576 .and_then(|window| window.downcast::<MultiWorkspace>())
8577 {
8578 return Some(workspace_window);
8579 }
8580
8581 for window in cx.windows() {
8582 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
8583 workspace_window
8584 .update(cx, |_, window, _| window.activate_window())
8585 .ok();
8586 return Some(workspace_window);
8587 }
8588 }
8589 None
8590 })
8591}
8592
8593pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
8594 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
8595}
8596
8597pub fn workspace_windows_for_location(
8598 serialized_location: &SerializedWorkspaceLocation,
8599 cx: &App,
8600) -> Vec<WindowHandle<MultiWorkspace>> {
8601 cx.windows()
8602 .into_iter()
8603 .filter_map(|window| window.downcast::<MultiWorkspace>())
8604 .filter(|multi_workspace| {
8605 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
8606 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
8607 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
8608 }
8609 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
8610 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
8611 a.distro_name == b.distro_name
8612 }
8613 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
8614 a.container_id == b.container_id
8615 }
8616 #[cfg(any(test, feature = "test-support"))]
8617 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
8618 a.id == b.id
8619 }
8620 _ => false,
8621 };
8622
8623 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
8624 multi_workspace.workspaces().iter().any(|workspace| {
8625 match workspace.read(cx).workspace_location(cx) {
8626 WorkspaceLocation::Location(location, _) => {
8627 match (&location, serialized_location) {
8628 (
8629 SerializedWorkspaceLocation::Local,
8630 SerializedWorkspaceLocation::Local,
8631 ) => true,
8632 (
8633 SerializedWorkspaceLocation::Remote(a),
8634 SerializedWorkspaceLocation::Remote(b),
8635 ) => same_host(a, b),
8636 _ => false,
8637 }
8638 }
8639 _ => false,
8640 }
8641 })
8642 })
8643 })
8644 .collect()
8645}
8646
8647pub async fn find_existing_workspace(
8648 abs_paths: &[PathBuf],
8649 open_options: &OpenOptions,
8650 location: &SerializedWorkspaceLocation,
8651 cx: &mut AsyncApp,
8652) -> (
8653 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
8654 OpenVisible,
8655) {
8656 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
8657 let mut open_visible = OpenVisible::All;
8658 let mut best_match = None;
8659
8660 if open_options.open_new_workspace != Some(true) {
8661 cx.update(|cx| {
8662 for window in workspace_windows_for_location(location, cx) {
8663 if let Ok(multi_workspace) = window.read(cx) {
8664 for workspace in multi_workspace.workspaces() {
8665 let project = workspace.read(cx).project.read(cx);
8666 let m = project.visibility_for_paths(
8667 abs_paths,
8668 open_options.open_new_workspace == None,
8669 cx,
8670 );
8671 if m > best_match {
8672 existing = Some((window, workspace.clone()));
8673 best_match = m;
8674 } else if best_match.is_none()
8675 && open_options.open_new_workspace == Some(false)
8676 {
8677 existing = Some((window, workspace.clone()))
8678 }
8679 }
8680 }
8681 }
8682 });
8683
8684 let all_paths_are_files = existing
8685 .as_ref()
8686 .and_then(|(_, target_workspace)| {
8687 cx.update(|cx| {
8688 let workspace = target_workspace.read(cx);
8689 let project = workspace.project.read(cx);
8690 let path_style = workspace.path_style(cx);
8691 Some(!abs_paths.iter().any(|path| {
8692 let path = util::paths::SanitizedPath::new(path);
8693 project.worktrees(cx).any(|worktree| {
8694 let worktree = worktree.read(cx);
8695 let abs_path = worktree.abs_path();
8696 path_style
8697 .strip_prefix(path.as_ref(), abs_path.as_ref())
8698 .and_then(|rel| worktree.entry_for_path(&rel))
8699 .is_some_and(|e| e.is_dir())
8700 })
8701 }))
8702 })
8703 })
8704 .unwrap_or(false);
8705
8706 if open_options.open_new_workspace.is_none()
8707 && existing.is_some()
8708 && open_options.wait
8709 && all_paths_are_files
8710 {
8711 cx.update(|cx| {
8712 let windows = workspace_windows_for_location(location, cx);
8713 let window = cx
8714 .active_window()
8715 .and_then(|window| window.downcast::<MultiWorkspace>())
8716 .filter(|window| windows.contains(window))
8717 .or_else(|| windows.into_iter().next());
8718 if let Some(window) = window {
8719 if let Ok(multi_workspace) = window.read(cx) {
8720 let active_workspace = multi_workspace.workspace().clone();
8721 existing = Some((window, active_workspace));
8722 open_visible = OpenVisible::None;
8723 }
8724 }
8725 });
8726 }
8727 }
8728 (existing, open_visible)
8729}
8730
8731#[derive(Default, Clone)]
8732pub struct OpenOptions {
8733 pub visible: Option<OpenVisible>,
8734 pub focus: Option<bool>,
8735 pub open_new_workspace: Option<bool>,
8736 pub wait: bool,
8737 pub replace_window: Option<WindowHandle<MultiWorkspace>>,
8738 pub env: Option<HashMap<String, String>>,
8739}
8740
8741/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
8742pub fn open_workspace_by_id(
8743 workspace_id: WorkspaceId,
8744 app_state: Arc<AppState>,
8745 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8746 cx: &mut App,
8747) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
8748 let project_handle = Project::local(
8749 app_state.client.clone(),
8750 app_state.node_runtime.clone(),
8751 app_state.user_store.clone(),
8752 app_state.languages.clone(),
8753 app_state.fs.clone(),
8754 None,
8755 project::LocalProjectFlags {
8756 init_worktree_trust: true,
8757 ..project::LocalProjectFlags::default()
8758 },
8759 cx,
8760 );
8761
8762 cx.spawn(async move |cx| {
8763 let serialized_workspace = persistence::DB
8764 .workspace_for_id(workspace_id)
8765 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
8766
8767 let centered_layout = serialized_workspace.centered_layout;
8768
8769 let (window, workspace) = if let Some(window) = requesting_window {
8770 let workspace = window.update(cx, |multi_workspace, window, cx| {
8771 let workspace = cx.new(|cx| {
8772 let mut workspace = Workspace::new(
8773 Some(workspace_id),
8774 project_handle.clone(),
8775 app_state.clone(),
8776 window,
8777 cx,
8778 );
8779 workspace.centered_layout = centered_layout;
8780 workspace
8781 });
8782 multi_workspace.add_workspace(workspace.clone(), cx);
8783 workspace
8784 })?;
8785 (window, workspace)
8786 } else {
8787 let window_bounds_override = window_bounds_env_override();
8788
8789 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
8790 (Some(WindowBounds::Windowed(bounds)), None)
8791 } else if let Some(display) = serialized_workspace.display
8792 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
8793 {
8794 (Some(bounds.0), Some(display))
8795 } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
8796 (Some(bounds), Some(display))
8797 } else {
8798 (None, None)
8799 };
8800
8801 let options = cx.update(|cx| {
8802 let mut options = (app_state.build_window_options)(display, cx);
8803 options.window_bounds = window_bounds;
8804 options
8805 });
8806
8807 let window = cx.open_window(options, {
8808 let app_state = app_state.clone();
8809 let project_handle = project_handle.clone();
8810 move |window, cx| {
8811 let workspace = cx.new(|cx| {
8812 let mut workspace = Workspace::new(
8813 Some(workspace_id),
8814 project_handle,
8815 app_state,
8816 window,
8817 cx,
8818 );
8819 workspace.centered_layout = centered_layout;
8820 workspace
8821 });
8822 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
8823 }
8824 })?;
8825
8826 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
8827 multi_workspace.workspace().clone()
8828 })?;
8829
8830 (window, workspace)
8831 };
8832
8833 notify_if_database_failed(window, cx);
8834
8835 // Restore items from the serialized workspace
8836 window
8837 .update(cx, |_, window, cx| {
8838 workspace.update(cx, |_workspace, cx| {
8839 open_items(Some(serialized_workspace), vec![], window, cx)
8840 })
8841 })?
8842 .await?;
8843
8844 window.update(cx, |_, window, cx| {
8845 workspace.update(cx, |workspace, cx| {
8846 workspace.serialize_workspace(window, cx);
8847 });
8848 })?;
8849
8850 Ok(window)
8851 })
8852}
8853
8854#[allow(clippy::type_complexity)]
8855pub fn open_paths(
8856 abs_paths: &[PathBuf],
8857 app_state: Arc<AppState>,
8858 open_options: OpenOptions,
8859 cx: &mut App,
8860) -> Task<
8861 anyhow::Result<(
8862 WindowHandle<MultiWorkspace>,
8863 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
8864 )>,
8865> {
8866 let abs_paths = abs_paths.to_vec();
8867 #[cfg(target_os = "windows")]
8868 let wsl_path = abs_paths
8869 .iter()
8870 .find_map(|p| util::paths::WslPath::from_path(p));
8871
8872 cx.spawn(async move |cx| {
8873 let (mut existing, mut open_visible) = find_existing_workspace(
8874 &abs_paths,
8875 &open_options,
8876 &SerializedWorkspaceLocation::Local,
8877 cx,
8878 )
8879 .await;
8880
8881 // Fallback: if no workspace contains the paths and all paths are files,
8882 // prefer an existing local workspace window (active window first).
8883 if open_options.open_new_workspace.is_none() && existing.is_none() {
8884 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
8885 let all_metadatas = futures::future::join_all(all_paths)
8886 .await
8887 .into_iter()
8888 .filter_map(|result| result.ok().flatten())
8889 .collect::<Vec<_>>();
8890
8891 if all_metadatas.iter().all(|file| !file.is_dir) {
8892 cx.update(|cx| {
8893 let windows = workspace_windows_for_location(
8894 &SerializedWorkspaceLocation::Local,
8895 cx,
8896 );
8897 let window = cx
8898 .active_window()
8899 .and_then(|window| window.downcast::<MultiWorkspace>())
8900 .filter(|window| windows.contains(window))
8901 .or_else(|| windows.into_iter().next());
8902 if let Some(window) = window {
8903 if let Ok(multi_workspace) = window.read(cx) {
8904 let active_workspace = multi_workspace.workspace().clone();
8905 existing = Some((window, active_workspace));
8906 open_visible = OpenVisible::None;
8907 }
8908 }
8909 });
8910 }
8911 }
8912
8913 let result = if let Some((existing, target_workspace)) = existing {
8914 let open_task = existing
8915 .update(cx, |multi_workspace, window, cx| {
8916 window.activate_window();
8917 multi_workspace.activate(target_workspace.clone(), cx);
8918 target_workspace.update(cx, |workspace, cx| {
8919 workspace.open_paths(
8920 abs_paths,
8921 OpenOptions {
8922 visible: Some(open_visible),
8923 ..Default::default()
8924 },
8925 None,
8926 window,
8927 cx,
8928 )
8929 })
8930 })?
8931 .await;
8932
8933 _ = existing.update(cx, |multi_workspace, _, cx| {
8934 let workspace = multi_workspace.workspace().clone();
8935 workspace.update(cx, |workspace, cx| {
8936 for item in open_task.iter().flatten() {
8937 if let Err(e) = item {
8938 workspace.show_error(&e, cx);
8939 }
8940 }
8941 });
8942 });
8943
8944 Ok((existing, open_task))
8945 } else {
8946 let result = cx
8947 .update(move |cx| {
8948 Workspace::new_local(
8949 abs_paths,
8950 app_state.clone(),
8951 open_options.replace_window,
8952 open_options.env,
8953 None,
8954 true,
8955 cx,
8956 )
8957 })
8958 .await;
8959
8960 if let Ok((ref window_handle, _)) = result {
8961 window_handle
8962 .update(cx, |_, window, _cx| {
8963 window.activate_window();
8964 })
8965 .log_err();
8966 }
8967
8968 result
8969 };
8970
8971 #[cfg(target_os = "windows")]
8972 if let Some(util::paths::WslPath{distro, path}) = wsl_path
8973 && let Ok((multi_workspace_window, _)) = &result
8974 {
8975 multi_workspace_window
8976 .update(cx, move |multi_workspace, _window, cx| {
8977 struct OpenInWsl;
8978 let workspace = multi_workspace.workspace().clone();
8979 workspace.update(cx, |workspace, cx| {
8980 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
8981 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
8982 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
8983 cx.new(move |cx| {
8984 MessageNotification::new(msg, cx)
8985 .primary_message("Open in WSL")
8986 .primary_icon(IconName::FolderOpen)
8987 .primary_on_click(move |window, cx| {
8988 window.dispatch_action(Box::new(remote::OpenWslPath {
8989 distro: remote::WslConnectionOptions {
8990 distro_name: distro.clone(),
8991 user: None,
8992 },
8993 paths: vec![path.clone().into()],
8994 }), cx)
8995 })
8996 })
8997 });
8998 });
8999 })
9000 .unwrap();
9001 };
9002 result
9003 })
9004}
9005
9006pub fn open_new(
9007 open_options: OpenOptions,
9008 app_state: Arc<AppState>,
9009 cx: &mut App,
9010 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9011) -> Task<anyhow::Result<()>> {
9012 let task = Workspace::new_local(
9013 Vec::new(),
9014 app_state,
9015 open_options.replace_window,
9016 open_options.env,
9017 Some(Box::new(init)),
9018 true,
9019 cx,
9020 );
9021 cx.spawn(async move |cx| {
9022 let (window, _opened_paths) = task.await?;
9023 window
9024 .update(cx, |_, window, _cx| {
9025 window.activate_window();
9026 })
9027 .ok();
9028 Ok(())
9029 })
9030}
9031
9032pub fn create_and_open_local_file(
9033 path: &'static Path,
9034 window: &mut Window,
9035 cx: &mut Context<Workspace>,
9036 default_content: impl 'static + Send + FnOnce() -> Rope,
9037) -> Task<Result<Box<dyn ItemHandle>>> {
9038 cx.spawn_in(window, async move |workspace, cx| {
9039 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9040 if !fs.is_file(path).await {
9041 fs.create_file(path, Default::default()).await?;
9042 fs.save(path, &default_content(), Default::default())
9043 .await?;
9044 }
9045
9046 workspace
9047 .update_in(cx, |workspace, window, cx| {
9048 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9049 let path = workspace
9050 .project
9051 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9052 cx.spawn_in(window, async move |workspace, cx| {
9053 let path = path.await?;
9054 let mut items = workspace
9055 .update_in(cx, |workspace, window, cx| {
9056 workspace.open_paths(
9057 vec![path.to_path_buf()],
9058 OpenOptions {
9059 visible: Some(OpenVisible::None),
9060 ..Default::default()
9061 },
9062 None,
9063 window,
9064 cx,
9065 )
9066 })?
9067 .await;
9068 let item = items.pop().flatten();
9069 item.with_context(|| format!("path {path:?} is not a file"))?
9070 })
9071 })
9072 })?
9073 .await?
9074 .await
9075 })
9076}
9077
9078pub fn open_remote_project_with_new_connection(
9079 window: WindowHandle<MultiWorkspace>,
9080 remote_connection: Arc<dyn RemoteConnection>,
9081 cancel_rx: oneshot::Receiver<()>,
9082 delegate: Arc<dyn RemoteClientDelegate>,
9083 app_state: Arc<AppState>,
9084 paths: Vec<PathBuf>,
9085 cx: &mut App,
9086) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9087 cx.spawn(async move |cx| {
9088 let (workspace_id, serialized_workspace) =
9089 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9090 .await?;
9091
9092 let session = match cx
9093 .update(|cx| {
9094 remote::RemoteClient::new(
9095 ConnectionIdentifier::Workspace(workspace_id.0),
9096 remote_connection,
9097 cancel_rx,
9098 delegate,
9099 cx,
9100 )
9101 })
9102 .await?
9103 {
9104 Some(result) => result,
9105 None => return Ok(Vec::new()),
9106 };
9107
9108 let project = cx.update(|cx| {
9109 project::Project::remote(
9110 session,
9111 app_state.client.clone(),
9112 app_state.node_runtime.clone(),
9113 app_state.user_store.clone(),
9114 app_state.languages.clone(),
9115 app_state.fs.clone(),
9116 true,
9117 cx,
9118 )
9119 });
9120
9121 open_remote_project_inner(
9122 project,
9123 paths,
9124 workspace_id,
9125 serialized_workspace,
9126 app_state,
9127 window,
9128 cx,
9129 )
9130 .await
9131 })
9132}
9133
9134pub fn open_remote_project_with_existing_connection(
9135 connection_options: RemoteConnectionOptions,
9136 project: Entity<Project>,
9137 paths: Vec<PathBuf>,
9138 app_state: Arc<AppState>,
9139 window: WindowHandle<MultiWorkspace>,
9140 cx: &mut AsyncApp,
9141) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9142 cx.spawn(async move |cx| {
9143 let (workspace_id, serialized_workspace) =
9144 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9145
9146 open_remote_project_inner(
9147 project,
9148 paths,
9149 workspace_id,
9150 serialized_workspace,
9151 app_state,
9152 window,
9153 cx,
9154 )
9155 .await
9156 })
9157}
9158
9159async fn open_remote_project_inner(
9160 project: Entity<Project>,
9161 paths: Vec<PathBuf>,
9162 workspace_id: WorkspaceId,
9163 serialized_workspace: Option<SerializedWorkspace>,
9164 app_state: Arc<AppState>,
9165 window: WindowHandle<MultiWorkspace>,
9166 cx: &mut AsyncApp,
9167) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9168 let toolchains = DB.toolchains(workspace_id).await?;
9169 for (toolchain, worktree_path, path) in toolchains {
9170 project
9171 .update(cx, |this, cx| {
9172 let Some(worktree_id) =
9173 this.find_worktree(&worktree_path, cx)
9174 .and_then(|(worktree, rel_path)| {
9175 if rel_path.is_empty() {
9176 Some(worktree.read(cx).id())
9177 } else {
9178 None
9179 }
9180 })
9181 else {
9182 return Task::ready(None);
9183 };
9184
9185 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9186 })
9187 .await;
9188 }
9189 let mut project_paths_to_open = vec![];
9190 let mut project_path_errors = vec![];
9191
9192 for path in paths {
9193 let result = cx
9194 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9195 .await;
9196 match result {
9197 Ok((_, project_path)) => {
9198 project_paths_to_open.push((path.clone(), Some(project_path)));
9199 }
9200 Err(error) => {
9201 project_path_errors.push(error);
9202 }
9203 };
9204 }
9205
9206 if project_paths_to_open.is_empty() {
9207 return Err(project_path_errors.pop().context("no paths given")?);
9208 }
9209
9210 let workspace = window.update(cx, |multi_workspace, window, cx| {
9211 telemetry::event!("SSH Project Opened");
9212
9213 let new_workspace = cx.new(|cx| {
9214 let mut workspace =
9215 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9216 workspace.update_history(cx);
9217
9218 if let Some(ref serialized) = serialized_workspace {
9219 workspace.centered_layout = serialized.centered_layout;
9220 }
9221
9222 workspace
9223 });
9224
9225 multi_workspace.activate(new_workspace.clone(), cx);
9226 new_workspace
9227 })?;
9228
9229 let items = window
9230 .update(cx, |_, window, cx| {
9231 window.activate_window();
9232 workspace.update(cx, |_workspace, cx| {
9233 open_items(serialized_workspace, project_paths_to_open, window, cx)
9234 })
9235 })?
9236 .await?;
9237
9238 workspace.update(cx, |workspace, cx| {
9239 for error in project_path_errors {
9240 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9241 if let Some(path) = error.error_tag("path") {
9242 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9243 }
9244 } else {
9245 workspace.show_error(&error, cx)
9246 }
9247 }
9248 });
9249
9250 Ok(items.into_iter().map(|item| item?.ok()).collect())
9251}
9252
9253fn deserialize_remote_project(
9254 connection_options: RemoteConnectionOptions,
9255 paths: Vec<PathBuf>,
9256 cx: &AsyncApp,
9257) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9258 cx.background_spawn(async move {
9259 let remote_connection_id = persistence::DB
9260 .get_or_create_remote_connection(connection_options)
9261 .await?;
9262
9263 let serialized_workspace =
9264 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
9265
9266 let workspace_id = if let Some(workspace_id) =
9267 serialized_workspace.as_ref().map(|workspace| workspace.id)
9268 {
9269 workspace_id
9270 } else {
9271 persistence::DB.next_id().await?
9272 };
9273
9274 Ok((workspace_id, serialized_workspace))
9275 })
9276}
9277
9278pub fn join_in_room_project(
9279 project_id: u64,
9280 follow_user_id: u64,
9281 app_state: Arc<AppState>,
9282 cx: &mut App,
9283) -> Task<Result<()>> {
9284 let windows = cx.windows();
9285 cx.spawn(async move |cx| {
9286 let existing_window_and_workspace: Option<(
9287 WindowHandle<MultiWorkspace>,
9288 Entity<Workspace>,
9289 )> = windows.into_iter().find_map(|window_handle| {
9290 window_handle
9291 .downcast::<MultiWorkspace>()
9292 .and_then(|window_handle| {
9293 window_handle
9294 .update(cx, |multi_workspace, _window, cx| {
9295 for workspace in multi_workspace.workspaces() {
9296 if workspace.read(cx).project().read(cx).remote_id()
9297 == Some(project_id)
9298 {
9299 return Some((window_handle, workspace.clone()));
9300 }
9301 }
9302 None
9303 })
9304 .unwrap_or(None)
9305 })
9306 });
9307
9308 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9309 existing_window_and_workspace
9310 {
9311 existing_window
9312 .update(cx, |multi_workspace, _, cx| {
9313 multi_workspace.activate(target_workspace, cx);
9314 })
9315 .ok();
9316 existing_window
9317 } else {
9318 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9319 let project = cx
9320 .update(|cx| {
9321 active_call.0.join_project(
9322 project_id,
9323 app_state.languages.clone(),
9324 app_state.fs.clone(),
9325 cx,
9326 )
9327 })
9328 .await?;
9329
9330 let window_bounds_override = window_bounds_env_override();
9331 cx.update(|cx| {
9332 let mut options = (app_state.build_window_options)(None, cx);
9333 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9334 cx.open_window(options, |window, cx| {
9335 let workspace = cx.new(|cx| {
9336 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9337 });
9338 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9339 })
9340 })?
9341 };
9342
9343 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9344 cx.activate(true);
9345 window.activate_window();
9346
9347 // We set the active workspace above, so this is the correct workspace.
9348 let workspace = multi_workspace.workspace().clone();
9349 workspace.update(cx, |workspace, cx| {
9350 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9351 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9352 .or_else(|| {
9353 // If we couldn't follow the given user, follow the host instead.
9354 let collaborator = workspace
9355 .project()
9356 .read(cx)
9357 .collaborators()
9358 .values()
9359 .find(|collaborator| collaborator.is_host)?;
9360 Some(collaborator.peer_id)
9361 });
9362
9363 if let Some(follow_peer_id) = follow_peer_id {
9364 workspace.follow(follow_peer_id, window, cx);
9365 }
9366 });
9367 })?;
9368
9369 anyhow::Ok(())
9370 })
9371}
9372
9373pub fn reload(cx: &mut App) {
9374 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9375 let mut workspace_windows = cx
9376 .windows()
9377 .into_iter()
9378 .filter_map(|window| window.downcast::<MultiWorkspace>())
9379 .collect::<Vec<_>>();
9380
9381 // If multiple windows have unsaved changes, and need a save prompt,
9382 // prompt in the active window before switching to a different window.
9383 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9384
9385 let mut prompt = None;
9386 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9387 prompt = window
9388 .update(cx, |_, window, cx| {
9389 window.prompt(
9390 PromptLevel::Info,
9391 "Are you sure you want to restart?",
9392 None,
9393 &["Restart", "Cancel"],
9394 cx,
9395 )
9396 })
9397 .ok();
9398 }
9399
9400 cx.spawn(async move |cx| {
9401 if let Some(prompt) = prompt {
9402 let answer = prompt.await?;
9403 if answer != 0 {
9404 return anyhow::Ok(());
9405 }
9406 }
9407
9408 // If the user cancels any save prompt, then keep the app open.
9409 for window in workspace_windows {
9410 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9411 let workspace = multi_workspace.workspace().clone();
9412 workspace.update(cx, |workspace, cx| {
9413 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9414 })
9415 }) && !should_close.await?
9416 {
9417 return anyhow::Ok(());
9418 }
9419 }
9420 cx.update(|cx| cx.restart());
9421 anyhow::Ok(())
9422 })
9423 .detach_and_log_err(cx);
9424}
9425
9426fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9427 let mut parts = value.split(',');
9428 let x: usize = parts.next()?.parse().ok()?;
9429 let y: usize = parts.next()?.parse().ok()?;
9430 Some(point(px(x as f32), px(y as f32)))
9431}
9432
9433fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9434 let mut parts = value.split(',');
9435 let width: usize = parts.next()?.parse().ok()?;
9436 let height: usize = parts.next()?.parse().ok()?;
9437 Some(size(px(width as f32), px(height as f32)))
9438}
9439
9440/// Add client-side decorations (rounded corners, shadows, resize handling) when
9441/// appropriate.
9442///
9443/// The `border_radius_tiling` parameter allows overriding which corners get
9444/// rounded, independently of the actual window tiling state. This is used
9445/// specifically for the workspace switcher sidebar: when the sidebar is open,
9446/// we want square corners on the left (so the sidebar appears flush with the
9447/// window edge) but we still need the shadow padding for proper visual
9448/// appearance. Unlike actual window tiling, this only affects border radius -
9449/// not padding or shadows.
9450pub fn client_side_decorations(
9451 element: impl IntoElement,
9452 window: &mut Window,
9453 cx: &mut App,
9454 border_radius_tiling: Tiling,
9455) -> Stateful<Div> {
9456 const BORDER_SIZE: Pixels = px(1.0);
9457 let decorations = window.window_decorations();
9458 let tiling = match decorations {
9459 Decorations::Server => Tiling::default(),
9460 Decorations::Client { tiling } => tiling,
9461 };
9462
9463 match decorations {
9464 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9465 Decorations::Server => window.set_client_inset(px(0.0)),
9466 }
9467
9468 struct GlobalResizeEdge(ResizeEdge);
9469 impl Global for GlobalResizeEdge {}
9470
9471 div()
9472 .id("window-backdrop")
9473 .bg(transparent_black())
9474 .map(|div| match decorations {
9475 Decorations::Server => div,
9476 Decorations::Client { .. } => div
9477 .when(
9478 !(tiling.top
9479 || tiling.right
9480 || border_radius_tiling.top
9481 || border_radius_tiling.right),
9482 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9483 )
9484 .when(
9485 !(tiling.top
9486 || tiling.left
9487 || border_radius_tiling.top
9488 || border_radius_tiling.left),
9489 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9490 )
9491 .when(
9492 !(tiling.bottom
9493 || tiling.right
9494 || border_radius_tiling.bottom
9495 || border_radius_tiling.right),
9496 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9497 )
9498 .when(
9499 !(tiling.bottom
9500 || tiling.left
9501 || border_radius_tiling.bottom
9502 || border_radius_tiling.left),
9503 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9504 )
9505 .when(!tiling.top, |div| {
9506 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9507 })
9508 .when(!tiling.bottom, |div| {
9509 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9510 })
9511 .when(!tiling.left, |div| {
9512 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9513 })
9514 .when(!tiling.right, |div| {
9515 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9516 })
9517 .on_mouse_move(move |e, window, cx| {
9518 let size = window.window_bounds().get_bounds().size;
9519 let pos = e.position;
9520
9521 let new_edge =
9522 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9523
9524 let edge = cx.try_global::<GlobalResizeEdge>();
9525 if new_edge != edge.map(|edge| edge.0) {
9526 window
9527 .window_handle()
9528 .update(cx, |workspace, _, cx| {
9529 cx.notify(workspace.entity_id());
9530 })
9531 .ok();
9532 }
9533 })
9534 .on_mouse_down(MouseButton::Left, move |e, window, _| {
9535 let size = window.window_bounds().get_bounds().size;
9536 let pos = e.position;
9537
9538 let edge = match resize_edge(
9539 pos,
9540 theme::CLIENT_SIDE_DECORATION_SHADOW,
9541 size,
9542 tiling,
9543 ) {
9544 Some(value) => value,
9545 None => return,
9546 };
9547
9548 window.start_window_resize(edge);
9549 }),
9550 })
9551 .size_full()
9552 .child(
9553 div()
9554 .cursor(CursorStyle::Arrow)
9555 .map(|div| match decorations {
9556 Decorations::Server => div,
9557 Decorations::Client { .. } => div
9558 .border_color(cx.theme().colors().border)
9559 .when(
9560 !(tiling.top
9561 || tiling.right
9562 || border_radius_tiling.top
9563 || border_radius_tiling.right),
9564 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9565 )
9566 .when(
9567 !(tiling.top
9568 || tiling.left
9569 || border_radius_tiling.top
9570 || border_radius_tiling.left),
9571 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9572 )
9573 .when(
9574 !(tiling.bottom
9575 || tiling.right
9576 || border_radius_tiling.bottom
9577 || border_radius_tiling.right),
9578 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9579 )
9580 .when(
9581 !(tiling.bottom
9582 || tiling.left
9583 || border_radius_tiling.bottom
9584 || border_radius_tiling.left),
9585 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9586 )
9587 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
9588 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
9589 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
9590 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
9591 .when(!tiling.is_tiled(), |div| {
9592 div.shadow(vec![gpui::BoxShadow {
9593 color: Hsla {
9594 h: 0.,
9595 s: 0.,
9596 l: 0.,
9597 a: 0.4,
9598 },
9599 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
9600 spread_radius: px(0.),
9601 offset: point(px(0.0), px(0.0)),
9602 }])
9603 }),
9604 })
9605 .on_mouse_move(|_e, _, cx| {
9606 cx.stop_propagation();
9607 })
9608 .size_full()
9609 .child(element),
9610 )
9611 .map(|div| match decorations {
9612 Decorations::Server => div,
9613 Decorations::Client { tiling, .. } => div.child(
9614 canvas(
9615 |_bounds, window, _| {
9616 window.insert_hitbox(
9617 Bounds::new(
9618 point(px(0.0), px(0.0)),
9619 window.window_bounds().get_bounds().size,
9620 ),
9621 HitboxBehavior::Normal,
9622 )
9623 },
9624 move |_bounds, hitbox, window, cx| {
9625 let mouse = window.mouse_position();
9626 let size = window.window_bounds().get_bounds().size;
9627 let Some(edge) =
9628 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
9629 else {
9630 return;
9631 };
9632 cx.set_global(GlobalResizeEdge(edge));
9633 window.set_cursor_style(
9634 match edge {
9635 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
9636 ResizeEdge::Left | ResizeEdge::Right => {
9637 CursorStyle::ResizeLeftRight
9638 }
9639 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
9640 CursorStyle::ResizeUpLeftDownRight
9641 }
9642 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
9643 CursorStyle::ResizeUpRightDownLeft
9644 }
9645 },
9646 &hitbox,
9647 );
9648 },
9649 )
9650 .size_full()
9651 .absolute(),
9652 ),
9653 })
9654}
9655
9656fn resize_edge(
9657 pos: Point<Pixels>,
9658 shadow_size: Pixels,
9659 window_size: Size<Pixels>,
9660 tiling: Tiling,
9661) -> Option<ResizeEdge> {
9662 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
9663 if bounds.contains(&pos) {
9664 return None;
9665 }
9666
9667 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
9668 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
9669 if !tiling.top && top_left_bounds.contains(&pos) {
9670 return Some(ResizeEdge::TopLeft);
9671 }
9672
9673 let top_right_bounds = Bounds::new(
9674 Point::new(window_size.width - corner_size.width, px(0.)),
9675 corner_size,
9676 );
9677 if !tiling.top && top_right_bounds.contains(&pos) {
9678 return Some(ResizeEdge::TopRight);
9679 }
9680
9681 let bottom_left_bounds = Bounds::new(
9682 Point::new(px(0.), window_size.height - corner_size.height),
9683 corner_size,
9684 );
9685 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
9686 return Some(ResizeEdge::BottomLeft);
9687 }
9688
9689 let bottom_right_bounds = Bounds::new(
9690 Point::new(
9691 window_size.width - corner_size.width,
9692 window_size.height - corner_size.height,
9693 ),
9694 corner_size,
9695 );
9696 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
9697 return Some(ResizeEdge::BottomRight);
9698 }
9699
9700 if !tiling.top && pos.y < shadow_size {
9701 Some(ResizeEdge::Top)
9702 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
9703 Some(ResizeEdge::Bottom)
9704 } else if !tiling.left && pos.x < shadow_size {
9705 Some(ResizeEdge::Left)
9706 } else if !tiling.right && pos.x > window_size.width - shadow_size {
9707 Some(ResizeEdge::Right)
9708 } else {
9709 None
9710 }
9711}
9712
9713fn join_pane_into_active(
9714 active_pane: &Entity<Pane>,
9715 pane: &Entity<Pane>,
9716 window: &mut Window,
9717 cx: &mut App,
9718) {
9719 if pane == active_pane {
9720 } else if pane.read(cx).items_len() == 0 {
9721 pane.update(cx, |_, cx| {
9722 cx.emit(pane::Event::Remove {
9723 focus_on_pane: None,
9724 });
9725 })
9726 } else {
9727 move_all_items(pane, active_pane, window, cx);
9728 }
9729}
9730
9731fn move_all_items(
9732 from_pane: &Entity<Pane>,
9733 to_pane: &Entity<Pane>,
9734 window: &mut Window,
9735 cx: &mut App,
9736) {
9737 let destination_is_different = from_pane != to_pane;
9738 let mut moved_items = 0;
9739 for (item_ix, item_handle) in from_pane
9740 .read(cx)
9741 .items()
9742 .enumerate()
9743 .map(|(ix, item)| (ix, item.clone()))
9744 .collect::<Vec<_>>()
9745 {
9746 let ix = item_ix - moved_items;
9747 if destination_is_different {
9748 // Close item from previous pane
9749 from_pane.update(cx, |source, cx| {
9750 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
9751 });
9752 moved_items += 1;
9753 }
9754
9755 // This automatically removes duplicate items in the pane
9756 to_pane.update(cx, |destination, cx| {
9757 destination.add_item(item_handle, true, true, None, window, cx);
9758 window.focus(&destination.focus_handle(cx), cx)
9759 });
9760 }
9761}
9762
9763pub fn move_item(
9764 source: &Entity<Pane>,
9765 destination: &Entity<Pane>,
9766 item_id_to_move: EntityId,
9767 destination_index: usize,
9768 activate: bool,
9769 window: &mut Window,
9770 cx: &mut App,
9771) {
9772 let Some((item_ix, item_handle)) = source
9773 .read(cx)
9774 .items()
9775 .enumerate()
9776 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
9777 .map(|(ix, item)| (ix, item.clone()))
9778 else {
9779 // Tab was closed during drag
9780 return;
9781 };
9782
9783 if source != destination {
9784 // Close item from previous pane
9785 source.update(cx, |source, cx| {
9786 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
9787 });
9788 }
9789
9790 // This automatically removes duplicate items in the pane
9791 destination.update(cx, |destination, cx| {
9792 destination.add_item_inner(
9793 item_handle,
9794 activate,
9795 activate,
9796 activate,
9797 Some(destination_index),
9798 window,
9799 cx,
9800 );
9801 if activate {
9802 window.focus(&destination.focus_handle(cx), cx)
9803 }
9804 });
9805}
9806
9807pub fn move_active_item(
9808 source: &Entity<Pane>,
9809 destination: &Entity<Pane>,
9810 focus_destination: bool,
9811 close_if_empty: bool,
9812 window: &mut Window,
9813 cx: &mut App,
9814) {
9815 if source == destination {
9816 return;
9817 }
9818 let Some(active_item) = source.read(cx).active_item() else {
9819 return;
9820 };
9821 source.update(cx, |source_pane, cx| {
9822 let item_id = active_item.item_id();
9823 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
9824 destination.update(cx, |target_pane, cx| {
9825 target_pane.add_item(
9826 active_item,
9827 focus_destination,
9828 focus_destination,
9829 Some(target_pane.items_len()),
9830 window,
9831 cx,
9832 );
9833 });
9834 });
9835}
9836
9837pub fn clone_active_item(
9838 workspace_id: Option<WorkspaceId>,
9839 source: &Entity<Pane>,
9840 destination: &Entity<Pane>,
9841 focus_destination: bool,
9842 window: &mut Window,
9843 cx: &mut App,
9844) {
9845 if source == destination {
9846 return;
9847 }
9848 let Some(active_item) = source.read(cx).active_item() else {
9849 return;
9850 };
9851 if !active_item.can_split(cx) {
9852 return;
9853 }
9854 let destination = destination.downgrade();
9855 let task = active_item.clone_on_split(workspace_id, window, cx);
9856 window
9857 .spawn(cx, async move |cx| {
9858 let Some(clone) = task.await else {
9859 return;
9860 };
9861 destination
9862 .update_in(cx, |target_pane, window, cx| {
9863 target_pane.add_item(
9864 clone,
9865 focus_destination,
9866 focus_destination,
9867 Some(target_pane.items_len()),
9868 window,
9869 cx,
9870 );
9871 })
9872 .log_err();
9873 })
9874 .detach();
9875}
9876
9877#[derive(Debug)]
9878pub struct WorkspacePosition {
9879 pub window_bounds: Option<WindowBounds>,
9880 pub display: Option<Uuid>,
9881 pub centered_layout: bool,
9882}
9883
9884pub fn remote_workspace_position_from_db(
9885 connection_options: RemoteConnectionOptions,
9886 paths_to_open: &[PathBuf],
9887 cx: &App,
9888) -> Task<Result<WorkspacePosition>> {
9889 let paths = paths_to_open.to_vec();
9890
9891 cx.background_spawn(async move {
9892 let remote_connection_id = persistence::DB
9893 .get_or_create_remote_connection(connection_options)
9894 .await
9895 .context("fetching serialized ssh project")?;
9896 let serialized_workspace =
9897 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
9898
9899 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
9900 (Some(WindowBounds::Windowed(bounds)), None)
9901 } else {
9902 let restorable_bounds = serialized_workspace
9903 .as_ref()
9904 .and_then(|workspace| {
9905 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
9906 })
9907 .or_else(|| persistence::read_default_window_bounds());
9908
9909 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
9910 (Some(serialized_bounds), Some(serialized_display))
9911 } else {
9912 (None, None)
9913 }
9914 };
9915
9916 let centered_layout = serialized_workspace
9917 .as_ref()
9918 .map(|w| w.centered_layout)
9919 .unwrap_or(false);
9920
9921 Ok(WorkspacePosition {
9922 window_bounds,
9923 display,
9924 centered_layout,
9925 })
9926 })
9927}
9928
9929pub fn with_active_or_new_workspace(
9930 cx: &mut App,
9931 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
9932) {
9933 match cx
9934 .active_window()
9935 .and_then(|w| w.downcast::<MultiWorkspace>())
9936 {
9937 Some(multi_workspace) => {
9938 cx.defer(move |cx| {
9939 multi_workspace
9940 .update(cx, |multi_workspace, window, cx| {
9941 let workspace = multi_workspace.workspace().clone();
9942 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
9943 })
9944 .log_err();
9945 });
9946 }
9947 None => {
9948 let app_state = AppState::global(cx);
9949 if let Some(app_state) = app_state.upgrade() {
9950 open_new(
9951 OpenOptions::default(),
9952 app_state,
9953 cx,
9954 move |workspace, window, cx| f(workspace, window, cx),
9955 )
9956 .detach_and_log_err(cx);
9957 }
9958 }
9959 }
9960}
9961
9962#[cfg(test)]
9963mod tests {
9964 use std::{cell::RefCell, rc::Rc};
9965
9966 use super::*;
9967 use crate::{
9968 dock::{PanelEvent, test::TestPanel},
9969 item::{
9970 ItemBufferKind, ItemEvent,
9971 test::{TestItem, TestProjectItem},
9972 },
9973 };
9974 use fs::FakeFs;
9975 use gpui::{
9976 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
9977 UpdateGlobal, VisualTestContext, px,
9978 };
9979 use project::{Project, ProjectEntryId};
9980 use serde_json::json;
9981 use settings::SettingsStore;
9982 use util::rel_path::rel_path;
9983
9984 #[gpui::test]
9985 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
9986 init_test(cx);
9987
9988 let fs = FakeFs::new(cx.executor());
9989 let project = Project::test(fs, [], cx).await;
9990 let (workspace, cx) =
9991 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9992
9993 // Adding an item with no ambiguity renders the tab without detail.
9994 let item1 = cx.new(|cx| {
9995 let mut item = TestItem::new(cx);
9996 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
9997 item
9998 });
9999 workspace.update_in(cx, |workspace, window, cx| {
10000 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10001 });
10002 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10003
10004 // Adding an item that creates ambiguity increases the level of detail on
10005 // both tabs.
10006 let item2 = cx.new_window_entity(|_window, cx| {
10007 let mut item = TestItem::new(cx);
10008 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10009 item
10010 });
10011 workspace.update_in(cx, |workspace, window, cx| {
10012 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10013 });
10014 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10015 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10016
10017 // Adding an item that creates ambiguity increases the level of detail only
10018 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10019 // we stop at the highest detail available.
10020 let item3 = cx.new(|cx| {
10021 let mut item = TestItem::new(cx);
10022 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10023 item
10024 });
10025 workspace.update_in(cx, |workspace, window, cx| {
10026 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10027 });
10028 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10029 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10030 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10031 }
10032
10033 #[gpui::test]
10034 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10035 init_test(cx);
10036
10037 let fs = FakeFs::new(cx.executor());
10038 fs.insert_tree(
10039 "/root1",
10040 json!({
10041 "one.txt": "",
10042 "two.txt": "",
10043 }),
10044 )
10045 .await;
10046 fs.insert_tree(
10047 "/root2",
10048 json!({
10049 "three.txt": "",
10050 }),
10051 )
10052 .await;
10053
10054 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10055 let (workspace, cx) =
10056 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10057 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10058 let worktree_id = project.update(cx, |project, cx| {
10059 project.worktrees(cx).next().unwrap().read(cx).id()
10060 });
10061
10062 let item1 = cx.new(|cx| {
10063 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10064 });
10065 let item2 = cx.new(|cx| {
10066 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10067 });
10068
10069 // Add an item to an empty pane
10070 workspace.update_in(cx, |workspace, window, cx| {
10071 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10072 });
10073 project.update(cx, |project, cx| {
10074 assert_eq!(
10075 project.active_entry(),
10076 project
10077 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10078 .map(|e| e.id)
10079 );
10080 });
10081 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10082
10083 // Add a second item to a non-empty pane
10084 workspace.update_in(cx, |workspace, window, cx| {
10085 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10086 });
10087 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10088 project.update(cx, |project, cx| {
10089 assert_eq!(
10090 project.active_entry(),
10091 project
10092 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10093 .map(|e| e.id)
10094 );
10095 });
10096
10097 // Close the active item
10098 pane.update_in(cx, |pane, window, cx| {
10099 pane.close_active_item(&Default::default(), window, cx)
10100 })
10101 .await
10102 .unwrap();
10103 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10104 project.update(cx, |project, cx| {
10105 assert_eq!(
10106 project.active_entry(),
10107 project
10108 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10109 .map(|e| e.id)
10110 );
10111 });
10112
10113 // Add a project folder
10114 project
10115 .update(cx, |project, cx| {
10116 project.find_or_create_worktree("root2", true, cx)
10117 })
10118 .await
10119 .unwrap();
10120 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10121
10122 // Remove a project folder
10123 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10124 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10125 }
10126
10127 #[gpui::test]
10128 async fn test_close_window(cx: &mut TestAppContext) {
10129 init_test(cx);
10130
10131 let fs = FakeFs::new(cx.executor());
10132 fs.insert_tree("/root", json!({ "one": "" })).await;
10133
10134 let project = Project::test(fs, ["root".as_ref()], cx).await;
10135 let (workspace, cx) =
10136 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10137
10138 // When there are no dirty items, there's nothing to do.
10139 let item1 = cx.new(TestItem::new);
10140 workspace.update_in(cx, |w, window, cx| {
10141 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10142 });
10143 let task = workspace.update_in(cx, |w, window, cx| {
10144 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10145 });
10146 assert!(task.await.unwrap());
10147
10148 // When there are dirty untitled items, prompt to save each one. If the user
10149 // cancels any prompt, then abort.
10150 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10151 let item3 = cx.new(|cx| {
10152 TestItem::new(cx)
10153 .with_dirty(true)
10154 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10155 });
10156 workspace.update_in(cx, |w, window, cx| {
10157 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10158 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10159 });
10160 let task = workspace.update_in(cx, |w, window, cx| {
10161 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10162 });
10163 cx.executor().run_until_parked();
10164 cx.simulate_prompt_answer("Cancel"); // cancel save all
10165 cx.executor().run_until_parked();
10166 assert!(!cx.has_pending_prompt());
10167 assert!(!task.await.unwrap());
10168 }
10169
10170 #[gpui::test]
10171 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10172 init_test(cx);
10173
10174 let fs = FakeFs::new(cx.executor());
10175 fs.insert_tree("/root", json!({ "one": "" })).await;
10176
10177 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10178 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10179 let multi_workspace_handle =
10180 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10181 cx.run_until_parked();
10182
10183 let workspace_a = multi_workspace_handle
10184 .read_with(cx, |mw, _| mw.workspace().clone())
10185 .unwrap();
10186
10187 let workspace_b = multi_workspace_handle
10188 .update(cx, |mw, window, cx| {
10189 mw.test_add_workspace(project_b, window, cx)
10190 })
10191 .unwrap();
10192
10193 // Activate workspace A
10194 multi_workspace_handle
10195 .update(cx, |mw, window, cx| {
10196 mw.activate_index(0, window, cx);
10197 })
10198 .unwrap();
10199
10200 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10201
10202 // Workspace A has a clean item
10203 let item_a = cx.new(TestItem::new);
10204 workspace_a.update_in(cx, |w, window, cx| {
10205 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10206 });
10207
10208 // Workspace B has a dirty item
10209 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10210 workspace_b.update_in(cx, |w, window, cx| {
10211 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10212 });
10213
10214 // Verify workspace A is active
10215 multi_workspace_handle
10216 .read_with(cx, |mw, _| {
10217 assert_eq!(mw.active_workspace_index(), 0);
10218 })
10219 .unwrap();
10220
10221 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10222 multi_workspace_handle
10223 .update(cx, |mw, window, cx| {
10224 mw.close_window(&CloseWindow, window, cx);
10225 })
10226 .unwrap();
10227 cx.run_until_parked();
10228
10229 // Workspace B should now be active since it has dirty items that need attention
10230 multi_workspace_handle
10231 .read_with(cx, |mw, _| {
10232 assert_eq!(
10233 mw.active_workspace_index(),
10234 1,
10235 "workspace B should be activated when it prompts"
10236 );
10237 })
10238 .unwrap();
10239
10240 // User cancels the save prompt from workspace B
10241 cx.simulate_prompt_answer("Cancel");
10242 cx.run_until_parked();
10243
10244 // Window should still exist because workspace B's close was cancelled
10245 assert!(
10246 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10247 "window should still exist after cancelling one workspace's close"
10248 );
10249 }
10250
10251 #[gpui::test]
10252 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10253 init_test(cx);
10254
10255 // Register TestItem as a serializable item
10256 cx.update(|cx| {
10257 register_serializable_item::<TestItem>(cx);
10258 });
10259
10260 let fs = FakeFs::new(cx.executor());
10261 fs.insert_tree("/root", json!({ "one": "" })).await;
10262
10263 let project = Project::test(fs, ["root".as_ref()], cx).await;
10264 let (workspace, cx) =
10265 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10266
10267 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10268 let item1 = cx.new(|cx| {
10269 TestItem::new(cx)
10270 .with_dirty(true)
10271 .with_serialize(|| Some(Task::ready(Ok(()))))
10272 });
10273 let item2 = cx.new(|cx| {
10274 TestItem::new(cx)
10275 .with_dirty(true)
10276 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10277 .with_serialize(|| Some(Task::ready(Ok(()))))
10278 });
10279 workspace.update_in(cx, |w, window, cx| {
10280 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10281 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10282 });
10283 let task = workspace.update_in(cx, |w, window, cx| {
10284 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10285 });
10286 assert!(task.await.unwrap());
10287 }
10288
10289 #[gpui::test]
10290 async fn test_close_pane_items(cx: &mut TestAppContext) {
10291 init_test(cx);
10292
10293 let fs = FakeFs::new(cx.executor());
10294
10295 let project = Project::test(fs, None, cx).await;
10296 let (workspace, cx) =
10297 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10298
10299 let item1 = cx.new(|cx| {
10300 TestItem::new(cx)
10301 .with_dirty(true)
10302 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10303 });
10304 let item2 = cx.new(|cx| {
10305 TestItem::new(cx)
10306 .with_dirty(true)
10307 .with_conflict(true)
10308 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10309 });
10310 let item3 = cx.new(|cx| {
10311 TestItem::new(cx)
10312 .with_dirty(true)
10313 .with_conflict(true)
10314 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10315 });
10316 let item4 = cx.new(|cx| {
10317 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10318 let project_item = TestProjectItem::new_untitled(cx);
10319 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10320 project_item
10321 }])
10322 });
10323 let pane = workspace.update_in(cx, |workspace, window, cx| {
10324 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10325 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10326 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10327 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10328 workspace.active_pane().clone()
10329 });
10330
10331 let close_items = pane.update_in(cx, |pane, window, cx| {
10332 pane.activate_item(1, true, true, window, cx);
10333 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10334 let item1_id = item1.item_id();
10335 let item3_id = item3.item_id();
10336 let item4_id = item4.item_id();
10337 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10338 [item1_id, item3_id, item4_id].contains(&id)
10339 })
10340 });
10341 cx.executor().run_until_parked();
10342
10343 assert!(cx.has_pending_prompt());
10344 cx.simulate_prompt_answer("Save all");
10345
10346 cx.executor().run_until_parked();
10347
10348 // Item 1 is saved. There's a prompt to save item 3.
10349 pane.update(cx, |pane, cx| {
10350 assert_eq!(item1.read(cx).save_count, 1);
10351 assert_eq!(item1.read(cx).save_as_count, 0);
10352 assert_eq!(item1.read(cx).reload_count, 0);
10353 assert_eq!(pane.items_len(), 3);
10354 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10355 });
10356 assert!(cx.has_pending_prompt());
10357
10358 // Cancel saving item 3.
10359 cx.simulate_prompt_answer("Discard");
10360 cx.executor().run_until_parked();
10361
10362 // Item 3 is reloaded. There's a prompt to save item 4.
10363 pane.update(cx, |pane, cx| {
10364 assert_eq!(item3.read(cx).save_count, 0);
10365 assert_eq!(item3.read(cx).save_as_count, 0);
10366 assert_eq!(item3.read(cx).reload_count, 1);
10367 assert_eq!(pane.items_len(), 2);
10368 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10369 });
10370
10371 // There's a prompt for a path for item 4.
10372 cx.simulate_new_path_selection(|_| Some(Default::default()));
10373 close_items.await.unwrap();
10374
10375 // The requested items are closed.
10376 pane.update(cx, |pane, cx| {
10377 assert_eq!(item4.read(cx).save_count, 0);
10378 assert_eq!(item4.read(cx).save_as_count, 1);
10379 assert_eq!(item4.read(cx).reload_count, 0);
10380 assert_eq!(pane.items_len(), 1);
10381 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10382 });
10383 }
10384
10385 #[gpui::test]
10386 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10387 init_test(cx);
10388
10389 let fs = FakeFs::new(cx.executor());
10390 let project = Project::test(fs, [], cx).await;
10391 let (workspace, cx) =
10392 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10393
10394 // Create several workspace items with single project entries, and two
10395 // workspace items with multiple project entries.
10396 let single_entry_items = (0..=4)
10397 .map(|project_entry_id| {
10398 cx.new(|cx| {
10399 TestItem::new(cx)
10400 .with_dirty(true)
10401 .with_project_items(&[dirty_project_item(
10402 project_entry_id,
10403 &format!("{project_entry_id}.txt"),
10404 cx,
10405 )])
10406 })
10407 })
10408 .collect::<Vec<_>>();
10409 let item_2_3 = cx.new(|cx| {
10410 TestItem::new(cx)
10411 .with_dirty(true)
10412 .with_buffer_kind(ItemBufferKind::Multibuffer)
10413 .with_project_items(&[
10414 single_entry_items[2].read(cx).project_items[0].clone(),
10415 single_entry_items[3].read(cx).project_items[0].clone(),
10416 ])
10417 });
10418 let item_3_4 = cx.new(|cx| {
10419 TestItem::new(cx)
10420 .with_dirty(true)
10421 .with_buffer_kind(ItemBufferKind::Multibuffer)
10422 .with_project_items(&[
10423 single_entry_items[3].read(cx).project_items[0].clone(),
10424 single_entry_items[4].read(cx).project_items[0].clone(),
10425 ])
10426 });
10427
10428 // Create two panes that contain the following project entries:
10429 // left pane:
10430 // multi-entry items: (2, 3)
10431 // single-entry items: 0, 2, 3, 4
10432 // right pane:
10433 // single-entry items: 4, 1
10434 // multi-entry items: (3, 4)
10435 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10436 let left_pane = workspace.active_pane().clone();
10437 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10438 workspace.add_item_to_active_pane(
10439 single_entry_items[0].boxed_clone(),
10440 None,
10441 true,
10442 window,
10443 cx,
10444 );
10445 workspace.add_item_to_active_pane(
10446 single_entry_items[2].boxed_clone(),
10447 None,
10448 true,
10449 window,
10450 cx,
10451 );
10452 workspace.add_item_to_active_pane(
10453 single_entry_items[3].boxed_clone(),
10454 None,
10455 true,
10456 window,
10457 cx,
10458 );
10459 workspace.add_item_to_active_pane(
10460 single_entry_items[4].boxed_clone(),
10461 None,
10462 true,
10463 window,
10464 cx,
10465 );
10466
10467 let right_pane =
10468 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10469
10470 let boxed_clone = single_entry_items[1].boxed_clone();
10471 let right_pane = window.spawn(cx, async move |cx| {
10472 right_pane.await.inspect(|right_pane| {
10473 right_pane
10474 .update_in(cx, |pane, window, cx| {
10475 pane.add_item(boxed_clone, true, true, None, window, cx);
10476 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10477 })
10478 .unwrap();
10479 })
10480 });
10481
10482 (left_pane, right_pane)
10483 });
10484 let right_pane = right_pane.await.unwrap();
10485 cx.focus(&right_pane);
10486
10487 let close = right_pane.update_in(cx, |pane, window, cx| {
10488 pane.close_all_items(&CloseAllItems::default(), window, cx)
10489 .unwrap()
10490 });
10491 cx.executor().run_until_parked();
10492
10493 let msg = cx.pending_prompt().unwrap().0;
10494 assert!(msg.contains("1.txt"));
10495 assert!(!msg.contains("2.txt"));
10496 assert!(!msg.contains("3.txt"));
10497 assert!(!msg.contains("4.txt"));
10498
10499 // With best-effort close, cancelling item 1 keeps it open but items 4
10500 // and (3,4) still close since their entries exist in left pane.
10501 cx.simulate_prompt_answer("Cancel");
10502 close.await;
10503
10504 right_pane.read_with(cx, |pane, _| {
10505 assert_eq!(pane.items_len(), 1);
10506 });
10507
10508 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10509 left_pane
10510 .update_in(cx, |left_pane, window, cx| {
10511 left_pane.close_item_by_id(
10512 single_entry_items[3].entity_id(),
10513 SaveIntent::Skip,
10514 window,
10515 cx,
10516 )
10517 })
10518 .await
10519 .unwrap();
10520
10521 let close = left_pane.update_in(cx, |pane, window, cx| {
10522 pane.close_all_items(&CloseAllItems::default(), window, cx)
10523 .unwrap()
10524 });
10525 cx.executor().run_until_parked();
10526
10527 let details = cx.pending_prompt().unwrap().1;
10528 assert!(details.contains("0.txt"));
10529 assert!(details.contains("3.txt"));
10530 assert!(details.contains("4.txt"));
10531 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10532 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10533 // assert!(!details.contains("2.txt"));
10534
10535 cx.simulate_prompt_answer("Save all");
10536 cx.executor().run_until_parked();
10537 close.await;
10538
10539 left_pane.read_with(cx, |pane, _| {
10540 assert_eq!(pane.items_len(), 0);
10541 });
10542 }
10543
10544 #[gpui::test]
10545 async fn test_autosave(cx: &mut gpui::TestAppContext) {
10546 init_test(cx);
10547
10548 let fs = FakeFs::new(cx.executor());
10549 let project = Project::test(fs, [], cx).await;
10550 let (workspace, cx) =
10551 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10552 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10553
10554 let item = cx.new(|cx| {
10555 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10556 });
10557 let item_id = item.entity_id();
10558 workspace.update_in(cx, |workspace, window, cx| {
10559 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10560 });
10561
10562 // Autosave on window change.
10563 item.update(cx, |item, cx| {
10564 SettingsStore::update_global(cx, |settings, cx| {
10565 settings.update_user_settings(cx, |settings| {
10566 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10567 })
10568 });
10569 item.is_dirty = true;
10570 });
10571
10572 // Deactivating the window saves the file.
10573 cx.deactivate_window();
10574 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10575
10576 // Re-activating the window doesn't save the file.
10577 cx.update(|window, _| window.activate_window());
10578 cx.executor().run_until_parked();
10579 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10580
10581 // Autosave on focus change.
10582 item.update_in(cx, |item, window, cx| {
10583 cx.focus_self(window);
10584 SettingsStore::update_global(cx, |settings, cx| {
10585 settings.update_user_settings(cx, |settings| {
10586 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10587 })
10588 });
10589 item.is_dirty = true;
10590 });
10591 // Blurring the item saves the file.
10592 item.update_in(cx, |_, window, _| window.blur());
10593 cx.executor().run_until_parked();
10594 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10595
10596 // Deactivating the window still saves the file.
10597 item.update_in(cx, |item, window, cx| {
10598 cx.focus_self(window);
10599 item.is_dirty = true;
10600 });
10601 cx.deactivate_window();
10602 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10603
10604 // Autosave after delay.
10605 item.update(cx, |item, cx| {
10606 SettingsStore::update_global(cx, |settings, cx| {
10607 settings.update_user_settings(cx, |settings| {
10608 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10609 milliseconds: 500.into(),
10610 });
10611 })
10612 });
10613 item.is_dirty = true;
10614 cx.emit(ItemEvent::Edit);
10615 });
10616
10617 // Delay hasn't fully expired, so the file is still dirty and unsaved.
10618 cx.executor().advance_clock(Duration::from_millis(250));
10619 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10620
10621 // After delay expires, the file is saved.
10622 cx.executor().advance_clock(Duration::from_millis(250));
10623 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10624
10625 // Autosave after delay, should save earlier than delay if tab is closed
10626 item.update(cx, |item, cx| {
10627 item.is_dirty = true;
10628 cx.emit(ItemEvent::Edit);
10629 });
10630 cx.executor().advance_clock(Duration::from_millis(250));
10631 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10632
10633 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10634 pane.update_in(cx, |pane, window, cx| {
10635 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10636 })
10637 .await
10638 .unwrap();
10639 assert!(!cx.has_pending_prompt());
10640 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10641
10642 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10643 workspace.update_in(cx, |workspace, window, cx| {
10644 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10645 });
10646 item.update_in(cx, |item, _window, cx| {
10647 item.is_dirty = true;
10648 for project_item in &mut item.project_items {
10649 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10650 }
10651 });
10652 cx.run_until_parked();
10653 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10654
10655 // Autosave on focus change, ensuring closing the tab counts as such.
10656 item.update(cx, |item, cx| {
10657 SettingsStore::update_global(cx, |settings, cx| {
10658 settings.update_user_settings(cx, |settings| {
10659 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10660 })
10661 });
10662 item.is_dirty = true;
10663 for project_item in &mut item.project_items {
10664 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10665 }
10666 });
10667
10668 pane.update_in(cx, |pane, window, cx| {
10669 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10670 })
10671 .await
10672 .unwrap();
10673 assert!(!cx.has_pending_prompt());
10674 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10675
10676 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10677 workspace.update_in(cx, |workspace, window, cx| {
10678 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10679 });
10680 item.update_in(cx, |item, window, cx| {
10681 item.project_items[0].update(cx, |item, _| {
10682 item.entry_id = None;
10683 });
10684 item.is_dirty = true;
10685 window.blur();
10686 });
10687 cx.run_until_parked();
10688 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10689
10690 // Ensure autosave is prevented for deleted files also when closing the buffer.
10691 let _close_items = pane.update_in(cx, |pane, window, cx| {
10692 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10693 });
10694 cx.run_until_parked();
10695 assert!(cx.has_pending_prompt());
10696 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10697 }
10698
10699 #[gpui::test]
10700 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
10701 init_test(cx);
10702
10703 let fs = FakeFs::new(cx.executor());
10704 let project = Project::test(fs, [], cx).await;
10705 let (workspace, cx) =
10706 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10707
10708 // Create a multibuffer-like item with two child focus handles,
10709 // simulating individual buffer editors within a multibuffer.
10710 let item = cx.new(|cx| {
10711 TestItem::new(cx)
10712 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10713 .with_child_focus_handles(2, cx)
10714 });
10715 workspace.update_in(cx, |workspace, window, cx| {
10716 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10717 });
10718
10719 // Set autosave to OnFocusChange and focus the first child handle,
10720 // simulating the user's cursor being inside one of the multibuffer's excerpts.
10721 item.update_in(cx, |item, window, cx| {
10722 SettingsStore::update_global(cx, |settings, cx| {
10723 settings.update_user_settings(cx, |settings| {
10724 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10725 })
10726 });
10727 item.is_dirty = true;
10728 window.focus(&item.child_focus_handles[0], cx);
10729 });
10730 cx.executor().run_until_parked();
10731 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
10732
10733 // Moving focus from one child to another within the same item should
10734 // NOT trigger autosave — focus is still within the item's focus hierarchy.
10735 item.update_in(cx, |item, window, cx| {
10736 window.focus(&item.child_focus_handles[1], cx);
10737 });
10738 cx.executor().run_until_parked();
10739 item.read_with(cx, |item, _| {
10740 assert_eq!(
10741 item.save_count, 0,
10742 "Switching focus between children within the same item should not autosave"
10743 );
10744 });
10745
10746 // Blurring the item saves the file. This is the core regression scenario:
10747 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
10748 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
10749 // the leaf is always a child focus handle, so `on_blur` never detected
10750 // focus leaving the item.
10751 item.update_in(cx, |_, window, _| window.blur());
10752 cx.executor().run_until_parked();
10753 item.read_with(cx, |item, _| {
10754 assert_eq!(
10755 item.save_count, 1,
10756 "Blurring should trigger autosave when focus was on a child of the item"
10757 );
10758 });
10759
10760 // Deactivating the window should also trigger autosave when a child of
10761 // the multibuffer item currently owns focus.
10762 item.update_in(cx, |item, window, cx| {
10763 item.is_dirty = true;
10764 window.focus(&item.child_focus_handles[0], cx);
10765 });
10766 cx.executor().run_until_parked();
10767 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10768
10769 cx.deactivate_window();
10770 item.read_with(cx, |item, _| {
10771 assert_eq!(
10772 item.save_count, 2,
10773 "Deactivating window should trigger autosave when focus was on a child"
10774 );
10775 });
10776 }
10777
10778 #[gpui::test]
10779 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10780 init_test(cx);
10781
10782 let fs = FakeFs::new(cx.executor());
10783
10784 let project = Project::test(fs, [], cx).await;
10785 let (workspace, cx) =
10786 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10787
10788 let item = cx.new(|cx| {
10789 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10790 });
10791 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10792 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10793 let toolbar_notify_count = Rc::new(RefCell::new(0));
10794
10795 workspace.update_in(cx, |workspace, window, cx| {
10796 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10797 let toolbar_notification_count = toolbar_notify_count.clone();
10798 cx.observe_in(&toolbar, window, move |_, _, _, _| {
10799 *toolbar_notification_count.borrow_mut() += 1
10800 })
10801 .detach();
10802 });
10803
10804 pane.read_with(cx, |pane, _| {
10805 assert!(!pane.can_navigate_backward());
10806 assert!(!pane.can_navigate_forward());
10807 });
10808
10809 item.update_in(cx, |item, _, cx| {
10810 item.set_state("one".to_string(), cx);
10811 });
10812
10813 // Toolbar must be notified to re-render the navigation buttons
10814 assert_eq!(*toolbar_notify_count.borrow(), 1);
10815
10816 pane.read_with(cx, |pane, _| {
10817 assert!(pane.can_navigate_backward());
10818 assert!(!pane.can_navigate_forward());
10819 });
10820
10821 workspace
10822 .update_in(cx, |workspace, window, cx| {
10823 workspace.go_back(pane.downgrade(), window, cx)
10824 })
10825 .await
10826 .unwrap();
10827
10828 assert_eq!(*toolbar_notify_count.borrow(), 2);
10829 pane.read_with(cx, |pane, _| {
10830 assert!(!pane.can_navigate_backward());
10831 assert!(pane.can_navigate_forward());
10832 });
10833 }
10834
10835 #[gpui::test]
10836 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
10837 init_test(cx);
10838 let fs = FakeFs::new(cx.executor());
10839 let project = Project::test(fs, [], cx).await;
10840 let (multi_workspace, cx) =
10841 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
10842 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
10843
10844 workspace.update_in(cx, |workspace, window, cx| {
10845 let first_item = cx.new(|cx| {
10846 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10847 });
10848 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
10849 workspace.split_pane(
10850 workspace.active_pane().clone(),
10851 SplitDirection::Right,
10852 window,
10853 cx,
10854 );
10855 workspace.split_pane(
10856 workspace.active_pane().clone(),
10857 SplitDirection::Right,
10858 window,
10859 cx,
10860 );
10861 });
10862
10863 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
10864 let panes = workspace.center.panes();
10865 assert!(panes.len() >= 2);
10866 (
10867 panes.first().expect("at least one pane").entity_id(),
10868 panes.last().expect("at least one pane").entity_id(),
10869 )
10870 });
10871
10872 workspace.update_in(cx, |workspace, window, cx| {
10873 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
10874 });
10875 workspace.update(cx, |workspace, _| {
10876 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
10877 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
10878 });
10879
10880 cx.dispatch_action(ActivateLastPane);
10881
10882 workspace.update(cx, |workspace, _| {
10883 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
10884 });
10885 }
10886
10887 #[gpui::test]
10888 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
10889 init_test(cx);
10890 let fs = FakeFs::new(cx.executor());
10891
10892 let project = Project::test(fs, [], cx).await;
10893 let (workspace, cx) =
10894 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10895
10896 let panel = workspace.update_in(cx, |workspace, window, cx| {
10897 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10898 workspace.add_panel(panel.clone(), window, cx);
10899
10900 workspace
10901 .right_dock()
10902 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10903
10904 panel
10905 });
10906
10907 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10908 pane.update_in(cx, |pane, window, cx| {
10909 let item = cx.new(TestItem::new);
10910 pane.add_item(Box::new(item), true, true, None, window, cx);
10911 });
10912
10913 // Transfer focus from center to panel
10914 workspace.update_in(cx, |workspace, window, cx| {
10915 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10916 });
10917
10918 workspace.update_in(cx, |workspace, window, cx| {
10919 assert!(workspace.right_dock().read(cx).is_open());
10920 assert!(!panel.is_zoomed(window, cx));
10921 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10922 });
10923
10924 // Transfer focus from panel to center
10925 workspace.update_in(cx, |workspace, window, cx| {
10926 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10927 });
10928
10929 workspace.update_in(cx, |workspace, window, cx| {
10930 assert!(workspace.right_dock().read(cx).is_open());
10931 assert!(!panel.is_zoomed(window, cx));
10932 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10933 });
10934
10935 // Close the dock
10936 workspace.update_in(cx, |workspace, window, cx| {
10937 workspace.toggle_dock(DockPosition::Right, window, cx);
10938 });
10939
10940 workspace.update_in(cx, |workspace, window, cx| {
10941 assert!(!workspace.right_dock().read(cx).is_open());
10942 assert!(!panel.is_zoomed(window, cx));
10943 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10944 });
10945
10946 // Open the dock
10947 workspace.update_in(cx, |workspace, window, cx| {
10948 workspace.toggle_dock(DockPosition::Right, window, cx);
10949 });
10950
10951 workspace.update_in(cx, |workspace, window, cx| {
10952 assert!(workspace.right_dock().read(cx).is_open());
10953 assert!(!panel.is_zoomed(window, cx));
10954 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10955 });
10956
10957 // Focus and zoom panel
10958 panel.update_in(cx, |panel, window, cx| {
10959 cx.focus_self(window);
10960 panel.set_zoomed(true, window, cx)
10961 });
10962
10963 workspace.update_in(cx, |workspace, window, cx| {
10964 assert!(workspace.right_dock().read(cx).is_open());
10965 assert!(panel.is_zoomed(window, cx));
10966 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10967 });
10968
10969 // Transfer focus to the center closes the dock
10970 workspace.update_in(cx, |workspace, window, cx| {
10971 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10972 });
10973
10974 workspace.update_in(cx, |workspace, window, cx| {
10975 assert!(!workspace.right_dock().read(cx).is_open());
10976 assert!(panel.is_zoomed(window, cx));
10977 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10978 });
10979
10980 // Transferring focus back to the panel keeps it zoomed
10981 workspace.update_in(cx, |workspace, window, cx| {
10982 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10983 });
10984
10985 workspace.update_in(cx, |workspace, window, cx| {
10986 assert!(workspace.right_dock().read(cx).is_open());
10987 assert!(panel.is_zoomed(window, cx));
10988 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10989 });
10990
10991 // Close the dock while it is zoomed
10992 workspace.update_in(cx, |workspace, window, cx| {
10993 workspace.toggle_dock(DockPosition::Right, window, cx)
10994 });
10995
10996 workspace.update_in(cx, |workspace, window, cx| {
10997 assert!(!workspace.right_dock().read(cx).is_open());
10998 assert!(panel.is_zoomed(window, cx));
10999 assert!(workspace.zoomed.is_none());
11000 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11001 });
11002
11003 // Opening the dock, when it's zoomed, retains focus
11004 workspace.update_in(cx, |workspace, window, cx| {
11005 workspace.toggle_dock(DockPosition::Right, window, cx)
11006 });
11007
11008 workspace.update_in(cx, |workspace, window, cx| {
11009 assert!(workspace.right_dock().read(cx).is_open());
11010 assert!(panel.is_zoomed(window, cx));
11011 assert!(workspace.zoomed.is_some());
11012 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11013 });
11014
11015 // Unzoom and close the panel, zoom the active pane.
11016 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11017 workspace.update_in(cx, |workspace, window, cx| {
11018 workspace.toggle_dock(DockPosition::Right, window, cx)
11019 });
11020 pane.update_in(cx, |pane, window, cx| {
11021 pane.toggle_zoom(&Default::default(), window, cx)
11022 });
11023
11024 // Opening a dock unzooms the pane.
11025 workspace.update_in(cx, |workspace, window, cx| {
11026 workspace.toggle_dock(DockPosition::Right, window, cx)
11027 });
11028 workspace.update_in(cx, |workspace, window, cx| {
11029 let pane = pane.read(cx);
11030 assert!(!pane.is_zoomed());
11031 assert!(!pane.focus_handle(cx).is_focused(window));
11032 assert!(workspace.right_dock().read(cx).is_open());
11033 assert!(workspace.zoomed.is_none());
11034 });
11035 }
11036
11037 #[gpui::test]
11038 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11039 init_test(cx);
11040 let fs = FakeFs::new(cx.executor());
11041
11042 let project = Project::test(fs, [], cx).await;
11043 let (workspace, cx) =
11044 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11045
11046 let panel = workspace.update_in(cx, |workspace, window, cx| {
11047 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11048 workspace.add_panel(panel.clone(), window, cx);
11049 panel
11050 });
11051
11052 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11053 pane.update_in(cx, |pane, window, cx| {
11054 let item = cx.new(TestItem::new);
11055 pane.add_item(Box::new(item), true, true, None, window, cx);
11056 });
11057
11058 // Enable close_panel_on_toggle
11059 cx.update_global(|store: &mut SettingsStore, cx| {
11060 store.update_user_settings(cx, |settings| {
11061 settings.workspace.close_panel_on_toggle = Some(true);
11062 });
11063 });
11064
11065 // Panel starts closed. Toggling should open and focus it.
11066 workspace.update_in(cx, |workspace, window, cx| {
11067 assert!(!workspace.right_dock().read(cx).is_open());
11068 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11069 });
11070
11071 workspace.update_in(cx, |workspace, window, cx| {
11072 assert!(
11073 workspace.right_dock().read(cx).is_open(),
11074 "Dock should be open after toggling from center"
11075 );
11076 assert!(
11077 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11078 "Panel should be focused after toggling from center"
11079 );
11080 });
11081
11082 // Panel is open and focused. Toggling should close the panel and
11083 // return focus to the center.
11084 workspace.update_in(cx, |workspace, window, cx| {
11085 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11086 });
11087
11088 workspace.update_in(cx, |workspace, window, cx| {
11089 assert!(
11090 !workspace.right_dock().read(cx).is_open(),
11091 "Dock should be closed after toggling from focused panel"
11092 );
11093 assert!(
11094 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11095 "Panel should not be focused after toggling from focused panel"
11096 );
11097 });
11098
11099 // Open the dock and focus something else so the panel is open but not
11100 // focused. Toggling should focus the panel (not close it).
11101 workspace.update_in(cx, |workspace, window, cx| {
11102 workspace
11103 .right_dock()
11104 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11105 window.focus(&pane.read(cx).focus_handle(cx), cx);
11106 });
11107
11108 workspace.update_in(cx, |workspace, window, cx| {
11109 assert!(workspace.right_dock().read(cx).is_open());
11110 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11111 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11112 });
11113
11114 workspace.update_in(cx, |workspace, window, cx| {
11115 assert!(
11116 workspace.right_dock().read(cx).is_open(),
11117 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11118 );
11119 assert!(
11120 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11121 "Panel should be focused after toggling an open-but-unfocused panel"
11122 );
11123 });
11124
11125 // Now disable the setting and verify the original behavior: toggling
11126 // from a focused panel moves focus to center but leaves the dock open.
11127 cx.update_global(|store: &mut SettingsStore, cx| {
11128 store.update_user_settings(cx, |settings| {
11129 settings.workspace.close_panel_on_toggle = Some(false);
11130 });
11131 });
11132
11133 workspace.update_in(cx, |workspace, window, cx| {
11134 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11135 });
11136
11137 workspace.update_in(cx, |workspace, window, cx| {
11138 assert!(
11139 workspace.right_dock().read(cx).is_open(),
11140 "Dock should remain open when setting is disabled"
11141 );
11142 assert!(
11143 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11144 "Panel should not be focused after toggling with setting disabled"
11145 );
11146 });
11147 }
11148
11149 #[gpui::test]
11150 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11151 init_test(cx);
11152 let fs = FakeFs::new(cx.executor());
11153
11154 let project = Project::test(fs, [], cx).await;
11155 let (workspace, cx) =
11156 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11157
11158 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11159 workspace.active_pane().clone()
11160 });
11161
11162 // Add an item to the pane so it can be zoomed
11163 workspace.update_in(cx, |workspace, window, cx| {
11164 let item = cx.new(TestItem::new);
11165 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11166 });
11167
11168 // Initially not zoomed
11169 workspace.update_in(cx, |workspace, _window, cx| {
11170 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11171 assert!(
11172 workspace.zoomed.is_none(),
11173 "Workspace should track no zoomed pane"
11174 );
11175 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11176 });
11177
11178 // Zoom In
11179 pane.update_in(cx, |pane, window, cx| {
11180 pane.zoom_in(&crate::ZoomIn, window, cx);
11181 });
11182
11183 workspace.update_in(cx, |workspace, window, cx| {
11184 assert!(
11185 pane.read(cx).is_zoomed(),
11186 "Pane should be zoomed after ZoomIn"
11187 );
11188 assert!(
11189 workspace.zoomed.is_some(),
11190 "Workspace should track the zoomed pane"
11191 );
11192 assert!(
11193 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11194 "ZoomIn should focus the pane"
11195 );
11196 });
11197
11198 // Zoom In again is a no-op
11199 pane.update_in(cx, |pane, window, cx| {
11200 pane.zoom_in(&crate::ZoomIn, window, cx);
11201 });
11202
11203 workspace.update_in(cx, |workspace, window, cx| {
11204 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11205 assert!(
11206 workspace.zoomed.is_some(),
11207 "Workspace still tracks zoomed pane"
11208 );
11209 assert!(
11210 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11211 "Pane remains focused after repeated ZoomIn"
11212 );
11213 });
11214
11215 // Zoom Out
11216 pane.update_in(cx, |pane, window, cx| {
11217 pane.zoom_out(&crate::ZoomOut, window, cx);
11218 });
11219
11220 workspace.update_in(cx, |workspace, _window, cx| {
11221 assert!(
11222 !pane.read(cx).is_zoomed(),
11223 "Pane should unzoom after ZoomOut"
11224 );
11225 assert!(
11226 workspace.zoomed.is_none(),
11227 "Workspace clears zoom tracking after ZoomOut"
11228 );
11229 });
11230
11231 // Zoom Out again is a no-op
11232 pane.update_in(cx, |pane, window, cx| {
11233 pane.zoom_out(&crate::ZoomOut, window, cx);
11234 });
11235
11236 workspace.update_in(cx, |workspace, _window, cx| {
11237 assert!(
11238 !pane.read(cx).is_zoomed(),
11239 "Second ZoomOut keeps pane unzoomed"
11240 );
11241 assert!(
11242 workspace.zoomed.is_none(),
11243 "Workspace remains without zoomed pane"
11244 );
11245 });
11246 }
11247
11248 #[gpui::test]
11249 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11250 init_test(cx);
11251 let fs = FakeFs::new(cx.executor());
11252
11253 let project = Project::test(fs, [], cx).await;
11254 let (workspace, cx) =
11255 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11256 workspace.update_in(cx, |workspace, window, cx| {
11257 // Open two docks
11258 let left_dock = workspace.dock_at_position(DockPosition::Left);
11259 let right_dock = workspace.dock_at_position(DockPosition::Right);
11260
11261 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11262 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11263
11264 assert!(left_dock.read(cx).is_open());
11265 assert!(right_dock.read(cx).is_open());
11266 });
11267
11268 workspace.update_in(cx, |workspace, window, cx| {
11269 // Toggle all docks - should close both
11270 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11271
11272 let left_dock = workspace.dock_at_position(DockPosition::Left);
11273 let right_dock = workspace.dock_at_position(DockPosition::Right);
11274 assert!(!left_dock.read(cx).is_open());
11275 assert!(!right_dock.read(cx).is_open());
11276 });
11277
11278 workspace.update_in(cx, |workspace, window, cx| {
11279 // Toggle again - should reopen both
11280 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11281
11282 let left_dock = workspace.dock_at_position(DockPosition::Left);
11283 let right_dock = workspace.dock_at_position(DockPosition::Right);
11284 assert!(left_dock.read(cx).is_open());
11285 assert!(right_dock.read(cx).is_open());
11286 });
11287 }
11288
11289 #[gpui::test]
11290 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11291 init_test(cx);
11292 let fs = FakeFs::new(cx.executor());
11293
11294 let project = Project::test(fs, [], cx).await;
11295 let (workspace, cx) =
11296 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11297 workspace.update_in(cx, |workspace, window, cx| {
11298 // Open two docks
11299 let left_dock = workspace.dock_at_position(DockPosition::Left);
11300 let right_dock = workspace.dock_at_position(DockPosition::Right);
11301
11302 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11303 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11304
11305 assert!(left_dock.read(cx).is_open());
11306 assert!(right_dock.read(cx).is_open());
11307 });
11308
11309 workspace.update_in(cx, |workspace, window, cx| {
11310 // Close them manually
11311 workspace.toggle_dock(DockPosition::Left, window, cx);
11312 workspace.toggle_dock(DockPosition::Right, window, cx);
11313
11314 let left_dock = workspace.dock_at_position(DockPosition::Left);
11315 let right_dock = workspace.dock_at_position(DockPosition::Right);
11316 assert!(!left_dock.read(cx).is_open());
11317 assert!(!right_dock.read(cx).is_open());
11318 });
11319
11320 workspace.update_in(cx, |workspace, window, cx| {
11321 // Toggle all docks - only last closed (right dock) should reopen
11322 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11323
11324 let left_dock = workspace.dock_at_position(DockPosition::Left);
11325 let right_dock = workspace.dock_at_position(DockPosition::Right);
11326 assert!(!left_dock.read(cx).is_open());
11327 assert!(right_dock.read(cx).is_open());
11328 });
11329 }
11330
11331 #[gpui::test]
11332 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11333 init_test(cx);
11334 let fs = FakeFs::new(cx.executor());
11335 let project = Project::test(fs, [], cx).await;
11336 let (multi_workspace, cx) =
11337 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11338 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11339
11340 // Open two docks (left and right) with one panel each
11341 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11342 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11343 workspace.add_panel(left_panel.clone(), window, cx);
11344
11345 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11346 workspace.add_panel(right_panel.clone(), window, cx);
11347
11348 workspace.toggle_dock(DockPosition::Left, window, cx);
11349 workspace.toggle_dock(DockPosition::Right, window, cx);
11350
11351 // Verify initial state
11352 assert!(
11353 workspace.left_dock().read(cx).is_open(),
11354 "Left dock should be open"
11355 );
11356 assert_eq!(
11357 workspace
11358 .left_dock()
11359 .read(cx)
11360 .visible_panel()
11361 .unwrap()
11362 .panel_id(),
11363 left_panel.panel_id(),
11364 "Left panel should be visible in left dock"
11365 );
11366 assert!(
11367 workspace.right_dock().read(cx).is_open(),
11368 "Right dock should be open"
11369 );
11370 assert_eq!(
11371 workspace
11372 .right_dock()
11373 .read(cx)
11374 .visible_panel()
11375 .unwrap()
11376 .panel_id(),
11377 right_panel.panel_id(),
11378 "Right panel should be visible in right dock"
11379 );
11380 assert!(
11381 !workspace.bottom_dock().read(cx).is_open(),
11382 "Bottom dock should be closed"
11383 );
11384
11385 (left_panel, right_panel)
11386 });
11387
11388 // Focus the left panel and move it to the next position (bottom dock)
11389 workspace.update_in(cx, |workspace, window, cx| {
11390 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11391 assert!(
11392 left_panel.read(cx).focus_handle(cx).is_focused(window),
11393 "Left panel should be focused"
11394 );
11395 });
11396
11397 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11398
11399 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11400 workspace.update(cx, |workspace, cx| {
11401 assert!(
11402 !workspace.left_dock().read(cx).is_open(),
11403 "Left dock should be closed"
11404 );
11405 assert!(
11406 workspace.bottom_dock().read(cx).is_open(),
11407 "Bottom dock should now be open"
11408 );
11409 assert_eq!(
11410 left_panel.read(cx).position,
11411 DockPosition::Bottom,
11412 "Left panel should now be in the bottom dock"
11413 );
11414 assert_eq!(
11415 workspace
11416 .bottom_dock()
11417 .read(cx)
11418 .visible_panel()
11419 .unwrap()
11420 .panel_id(),
11421 left_panel.panel_id(),
11422 "Left panel should be the visible panel in the bottom dock"
11423 );
11424 });
11425
11426 // Toggle all docks off
11427 workspace.update_in(cx, |workspace, window, cx| {
11428 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11429 assert!(
11430 !workspace.left_dock().read(cx).is_open(),
11431 "Left dock should be closed"
11432 );
11433 assert!(
11434 !workspace.right_dock().read(cx).is_open(),
11435 "Right dock should be closed"
11436 );
11437 assert!(
11438 !workspace.bottom_dock().read(cx).is_open(),
11439 "Bottom dock should be closed"
11440 );
11441 });
11442
11443 // Toggle all docks back on and verify positions are restored
11444 workspace.update_in(cx, |workspace, window, cx| {
11445 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11446 assert!(
11447 !workspace.left_dock().read(cx).is_open(),
11448 "Left dock should remain closed"
11449 );
11450 assert!(
11451 workspace.right_dock().read(cx).is_open(),
11452 "Right dock should remain open"
11453 );
11454 assert!(
11455 workspace.bottom_dock().read(cx).is_open(),
11456 "Bottom dock should remain open"
11457 );
11458 assert_eq!(
11459 left_panel.read(cx).position,
11460 DockPosition::Bottom,
11461 "Left panel should remain in the bottom dock"
11462 );
11463 assert_eq!(
11464 right_panel.read(cx).position,
11465 DockPosition::Right,
11466 "Right panel should remain in the right dock"
11467 );
11468 assert_eq!(
11469 workspace
11470 .bottom_dock()
11471 .read(cx)
11472 .visible_panel()
11473 .unwrap()
11474 .panel_id(),
11475 left_panel.panel_id(),
11476 "Left panel should be the visible panel in the right dock"
11477 );
11478 });
11479 }
11480
11481 #[gpui::test]
11482 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11483 init_test(cx);
11484
11485 let fs = FakeFs::new(cx.executor());
11486
11487 let project = Project::test(fs, None, cx).await;
11488 let (workspace, cx) =
11489 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11490
11491 // Let's arrange the panes like this:
11492 //
11493 // +-----------------------+
11494 // | top |
11495 // +------+--------+-------+
11496 // | left | center | right |
11497 // +------+--------+-------+
11498 // | bottom |
11499 // +-----------------------+
11500
11501 let top_item = cx.new(|cx| {
11502 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11503 });
11504 let bottom_item = cx.new(|cx| {
11505 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11506 });
11507 let left_item = cx.new(|cx| {
11508 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11509 });
11510 let right_item = cx.new(|cx| {
11511 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11512 });
11513 let center_item = cx.new(|cx| {
11514 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11515 });
11516
11517 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11518 let top_pane_id = workspace.active_pane().entity_id();
11519 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11520 workspace.split_pane(
11521 workspace.active_pane().clone(),
11522 SplitDirection::Down,
11523 window,
11524 cx,
11525 );
11526 top_pane_id
11527 });
11528 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11529 let bottom_pane_id = workspace.active_pane().entity_id();
11530 workspace.add_item_to_active_pane(
11531 Box::new(bottom_item.clone()),
11532 None,
11533 false,
11534 window,
11535 cx,
11536 );
11537 workspace.split_pane(
11538 workspace.active_pane().clone(),
11539 SplitDirection::Up,
11540 window,
11541 cx,
11542 );
11543 bottom_pane_id
11544 });
11545 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11546 let left_pane_id = workspace.active_pane().entity_id();
11547 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11548 workspace.split_pane(
11549 workspace.active_pane().clone(),
11550 SplitDirection::Right,
11551 window,
11552 cx,
11553 );
11554 left_pane_id
11555 });
11556 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11557 let right_pane_id = workspace.active_pane().entity_id();
11558 workspace.add_item_to_active_pane(
11559 Box::new(right_item.clone()),
11560 None,
11561 false,
11562 window,
11563 cx,
11564 );
11565 workspace.split_pane(
11566 workspace.active_pane().clone(),
11567 SplitDirection::Left,
11568 window,
11569 cx,
11570 );
11571 right_pane_id
11572 });
11573 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11574 let center_pane_id = workspace.active_pane().entity_id();
11575 workspace.add_item_to_active_pane(
11576 Box::new(center_item.clone()),
11577 None,
11578 false,
11579 window,
11580 cx,
11581 );
11582 center_pane_id
11583 });
11584 cx.executor().run_until_parked();
11585
11586 workspace.update_in(cx, |workspace, window, cx| {
11587 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11588
11589 // Join into next from center pane into right
11590 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11591 });
11592
11593 workspace.update_in(cx, |workspace, window, cx| {
11594 let active_pane = workspace.active_pane();
11595 assert_eq!(right_pane_id, active_pane.entity_id());
11596 assert_eq!(2, active_pane.read(cx).items_len());
11597 let item_ids_in_pane =
11598 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11599 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11600 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11601
11602 // Join into next from right pane into bottom
11603 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11604 });
11605
11606 workspace.update_in(cx, |workspace, window, cx| {
11607 let active_pane = workspace.active_pane();
11608 assert_eq!(bottom_pane_id, active_pane.entity_id());
11609 assert_eq!(3, active_pane.read(cx).items_len());
11610 let item_ids_in_pane =
11611 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11612 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11613 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11614 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11615
11616 // Join into next from bottom pane into left
11617 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11618 });
11619
11620 workspace.update_in(cx, |workspace, window, cx| {
11621 let active_pane = workspace.active_pane();
11622 assert_eq!(left_pane_id, active_pane.entity_id());
11623 assert_eq!(4, active_pane.read(cx).items_len());
11624 let item_ids_in_pane =
11625 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11626 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11627 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11628 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11629 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11630
11631 // Join into next from left pane into top
11632 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11633 });
11634
11635 workspace.update_in(cx, |workspace, window, cx| {
11636 let active_pane = workspace.active_pane();
11637 assert_eq!(top_pane_id, active_pane.entity_id());
11638 assert_eq!(5, active_pane.read(cx).items_len());
11639 let item_ids_in_pane =
11640 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11641 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11642 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11643 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11644 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11645 assert!(item_ids_in_pane.contains(&top_item.item_id()));
11646
11647 // Single pane left: no-op
11648 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11649 });
11650
11651 workspace.update(cx, |workspace, _cx| {
11652 let active_pane = workspace.active_pane();
11653 assert_eq!(top_pane_id, active_pane.entity_id());
11654 });
11655 }
11656
11657 fn add_an_item_to_active_pane(
11658 cx: &mut VisualTestContext,
11659 workspace: &Entity<Workspace>,
11660 item_id: u64,
11661 ) -> Entity<TestItem> {
11662 let item = cx.new(|cx| {
11663 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11664 item_id,
11665 "item{item_id}.txt",
11666 cx,
11667 )])
11668 });
11669 workspace.update_in(cx, |workspace, window, cx| {
11670 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11671 });
11672 item
11673 }
11674
11675 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11676 workspace.update_in(cx, |workspace, window, cx| {
11677 workspace.split_pane(
11678 workspace.active_pane().clone(),
11679 SplitDirection::Right,
11680 window,
11681 cx,
11682 )
11683 })
11684 }
11685
11686 #[gpui::test]
11687 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11688 init_test(cx);
11689 let fs = FakeFs::new(cx.executor());
11690 let project = Project::test(fs, None, cx).await;
11691 let (workspace, cx) =
11692 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11693
11694 add_an_item_to_active_pane(cx, &workspace, 1);
11695 split_pane(cx, &workspace);
11696 add_an_item_to_active_pane(cx, &workspace, 2);
11697 split_pane(cx, &workspace); // empty pane
11698 split_pane(cx, &workspace);
11699 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11700
11701 cx.executor().run_until_parked();
11702
11703 workspace.update(cx, |workspace, cx| {
11704 let num_panes = workspace.panes().len();
11705 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11706 let active_item = workspace
11707 .active_pane()
11708 .read(cx)
11709 .active_item()
11710 .expect("item is in focus");
11711
11712 assert_eq!(num_panes, 4);
11713 assert_eq!(num_items_in_current_pane, 1);
11714 assert_eq!(active_item.item_id(), last_item.item_id());
11715 });
11716
11717 workspace.update_in(cx, |workspace, window, cx| {
11718 workspace.join_all_panes(window, cx);
11719 });
11720
11721 workspace.update(cx, |workspace, cx| {
11722 let num_panes = workspace.panes().len();
11723 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11724 let active_item = workspace
11725 .active_pane()
11726 .read(cx)
11727 .active_item()
11728 .expect("item is in focus");
11729
11730 assert_eq!(num_panes, 1);
11731 assert_eq!(num_items_in_current_pane, 3);
11732 assert_eq!(active_item.item_id(), last_item.item_id());
11733 });
11734 }
11735 struct TestModal(FocusHandle);
11736
11737 impl TestModal {
11738 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11739 Self(cx.focus_handle())
11740 }
11741 }
11742
11743 impl EventEmitter<DismissEvent> for TestModal {}
11744
11745 impl Focusable for TestModal {
11746 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11747 self.0.clone()
11748 }
11749 }
11750
11751 impl ModalView for TestModal {}
11752
11753 impl Render for TestModal {
11754 fn render(
11755 &mut self,
11756 _window: &mut Window,
11757 _cx: &mut Context<TestModal>,
11758 ) -> impl IntoElement {
11759 div().track_focus(&self.0)
11760 }
11761 }
11762
11763 #[gpui::test]
11764 async fn test_panels(cx: &mut gpui::TestAppContext) {
11765 init_test(cx);
11766 let fs = FakeFs::new(cx.executor());
11767
11768 let project = Project::test(fs, [], cx).await;
11769 let (multi_workspace, cx) =
11770 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11771 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11772
11773 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11774 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11775 workspace.add_panel(panel_1.clone(), window, cx);
11776 workspace.toggle_dock(DockPosition::Left, window, cx);
11777 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11778 workspace.add_panel(panel_2.clone(), window, cx);
11779 workspace.toggle_dock(DockPosition::Right, window, cx);
11780
11781 let left_dock = workspace.left_dock();
11782 assert_eq!(
11783 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11784 panel_1.panel_id()
11785 );
11786 assert_eq!(
11787 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11788 panel_1.size(window, cx)
11789 );
11790
11791 left_dock.update(cx, |left_dock, cx| {
11792 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11793 });
11794 assert_eq!(
11795 workspace
11796 .right_dock()
11797 .read(cx)
11798 .visible_panel()
11799 .unwrap()
11800 .panel_id(),
11801 panel_2.panel_id(),
11802 );
11803
11804 (panel_1, panel_2)
11805 });
11806
11807 // Move panel_1 to the right
11808 panel_1.update_in(cx, |panel_1, window, cx| {
11809 panel_1.set_position(DockPosition::Right, window, cx)
11810 });
11811
11812 workspace.update_in(cx, |workspace, window, cx| {
11813 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11814 // Since it was the only panel on the left, the left dock should now be closed.
11815 assert!(!workspace.left_dock().read(cx).is_open());
11816 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11817 let right_dock = workspace.right_dock();
11818 assert_eq!(
11819 right_dock.read(cx).visible_panel().unwrap().panel_id(),
11820 panel_1.panel_id()
11821 );
11822 assert_eq!(
11823 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11824 px(1337.)
11825 );
11826
11827 // Now we move panel_2 to the left
11828 panel_2.set_position(DockPosition::Left, window, cx);
11829 });
11830
11831 workspace.update(cx, |workspace, cx| {
11832 // Since panel_2 was not visible on the right, we don't open the left dock.
11833 assert!(!workspace.left_dock().read(cx).is_open());
11834 // And the right dock is unaffected in its displaying of panel_1
11835 assert!(workspace.right_dock().read(cx).is_open());
11836 assert_eq!(
11837 workspace
11838 .right_dock()
11839 .read(cx)
11840 .visible_panel()
11841 .unwrap()
11842 .panel_id(),
11843 panel_1.panel_id(),
11844 );
11845 });
11846
11847 // Move panel_1 back to the left
11848 panel_1.update_in(cx, |panel_1, window, cx| {
11849 panel_1.set_position(DockPosition::Left, window, cx)
11850 });
11851
11852 workspace.update_in(cx, |workspace, window, cx| {
11853 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11854 let left_dock = workspace.left_dock();
11855 assert!(left_dock.read(cx).is_open());
11856 assert_eq!(
11857 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11858 panel_1.panel_id()
11859 );
11860 assert_eq!(
11861 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11862 px(1337.)
11863 );
11864 // And the right dock should be closed as it no longer has any panels.
11865 assert!(!workspace.right_dock().read(cx).is_open());
11866
11867 // Now we move panel_1 to the bottom
11868 panel_1.set_position(DockPosition::Bottom, window, cx);
11869 });
11870
11871 workspace.update_in(cx, |workspace, window, cx| {
11872 // Since panel_1 was visible on the left, we close the left dock.
11873 assert!(!workspace.left_dock().read(cx).is_open());
11874 // The bottom dock is sized based on the panel's default size,
11875 // since the panel orientation changed from vertical to horizontal.
11876 let bottom_dock = workspace.bottom_dock();
11877 assert_eq!(
11878 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
11879 panel_1.size(window, cx),
11880 );
11881 // Close bottom dock and move panel_1 back to the left.
11882 bottom_dock.update(cx, |bottom_dock, cx| {
11883 bottom_dock.set_open(false, window, cx)
11884 });
11885 panel_1.set_position(DockPosition::Left, window, cx);
11886 });
11887
11888 // Emit activated event on panel 1
11889 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
11890
11891 // Now the left dock is open and panel_1 is active and focused.
11892 workspace.update_in(cx, |workspace, window, cx| {
11893 let left_dock = workspace.left_dock();
11894 assert!(left_dock.read(cx).is_open());
11895 assert_eq!(
11896 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11897 panel_1.panel_id(),
11898 );
11899 assert!(panel_1.focus_handle(cx).is_focused(window));
11900 });
11901
11902 // Emit closed event on panel 2, which is not active
11903 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11904
11905 // Wo don't close the left dock, because panel_2 wasn't the active panel
11906 workspace.update(cx, |workspace, cx| {
11907 let left_dock = workspace.left_dock();
11908 assert!(left_dock.read(cx).is_open());
11909 assert_eq!(
11910 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11911 panel_1.panel_id(),
11912 );
11913 });
11914
11915 // Emitting a ZoomIn event shows the panel as zoomed.
11916 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
11917 workspace.read_with(cx, |workspace, _| {
11918 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11919 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
11920 });
11921
11922 // Move panel to another dock while it is zoomed
11923 panel_1.update_in(cx, |panel, window, cx| {
11924 panel.set_position(DockPosition::Right, window, cx)
11925 });
11926 workspace.read_with(cx, |workspace, _| {
11927 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11928
11929 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11930 });
11931
11932 // This is a helper for getting a:
11933 // - valid focus on an element,
11934 // - that isn't a part of the panes and panels system of the Workspace,
11935 // - and doesn't trigger the 'on_focus_lost' API.
11936 let focus_other_view = {
11937 let workspace = workspace.clone();
11938 move |cx: &mut VisualTestContext| {
11939 workspace.update_in(cx, |workspace, window, cx| {
11940 if workspace.active_modal::<TestModal>(cx).is_some() {
11941 workspace.toggle_modal(window, cx, TestModal::new);
11942 workspace.toggle_modal(window, cx, TestModal::new);
11943 } else {
11944 workspace.toggle_modal(window, cx, TestModal::new);
11945 }
11946 })
11947 }
11948 };
11949
11950 // If focus is transferred to another view that's not a panel or another pane, we still show
11951 // the panel as zoomed.
11952 focus_other_view(cx);
11953 workspace.read_with(cx, |workspace, _| {
11954 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11955 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11956 });
11957
11958 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
11959 workspace.update_in(cx, |_workspace, window, cx| {
11960 cx.focus_self(window);
11961 });
11962 workspace.read_with(cx, |workspace, _| {
11963 assert_eq!(workspace.zoomed, None);
11964 assert_eq!(workspace.zoomed_position, None);
11965 });
11966
11967 // If focus is transferred again to another view that's not a panel or a pane, we won't
11968 // show the panel as zoomed because it wasn't zoomed before.
11969 focus_other_view(cx);
11970 workspace.read_with(cx, |workspace, _| {
11971 assert_eq!(workspace.zoomed, None);
11972 assert_eq!(workspace.zoomed_position, None);
11973 });
11974
11975 // When the panel is activated, it is zoomed again.
11976 cx.dispatch_action(ToggleRightDock);
11977 workspace.read_with(cx, |workspace, _| {
11978 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11979 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11980 });
11981
11982 // Emitting a ZoomOut event unzooms the panel.
11983 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
11984 workspace.read_with(cx, |workspace, _| {
11985 assert_eq!(workspace.zoomed, None);
11986 assert_eq!(workspace.zoomed_position, None);
11987 });
11988
11989 // Emit closed event on panel 1, which is active
11990 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11991
11992 // Now the left dock is closed, because panel_1 was the active panel
11993 workspace.update(cx, |workspace, cx| {
11994 let right_dock = workspace.right_dock();
11995 assert!(!right_dock.read(cx).is_open());
11996 });
11997 }
11998
11999 #[gpui::test]
12000 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12001 init_test(cx);
12002
12003 let fs = FakeFs::new(cx.background_executor.clone());
12004 let project = Project::test(fs, [], cx).await;
12005 let (workspace, cx) =
12006 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12007 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12008
12009 let dirty_regular_buffer = cx.new(|cx| {
12010 TestItem::new(cx)
12011 .with_dirty(true)
12012 .with_label("1.txt")
12013 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12014 });
12015 let dirty_regular_buffer_2 = cx.new(|cx| {
12016 TestItem::new(cx)
12017 .with_dirty(true)
12018 .with_label("2.txt")
12019 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12020 });
12021 let dirty_multi_buffer_with_both = cx.new(|cx| {
12022 TestItem::new(cx)
12023 .with_dirty(true)
12024 .with_buffer_kind(ItemBufferKind::Multibuffer)
12025 .with_label("Fake Project Search")
12026 .with_project_items(&[
12027 dirty_regular_buffer.read(cx).project_items[0].clone(),
12028 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12029 ])
12030 });
12031 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12032 workspace.update_in(cx, |workspace, window, cx| {
12033 workspace.add_item(
12034 pane.clone(),
12035 Box::new(dirty_regular_buffer.clone()),
12036 None,
12037 false,
12038 false,
12039 window,
12040 cx,
12041 );
12042 workspace.add_item(
12043 pane.clone(),
12044 Box::new(dirty_regular_buffer_2.clone()),
12045 None,
12046 false,
12047 false,
12048 window,
12049 cx,
12050 );
12051 workspace.add_item(
12052 pane.clone(),
12053 Box::new(dirty_multi_buffer_with_both.clone()),
12054 None,
12055 false,
12056 false,
12057 window,
12058 cx,
12059 );
12060 });
12061
12062 pane.update_in(cx, |pane, window, cx| {
12063 pane.activate_item(2, true, true, window, cx);
12064 assert_eq!(
12065 pane.active_item().unwrap().item_id(),
12066 multi_buffer_with_both_files_id,
12067 "Should select the multi buffer in the pane"
12068 );
12069 });
12070 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12071 pane.close_other_items(
12072 &CloseOtherItems {
12073 save_intent: Some(SaveIntent::Save),
12074 close_pinned: true,
12075 },
12076 None,
12077 window,
12078 cx,
12079 )
12080 });
12081 cx.background_executor.run_until_parked();
12082 assert!(!cx.has_pending_prompt());
12083 close_all_but_multi_buffer_task
12084 .await
12085 .expect("Closing all buffers but the multi buffer failed");
12086 pane.update(cx, |pane, cx| {
12087 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12088 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12089 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12090 assert_eq!(pane.items_len(), 1);
12091 assert_eq!(
12092 pane.active_item().unwrap().item_id(),
12093 multi_buffer_with_both_files_id,
12094 "Should have only the multi buffer left in the pane"
12095 );
12096 assert!(
12097 dirty_multi_buffer_with_both.read(cx).is_dirty,
12098 "The multi buffer containing the unsaved buffer should still be dirty"
12099 );
12100 });
12101
12102 dirty_regular_buffer.update(cx, |buffer, cx| {
12103 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12104 });
12105
12106 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12107 pane.close_active_item(
12108 &CloseActiveItem {
12109 save_intent: Some(SaveIntent::Close),
12110 close_pinned: false,
12111 },
12112 window,
12113 cx,
12114 )
12115 });
12116 cx.background_executor.run_until_parked();
12117 assert!(
12118 cx.has_pending_prompt(),
12119 "Dirty multi buffer should prompt a save dialog"
12120 );
12121 cx.simulate_prompt_answer("Save");
12122 cx.background_executor.run_until_parked();
12123 close_multi_buffer_task
12124 .await
12125 .expect("Closing the multi buffer failed");
12126 pane.update(cx, |pane, cx| {
12127 assert_eq!(
12128 dirty_multi_buffer_with_both.read(cx).save_count,
12129 1,
12130 "Multi buffer item should get be saved"
12131 );
12132 // Test impl does not save inner items, so we do not assert them
12133 assert_eq!(
12134 pane.items_len(),
12135 0,
12136 "No more items should be left in the pane"
12137 );
12138 assert!(pane.active_item().is_none());
12139 });
12140 }
12141
12142 #[gpui::test]
12143 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
12144 cx: &mut TestAppContext,
12145 ) {
12146 init_test(cx);
12147
12148 let fs = FakeFs::new(cx.background_executor.clone());
12149 let project = Project::test(fs, [], cx).await;
12150 let (workspace, cx) =
12151 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12152 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12153
12154 let dirty_regular_buffer = cx.new(|cx| {
12155 TestItem::new(cx)
12156 .with_dirty(true)
12157 .with_label("1.txt")
12158 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12159 });
12160 let dirty_regular_buffer_2 = cx.new(|cx| {
12161 TestItem::new(cx)
12162 .with_dirty(true)
12163 .with_label("2.txt")
12164 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12165 });
12166 let clear_regular_buffer = cx.new(|cx| {
12167 TestItem::new(cx)
12168 .with_label("3.txt")
12169 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12170 });
12171
12172 let dirty_multi_buffer_with_both = cx.new(|cx| {
12173 TestItem::new(cx)
12174 .with_dirty(true)
12175 .with_buffer_kind(ItemBufferKind::Multibuffer)
12176 .with_label("Fake Project Search")
12177 .with_project_items(&[
12178 dirty_regular_buffer.read(cx).project_items[0].clone(),
12179 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12180 clear_regular_buffer.read(cx).project_items[0].clone(),
12181 ])
12182 });
12183 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12184 workspace.update_in(cx, |workspace, window, cx| {
12185 workspace.add_item(
12186 pane.clone(),
12187 Box::new(dirty_regular_buffer.clone()),
12188 None,
12189 false,
12190 false,
12191 window,
12192 cx,
12193 );
12194 workspace.add_item(
12195 pane.clone(),
12196 Box::new(dirty_multi_buffer_with_both.clone()),
12197 None,
12198 false,
12199 false,
12200 window,
12201 cx,
12202 );
12203 });
12204
12205 pane.update_in(cx, |pane, window, cx| {
12206 pane.activate_item(1, true, true, window, cx);
12207 assert_eq!(
12208 pane.active_item().unwrap().item_id(),
12209 multi_buffer_with_both_files_id,
12210 "Should select the multi buffer in the pane"
12211 );
12212 });
12213 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12214 pane.close_active_item(
12215 &CloseActiveItem {
12216 save_intent: None,
12217 close_pinned: false,
12218 },
12219 window,
12220 cx,
12221 )
12222 });
12223 cx.background_executor.run_until_parked();
12224 assert!(
12225 cx.has_pending_prompt(),
12226 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
12227 );
12228 }
12229
12230 /// Tests that when `close_on_file_delete` is enabled, files are automatically
12231 /// closed when they are deleted from disk.
12232 #[gpui::test]
12233 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
12234 init_test(cx);
12235
12236 // Enable the close_on_disk_deletion setting
12237 cx.update_global(|store: &mut SettingsStore, cx| {
12238 store.update_user_settings(cx, |settings| {
12239 settings.workspace.close_on_file_delete = Some(true);
12240 });
12241 });
12242
12243 let fs = FakeFs::new(cx.background_executor.clone());
12244 let project = Project::test(fs, [], cx).await;
12245 let (workspace, cx) =
12246 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12247 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12248
12249 // Create a test item that simulates a file
12250 let item = cx.new(|cx| {
12251 TestItem::new(cx)
12252 .with_label("test.txt")
12253 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12254 });
12255
12256 // Add item to workspace
12257 workspace.update_in(cx, |workspace, window, cx| {
12258 workspace.add_item(
12259 pane.clone(),
12260 Box::new(item.clone()),
12261 None,
12262 false,
12263 false,
12264 window,
12265 cx,
12266 );
12267 });
12268
12269 // Verify the item is in the pane
12270 pane.read_with(cx, |pane, _| {
12271 assert_eq!(pane.items().count(), 1);
12272 });
12273
12274 // Simulate file deletion by setting the item's deleted state
12275 item.update(cx, |item, _| {
12276 item.set_has_deleted_file(true);
12277 });
12278
12279 // Emit UpdateTab event to trigger the close behavior
12280 cx.run_until_parked();
12281 item.update(cx, |_, cx| {
12282 cx.emit(ItemEvent::UpdateTab);
12283 });
12284
12285 // Allow the close operation to complete
12286 cx.run_until_parked();
12287
12288 // Verify the item was automatically closed
12289 pane.read_with(cx, |pane, _| {
12290 assert_eq!(
12291 pane.items().count(),
12292 0,
12293 "Item should be automatically closed when file is deleted"
12294 );
12295 });
12296 }
12297
12298 /// Tests that when `close_on_file_delete` is disabled (default), files remain
12299 /// open with a strikethrough when they are deleted from disk.
12300 #[gpui::test]
12301 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12302 init_test(cx);
12303
12304 // Ensure close_on_disk_deletion is disabled (default)
12305 cx.update_global(|store: &mut SettingsStore, cx| {
12306 store.update_user_settings(cx, |settings| {
12307 settings.workspace.close_on_file_delete = Some(false);
12308 });
12309 });
12310
12311 let fs = FakeFs::new(cx.background_executor.clone());
12312 let project = Project::test(fs, [], cx).await;
12313 let (workspace, cx) =
12314 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12315 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12316
12317 // Create a test item that simulates a file
12318 let item = cx.new(|cx| {
12319 TestItem::new(cx)
12320 .with_label("test.txt")
12321 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12322 });
12323
12324 // Add item to workspace
12325 workspace.update_in(cx, |workspace, window, cx| {
12326 workspace.add_item(
12327 pane.clone(),
12328 Box::new(item.clone()),
12329 None,
12330 false,
12331 false,
12332 window,
12333 cx,
12334 );
12335 });
12336
12337 // Verify the item is in the pane
12338 pane.read_with(cx, |pane, _| {
12339 assert_eq!(pane.items().count(), 1);
12340 });
12341
12342 // Simulate file deletion
12343 item.update(cx, |item, _| {
12344 item.set_has_deleted_file(true);
12345 });
12346
12347 // Emit UpdateTab event
12348 cx.run_until_parked();
12349 item.update(cx, |_, cx| {
12350 cx.emit(ItemEvent::UpdateTab);
12351 });
12352
12353 // Allow any potential close operation to complete
12354 cx.run_until_parked();
12355
12356 // Verify the item remains open (with strikethrough)
12357 pane.read_with(cx, |pane, _| {
12358 assert_eq!(
12359 pane.items().count(),
12360 1,
12361 "Item should remain open when close_on_disk_deletion is disabled"
12362 );
12363 });
12364
12365 // Verify the item shows as deleted
12366 item.read_with(cx, |item, _| {
12367 assert!(
12368 item.has_deleted_file,
12369 "Item should be marked as having deleted file"
12370 );
12371 });
12372 }
12373
12374 /// Tests that dirty files are not automatically closed when deleted from disk,
12375 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12376 /// unsaved changes without being prompted.
12377 #[gpui::test]
12378 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12379 init_test(cx);
12380
12381 // Enable the close_on_file_delete setting
12382 cx.update_global(|store: &mut SettingsStore, cx| {
12383 store.update_user_settings(cx, |settings| {
12384 settings.workspace.close_on_file_delete = Some(true);
12385 });
12386 });
12387
12388 let fs = FakeFs::new(cx.background_executor.clone());
12389 let project = Project::test(fs, [], cx).await;
12390 let (workspace, cx) =
12391 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12392 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12393
12394 // Create a dirty test item
12395 let item = cx.new(|cx| {
12396 TestItem::new(cx)
12397 .with_dirty(true)
12398 .with_label("test.txt")
12399 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12400 });
12401
12402 // Add item to workspace
12403 workspace.update_in(cx, |workspace, window, cx| {
12404 workspace.add_item(
12405 pane.clone(),
12406 Box::new(item.clone()),
12407 None,
12408 false,
12409 false,
12410 window,
12411 cx,
12412 );
12413 });
12414
12415 // Simulate file deletion
12416 item.update(cx, |item, _| {
12417 item.set_has_deleted_file(true);
12418 });
12419
12420 // Emit UpdateTab event to trigger the close behavior
12421 cx.run_until_parked();
12422 item.update(cx, |_, cx| {
12423 cx.emit(ItemEvent::UpdateTab);
12424 });
12425
12426 // Allow any potential close operation to complete
12427 cx.run_until_parked();
12428
12429 // Verify the item remains open (dirty files are not auto-closed)
12430 pane.read_with(cx, |pane, _| {
12431 assert_eq!(
12432 pane.items().count(),
12433 1,
12434 "Dirty items should not be automatically closed even when file is deleted"
12435 );
12436 });
12437
12438 // Verify the item is marked as deleted and still dirty
12439 item.read_with(cx, |item, _| {
12440 assert!(
12441 item.has_deleted_file,
12442 "Item should be marked as having deleted file"
12443 );
12444 assert!(item.is_dirty, "Item should still be dirty");
12445 });
12446 }
12447
12448 /// Tests that navigation history is cleaned up when files are auto-closed
12449 /// due to deletion from disk.
12450 #[gpui::test]
12451 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12452 init_test(cx);
12453
12454 // Enable the close_on_file_delete setting
12455 cx.update_global(|store: &mut SettingsStore, cx| {
12456 store.update_user_settings(cx, |settings| {
12457 settings.workspace.close_on_file_delete = Some(true);
12458 });
12459 });
12460
12461 let fs = FakeFs::new(cx.background_executor.clone());
12462 let project = Project::test(fs, [], cx).await;
12463 let (workspace, cx) =
12464 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12465 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12466
12467 // Create test items
12468 let item1 = cx.new(|cx| {
12469 TestItem::new(cx)
12470 .with_label("test1.txt")
12471 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12472 });
12473 let item1_id = item1.item_id();
12474
12475 let item2 = cx.new(|cx| {
12476 TestItem::new(cx)
12477 .with_label("test2.txt")
12478 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12479 });
12480
12481 // Add items to workspace
12482 workspace.update_in(cx, |workspace, window, cx| {
12483 workspace.add_item(
12484 pane.clone(),
12485 Box::new(item1.clone()),
12486 None,
12487 false,
12488 false,
12489 window,
12490 cx,
12491 );
12492 workspace.add_item(
12493 pane.clone(),
12494 Box::new(item2.clone()),
12495 None,
12496 false,
12497 false,
12498 window,
12499 cx,
12500 );
12501 });
12502
12503 // Activate item1 to ensure it gets navigation entries
12504 pane.update_in(cx, |pane, window, cx| {
12505 pane.activate_item(0, true, true, window, cx);
12506 });
12507
12508 // Switch to item2 and back to create navigation history
12509 pane.update_in(cx, |pane, window, cx| {
12510 pane.activate_item(1, true, true, window, cx);
12511 });
12512 cx.run_until_parked();
12513
12514 pane.update_in(cx, |pane, window, cx| {
12515 pane.activate_item(0, true, true, window, cx);
12516 });
12517 cx.run_until_parked();
12518
12519 // Simulate file deletion for item1
12520 item1.update(cx, |item, _| {
12521 item.set_has_deleted_file(true);
12522 });
12523
12524 // Emit UpdateTab event to trigger the close behavior
12525 item1.update(cx, |_, cx| {
12526 cx.emit(ItemEvent::UpdateTab);
12527 });
12528 cx.run_until_parked();
12529
12530 // Verify item1 was closed
12531 pane.read_with(cx, |pane, _| {
12532 assert_eq!(
12533 pane.items().count(),
12534 1,
12535 "Should have 1 item remaining after auto-close"
12536 );
12537 });
12538
12539 // Check navigation history after close
12540 let has_item = pane.read_with(cx, |pane, cx| {
12541 let mut has_item = false;
12542 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12543 if entry.item.id() == item1_id {
12544 has_item = true;
12545 }
12546 });
12547 has_item
12548 });
12549
12550 assert!(
12551 !has_item,
12552 "Navigation history should not contain closed item entries"
12553 );
12554 }
12555
12556 #[gpui::test]
12557 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12558 cx: &mut TestAppContext,
12559 ) {
12560 init_test(cx);
12561
12562 let fs = FakeFs::new(cx.background_executor.clone());
12563 let project = Project::test(fs, [], cx).await;
12564 let (workspace, cx) =
12565 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12566 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12567
12568 let dirty_regular_buffer = cx.new(|cx| {
12569 TestItem::new(cx)
12570 .with_dirty(true)
12571 .with_label("1.txt")
12572 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12573 });
12574 let dirty_regular_buffer_2 = cx.new(|cx| {
12575 TestItem::new(cx)
12576 .with_dirty(true)
12577 .with_label("2.txt")
12578 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12579 });
12580 let clear_regular_buffer = cx.new(|cx| {
12581 TestItem::new(cx)
12582 .with_label("3.txt")
12583 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12584 });
12585
12586 let dirty_multi_buffer = cx.new(|cx| {
12587 TestItem::new(cx)
12588 .with_dirty(true)
12589 .with_buffer_kind(ItemBufferKind::Multibuffer)
12590 .with_label("Fake Project Search")
12591 .with_project_items(&[
12592 dirty_regular_buffer.read(cx).project_items[0].clone(),
12593 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12594 clear_regular_buffer.read(cx).project_items[0].clone(),
12595 ])
12596 });
12597 workspace.update_in(cx, |workspace, window, cx| {
12598 workspace.add_item(
12599 pane.clone(),
12600 Box::new(dirty_regular_buffer.clone()),
12601 None,
12602 false,
12603 false,
12604 window,
12605 cx,
12606 );
12607 workspace.add_item(
12608 pane.clone(),
12609 Box::new(dirty_regular_buffer_2.clone()),
12610 None,
12611 false,
12612 false,
12613 window,
12614 cx,
12615 );
12616 workspace.add_item(
12617 pane.clone(),
12618 Box::new(dirty_multi_buffer.clone()),
12619 None,
12620 false,
12621 false,
12622 window,
12623 cx,
12624 );
12625 });
12626
12627 pane.update_in(cx, |pane, window, cx| {
12628 pane.activate_item(2, true, true, window, cx);
12629 assert_eq!(
12630 pane.active_item().unwrap().item_id(),
12631 dirty_multi_buffer.item_id(),
12632 "Should select the multi buffer in the pane"
12633 );
12634 });
12635 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12636 pane.close_active_item(
12637 &CloseActiveItem {
12638 save_intent: None,
12639 close_pinned: false,
12640 },
12641 window,
12642 cx,
12643 )
12644 });
12645 cx.background_executor.run_until_parked();
12646 assert!(
12647 !cx.has_pending_prompt(),
12648 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12649 );
12650 close_multi_buffer_task
12651 .await
12652 .expect("Closing multi buffer failed");
12653 pane.update(cx, |pane, cx| {
12654 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12655 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12656 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12657 assert_eq!(
12658 pane.items()
12659 .map(|item| item.item_id())
12660 .sorted()
12661 .collect::<Vec<_>>(),
12662 vec![
12663 dirty_regular_buffer.item_id(),
12664 dirty_regular_buffer_2.item_id(),
12665 ],
12666 "Should have no multi buffer left in the pane"
12667 );
12668 assert!(dirty_regular_buffer.read(cx).is_dirty);
12669 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12670 });
12671 }
12672
12673 #[gpui::test]
12674 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12675 init_test(cx);
12676 let fs = FakeFs::new(cx.executor());
12677 let project = Project::test(fs, [], cx).await;
12678 let (multi_workspace, cx) =
12679 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12680 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12681
12682 // Add a new panel to the right dock, opening the dock and setting the
12683 // focus to the new panel.
12684 let panel = workspace.update_in(cx, |workspace, window, cx| {
12685 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12686 workspace.add_panel(panel.clone(), window, cx);
12687
12688 workspace
12689 .right_dock()
12690 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12691
12692 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12693
12694 panel
12695 });
12696
12697 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12698 // panel to the next valid position which, in this case, is the left
12699 // dock.
12700 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12701 workspace.update(cx, |workspace, cx| {
12702 assert!(workspace.left_dock().read(cx).is_open());
12703 assert_eq!(panel.read(cx).position, DockPosition::Left);
12704 });
12705
12706 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12707 // panel to the next valid position which, in this case, is the bottom
12708 // dock.
12709 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12710 workspace.update(cx, |workspace, cx| {
12711 assert!(workspace.bottom_dock().read(cx).is_open());
12712 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12713 });
12714
12715 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12716 // around moving the panel to its initial position, the right dock.
12717 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12718 workspace.update(cx, |workspace, cx| {
12719 assert!(workspace.right_dock().read(cx).is_open());
12720 assert_eq!(panel.read(cx).position, DockPosition::Right);
12721 });
12722
12723 // Remove focus from the panel, ensuring that, if the panel is not
12724 // focused, the `MoveFocusedPanelToNextPosition` action does not update
12725 // the panel's position, so the panel is still in the right dock.
12726 workspace.update_in(cx, |workspace, window, cx| {
12727 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12728 });
12729
12730 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12731 workspace.update(cx, |workspace, cx| {
12732 assert!(workspace.right_dock().read(cx).is_open());
12733 assert_eq!(panel.read(cx).position, DockPosition::Right);
12734 });
12735 }
12736
12737 #[gpui::test]
12738 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12739 init_test(cx);
12740
12741 let fs = FakeFs::new(cx.executor());
12742 let project = Project::test(fs, [], cx).await;
12743 let (workspace, cx) =
12744 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12745
12746 let item_1 = cx.new(|cx| {
12747 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12748 });
12749 workspace.update_in(cx, |workspace, window, cx| {
12750 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12751 workspace.move_item_to_pane_in_direction(
12752 &MoveItemToPaneInDirection {
12753 direction: SplitDirection::Right,
12754 focus: true,
12755 clone: false,
12756 },
12757 window,
12758 cx,
12759 );
12760 workspace.move_item_to_pane_at_index(
12761 &MoveItemToPane {
12762 destination: 3,
12763 focus: true,
12764 clone: false,
12765 },
12766 window,
12767 cx,
12768 );
12769
12770 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12771 assert_eq!(
12772 pane_items_paths(&workspace.active_pane, cx),
12773 vec!["first.txt".to_string()],
12774 "Single item was not moved anywhere"
12775 );
12776 });
12777
12778 let item_2 = cx.new(|cx| {
12779 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12780 });
12781 workspace.update_in(cx, |workspace, window, cx| {
12782 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12783 assert_eq!(
12784 pane_items_paths(&workspace.panes[0], cx),
12785 vec!["first.txt".to_string(), "second.txt".to_string()],
12786 );
12787 workspace.move_item_to_pane_in_direction(
12788 &MoveItemToPaneInDirection {
12789 direction: SplitDirection::Right,
12790 focus: true,
12791 clone: false,
12792 },
12793 window,
12794 cx,
12795 );
12796
12797 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12798 assert_eq!(
12799 pane_items_paths(&workspace.panes[0], cx),
12800 vec!["first.txt".to_string()],
12801 "After moving, one item should be left in the original pane"
12802 );
12803 assert_eq!(
12804 pane_items_paths(&workspace.panes[1], cx),
12805 vec!["second.txt".to_string()],
12806 "New item should have been moved to the new pane"
12807 );
12808 });
12809
12810 let item_3 = cx.new(|cx| {
12811 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12812 });
12813 workspace.update_in(cx, |workspace, window, cx| {
12814 let original_pane = workspace.panes[0].clone();
12815 workspace.set_active_pane(&original_pane, window, cx);
12816 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12817 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12818 assert_eq!(
12819 pane_items_paths(&workspace.active_pane, cx),
12820 vec!["first.txt".to_string(), "third.txt".to_string()],
12821 "New pane should be ready to move one item out"
12822 );
12823
12824 workspace.move_item_to_pane_at_index(
12825 &MoveItemToPane {
12826 destination: 3,
12827 focus: true,
12828 clone: false,
12829 },
12830 window,
12831 cx,
12832 );
12833 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12834 assert_eq!(
12835 pane_items_paths(&workspace.active_pane, cx),
12836 vec!["first.txt".to_string()],
12837 "After moving, one item should be left in the original pane"
12838 );
12839 assert_eq!(
12840 pane_items_paths(&workspace.panes[1], cx),
12841 vec!["second.txt".to_string()],
12842 "Previously created pane should be unchanged"
12843 );
12844 assert_eq!(
12845 pane_items_paths(&workspace.panes[2], cx),
12846 vec!["third.txt".to_string()],
12847 "New item should have been moved to the new pane"
12848 );
12849 });
12850 }
12851
12852 #[gpui::test]
12853 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12854 init_test(cx);
12855
12856 let fs = FakeFs::new(cx.executor());
12857 let project = Project::test(fs, [], cx).await;
12858 let (workspace, cx) =
12859 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12860
12861 let item_1 = cx.new(|cx| {
12862 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12863 });
12864 workspace.update_in(cx, |workspace, window, cx| {
12865 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12866 workspace.move_item_to_pane_in_direction(
12867 &MoveItemToPaneInDirection {
12868 direction: SplitDirection::Right,
12869 focus: true,
12870 clone: true,
12871 },
12872 window,
12873 cx,
12874 );
12875 });
12876 cx.run_until_parked();
12877 workspace.update_in(cx, |workspace, window, cx| {
12878 workspace.move_item_to_pane_at_index(
12879 &MoveItemToPane {
12880 destination: 3,
12881 focus: true,
12882 clone: true,
12883 },
12884 window,
12885 cx,
12886 );
12887 });
12888 cx.run_until_parked();
12889
12890 workspace.update(cx, |workspace, cx| {
12891 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
12892 for pane in workspace.panes() {
12893 assert_eq!(
12894 pane_items_paths(pane, cx),
12895 vec!["first.txt".to_string()],
12896 "Single item exists in all panes"
12897 );
12898 }
12899 });
12900
12901 // verify that the active pane has been updated after waiting for the
12902 // pane focus event to fire and resolve
12903 workspace.read_with(cx, |workspace, _app| {
12904 assert_eq!(
12905 workspace.active_pane(),
12906 &workspace.panes[2],
12907 "The third pane should be the active one: {:?}",
12908 workspace.panes
12909 );
12910 })
12911 }
12912
12913 #[gpui::test]
12914 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
12915 init_test(cx);
12916
12917 let fs = FakeFs::new(cx.executor());
12918 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
12919
12920 let project = Project::test(fs, ["root".as_ref()], cx).await;
12921 let (workspace, cx) =
12922 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12923
12924 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12925 // Add item to pane A with project path
12926 let item_a = cx.new(|cx| {
12927 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12928 });
12929 workspace.update_in(cx, |workspace, window, cx| {
12930 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
12931 });
12932
12933 // Split to create pane B
12934 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
12935 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
12936 });
12937
12938 // Add item with SAME project path to pane B, and pin it
12939 let item_b = cx.new(|cx| {
12940 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12941 });
12942 pane_b.update_in(cx, |pane, window, cx| {
12943 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
12944 pane.set_pinned_count(1);
12945 });
12946
12947 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
12948 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
12949
12950 // close_pinned: false should only close the unpinned copy
12951 workspace.update_in(cx, |workspace, window, cx| {
12952 workspace.close_item_in_all_panes(
12953 &CloseItemInAllPanes {
12954 save_intent: Some(SaveIntent::Close),
12955 close_pinned: false,
12956 },
12957 window,
12958 cx,
12959 )
12960 });
12961 cx.executor().run_until_parked();
12962
12963 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
12964 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12965 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
12966 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
12967
12968 // Split again, seeing as closing the previous item also closed its
12969 // pane, so only pane remains, which does not allow us to properly test
12970 // that both items close when `close_pinned: true`.
12971 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
12972 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
12973 });
12974
12975 // Add an item with the same project path to pane C so that
12976 // close_item_in_all_panes can determine what to close across all panes
12977 // (it reads the active item from the active pane, and split_pane
12978 // creates an empty pane).
12979 let item_c = cx.new(|cx| {
12980 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12981 });
12982 pane_c.update_in(cx, |pane, window, cx| {
12983 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
12984 });
12985
12986 // close_pinned: true should close the pinned copy too
12987 workspace.update_in(cx, |workspace, window, cx| {
12988 let panes_count = workspace.panes().len();
12989 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
12990
12991 workspace.close_item_in_all_panes(
12992 &CloseItemInAllPanes {
12993 save_intent: Some(SaveIntent::Close),
12994 close_pinned: true,
12995 },
12996 window,
12997 cx,
12998 )
12999 });
13000 cx.executor().run_until_parked();
13001
13002 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13003 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13004 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13005 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13006 }
13007
13008 mod register_project_item_tests {
13009
13010 use super::*;
13011
13012 // View
13013 struct TestPngItemView {
13014 focus_handle: FocusHandle,
13015 }
13016 // Model
13017 struct TestPngItem {}
13018
13019 impl project::ProjectItem for TestPngItem {
13020 fn try_open(
13021 _project: &Entity<Project>,
13022 path: &ProjectPath,
13023 cx: &mut App,
13024 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13025 if path.path.extension().unwrap() == "png" {
13026 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13027 } else {
13028 None
13029 }
13030 }
13031
13032 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13033 None
13034 }
13035
13036 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13037 None
13038 }
13039
13040 fn is_dirty(&self) -> bool {
13041 false
13042 }
13043 }
13044
13045 impl Item for TestPngItemView {
13046 type Event = ();
13047 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13048 "".into()
13049 }
13050 }
13051 impl EventEmitter<()> for TestPngItemView {}
13052 impl Focusable for TestPngItemView {
13053 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13054 self.focus_handle.clone()
13055 }
13056 }
13057
13058 impl Render for TestPngItemView {
13059 fn render(
13060 &mut self,
13061 _window: &mut Window,
13062 _cx: &mut Context<Self>,
13063 ) -> impl IntoElement {
13064 Empty
13065 }
13066 }
13067
13068 impl ProjectItem for TestPngItemView {
13069 type Item = TestPngItem;
13070
13071 fn for_project_item(
13072 _project: Entity<Project>,
13073 _pane: Option<&Pane>,
13074 _item: Entity<Self::Item>,
13075 _: &mut Window,
13076 cx: &mut Context<Self>,
13077 ) -> Self
13078 where
13079 Self: Sized,
13080 {
13081 Self {
13082 focus_handle: cx.focus_handle(),
13083 }
13084 }
13085 }
13086
13087 // View
13088 struct TestIpynbItemView {
13089 focus_handle: FocusHandle,
13090 }
13091 // Model
13092 struct TestIpynbItem {}
13093
13094 impl project::ProjectItem for TestIpynbItem {
13095 fn try_open(
13096 _project: &Entity<Project>,
13097 path: &ProjectPath,
13098 cx: &mut App,
13099 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13100 if path.path.extension().unwrap() == "ipynb" {
13101 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13102 } else {
13103 None
13104 }
13105 }
13106
13107 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13108 None
13109 }
13110
13111 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13112 None
13113 }
13114
13115 fn is_dirty(&self) -> bool {
13116 false
13117 }
13118 }
13119
13120 impl Item for TestIpynbItemView {
13121 type Event = ();
13122 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13123 "".into()
13124 }
13125 }
13126 impl EventEmitter<()> for TestIpynbItemView {}
13127 impl Focusable for TestIpynbItemView {
13128 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13129 self.focus_handle.clone()
13130 }
13131 }
13132
13133 impl Render for TestIpynbItemView {
13134 fn render(
13135 &mut self,
13136 _window: &mut Window,
13137 _cx: &mut Context<Self>,
13138 ) -> impl IntoElement {
13139 Empty
13140 }
13141 }
13142
13143 impl ProjectItem for TestIpynbItemView {
13144 type Item = TestIpynbItem;
13145
13146 fn for_project_item(
13147 _project: Entity<Project>,
13148 _pane: Option<&Pane>,
13149 _item: Entity<Self::Item>,
13150 _: &mut Window,
13151 cx: &mut Context<Self>,
13152 ) -> Self
13153 where
13154 Self: Sized,
13155 {
13156 Self {
13157 focus_handle: cx.focus_handle(),
13158 }
13159 }
13160 }
13161
13162 struct TestAlternatePngItemView {
13163 focus_handle: FocusHandle,
13164 }
13165
13166 impl Item for TestAlternatePngItemView {
13167 type Event = ();
13168 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13169 "".into()
13170 }
13171 }
13172
13173 impl EventEmitter<()> for TestAlternatePngItemView {}
13174 impl Focusable for TestAlternatePngItemView {
13175 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13176 self.focus_handle.clone()
13177 }
13178 }
13179
13180 impl Render for TestAlternatePngItemView {
13181 fn render(
13182 &mut self,
13183 _window: &mut Window,
13184 _cx: &mut Context<Self>,
13185 ) -> impl IntoElement {
13186 Empty
13187 }
13188 }
13189
13190 impl ProjectItem for TestAlternatePngItemView {
13191 type Item = TestPngItem;
13192
13193 fn for_project_item(
13194 _project: Entity<Project>,
13195 _pane: Option<&Pane>,
13196 _item: Entity<Self::Item>,
13197 _: &mut Window,
13198 cx: &mut Context<Self>,
13199 ) -> Self
13200 where
13201 Self: Sized,
13202 {
13203 Self {
13204 focus_handle: cx.focus_handle(),
13205 }
13206 }
13207 }
13208
13209 #[gpui::test]
13210 async fn test_register_project_item(cx: &mut TestAppContext) {
13211 init_test(cx);
13212
13213 cx.update(|cx| {
13214 register_project_item::<TestPngItemView>(cx);
13215 register_project_item::<TestIpynbItemView>(cx);
13216 });
13217
13218 let fs = FakeFs::new(cx.executor());
13219 fs.insert_tree(
13220 "/root1",
13221 json!({
13222 "one.png": "BINARYDATAHERE",
13223 "two.ipynb": "{ totally a notebook }",
13224 "three.txt": "editing text, sure why not?"
13225 }),
13226 )
13227 .await;
13228
13229 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13230 let (workspace, cx) =
13231 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13232
13233 let worktree_id = project.update(cx, |project, cx| {
13234 project.worktrees(cx).next().unwrap().read(cx).id()
13235 });
13236
13237 let handle = workspace
13238 .update_in(cx, |workspace, window, cx| {
13239 let project_path = (worktree_id, rel_path("one.png"));
13240 workspace.open_path(project_path, None, true, window, cx)
13241 })
13242 .await
13243 .unwrap();
13244
13245 // Now we can check if the handle we got back errored or not
13246 assert_eq!(
13247 handle.to_any_view().entity_type(),
13248 TypeId::of::<TestPngItemView>()
13249 );
13250
13251 let handle = workspace
13252 .update_in(cx, |workspace, window, cx| {
13253 let project_path = (worktree_id, rel_path("two.ipynb"));
13254 workspace.open_path(project_path, None, true, window, cx)
13255 })
13256 .await
13257 .unwrap();
13258
13259 assert_eq!(
13260 handle.to_any_view().entity_type(),
13261 TypeId::of::<TestIpynbItemView>()
13262 );
13263
13264 let handle = workspace
13265 .update_in(cx, |workspace, window, cx| {
13266 let project_path = (worktree_id, rel_path("three.txt"));
13267 workspace.open_path(project_path, None, true, window, cx)
13268 })
13269 .await;
13270 assert!(handle.is_err());
13271 }
13272
13273 #[gpui::test]
13274 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
13275 init_test(cx);
13276
13277 cx.update(|cx| {
13278 register_project_item::<TestPngItemView>(cx);
13279 register_project_item::<TestAlternatePngItemView>(cx);
13280 });
13281
13282 let fs = FakeFs::new(cx.executor());
13283 fs.insert_tree(
13284 "/root1",
13285 json!({
13286 "one.png": "BINARYDATAHERE",
13287 "two.ipynb": "{ totally a notebook }",
13288 "three.txt": "editing text, sure why not?"
13289 }),
13290 )
13291 .await;
13292 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13293 let (workspace, cx) =
13294 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13295 let worktree_id = project.update(cx, |project, cx| {
13296 project.worktrees(cx).next().unwrap().read(cx).id()
13297 });
13298
13299 let handle = workspace
13300 .update_in(cx, |workspace, window, cx| {
13301 let project_path = (worktree_id, rel_path("one.png"));
13302 workspace.open_path(project_path, None, true, window, cx)
13303 })
13304 .await
13305 .unwrap();
13306
13307 // This _must_ be the second item registered
13308 assert_eq!(
13309 handle.to_any_view().entity_type(),
13310 TypeId::of::<TestAlternatePngItemView>()
13311 );
13312
13313 let handle = workspace
13314 .update_in(cx, |workspace, window, cx| {
13315 let project_path = (worktree_id, rel_path("three.txt"));
13316 workspace.open_path(project_path, None, true, window, cx)
13317 })
13318 .await;
13319 assert!(handle.is_err());
13320 }
13321 }
13322
13323 #[gpui::test]
13324 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13325 init_test(cx);
13326
13327 let fs = FakeFs::new(cx.executor());
13328 let project = Project::test(fs, [], cx).await;
13329 let (workspace, _cx) =
13330 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13331
13332 // Test with status bar shown (default)
13333 workspace.read_with(cx, |workspace, cx| {
13334 let visible = workspace.status_bar_visible(cx);
13335 assert!(visible, "Status bar should be visible by default");
13336 });
13337
13338 // Test with status bar hidden
13339 cx.update_global(|store: &mut SettingsStore, cx| {
13340 store.update_user_settings(cx, |settings| {
13341 settings.status_bar.get_or_insert_default().show = Some(false);
13342 });
13343 });
13344
13345 workspace.read_with(cx, |workspace, cx| {
13346 let visible = workspace.status_bar_visible(cx);
13347 assert!(!visible, "Status bar should be hidden when show is false");
13348 });
13349
13350 // Test with status bar shown explicitly
13351 cx.update_global(|store: &mut SettingsStore, cx| {
13352 store.update_user_settings(cx, |settings| {
13353 settings.status_bar.get_or_insert_default().show = Some(true);
13354 });
13355 });
13356
13357 workspace.read_with(cx, |workspace, cx| {
13358 let visible = workspace.status_bar_visible(cx);
13359 assert!(visible, "Status bar should be visible when show is true");
13360 });
13361 }
13362
13363 #[gpui::test]
13364 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13365 init_test(cx);
13366
13367 let fs = FakeFs::new(cx.executor());
13368 let project = Project::test(fs, [], cx).await;
13369 let (multi_workspace, cx) =
13370 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13371 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13372 let panel = workspace.update_in(cx, |workspace, window, cx| {
13373 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13374 workspace.add_panel(panel.clone(), window, cx);
13375
13376 workspace
13377 .right_dock()
13378 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13379
13380 panel
13381 });
13382
13383 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13384 let item_a = cx.new(TestItem::new);
13385 let item_b = cx.new(TestItem::new);
13386 let item_a_id = item_a.entity_id();
13387 let item_b_id = item_b.entity_id();
13388
13389 pane.update_in(cx, |pane, window, cx| {
13390 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13391 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13392 });
13393
13394 pane.read_with(cx, |pane, _| {
13395 assert_eq!(pane.items_len(), 2);
13396 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13397 });
13398
13399 workspace.update_in(cx, |workspace, window, cx| {
13400 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13401 });
13402
13403 workspace.update_in(cx, |_, window, cx| {
13404 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13405 });
13406
13407 // Assert that the `pane::CloseActiveItem` action is handled at the
13408 // workspace level when one of the dock panels is focused and, in that
13409 // case, the center pane's active item is closed but the focus is not
13410 // moved.
13411 cx.dispatch_action(pane::CloseActiveItem::default());
13412 cx.run_until_parked();
13413
13414 pane.read_with(cx, |pane, _| {
13415 assert_eq!(pane.items_len(), 1);
13416 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13417 });
13418
13419 workspace.update_in(cx, |workspace, window, cx| {
13420 assert!(workspace.right_dock().read(cx).is_open());
13421 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13422 });
13423 }
13424
13425 #[gpui::test]
13426 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13427 init_test(cx);
13428 let fs = FakeFs::new(cx.executor());
13429
13430 let project_a = Project::test(fs.clone(), [], cx).await;
13431 let project_b = Project::test(fs, [], cx).await;
13432
13433 let multi_workspace_handle =
13434 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13435 cx.run_until_parked();
13436
13437 let workspace_a = multi_workspace_handle
13438 .read_with(cx, |mw, _| mw.workspace().clone())
13439 .unwrap();
13440
13441 let _workspace_b = multi_workspace_handle
13442 .update(cx, |mw, window, cx| {
13443 mw.test_add_workspace(project_b, window, cx)
13444 })
13445 .unwrap();
13446
13447 // Switch to workspace A
13448 multi_workspace_handle
13449 .update(cx, |mw, window, cx| {
13450 mw.activate_index(0, window, cx);
13451 })
13452 .unwrap();
13453
13454 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13455
13456 // Add a panel to workspace A's right dock and open the dock
13457 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13458 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13459 workspace.add_panel(panel.clone(), window, cx);
13460 workspace
13461 .right_dock()
13462 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13463 panel
13464 });
13465
13466 // Focus the panel through the workspace (matching existing test pattern)
13467 workspace_a.update_in(cx, |workspace, window, cx| {
13468 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13469 });
13470
13471 // Zoom the panel
13472 panel.update_in(cx, |panel, window, cx| {
13473 panel.set_zoomed(true, window, cx);
13474 });
13475
13476 // Verify the panel is zoomed and the dock is open
13477 workspace_a.update_in(cx, |workspace, window, cx| {
13478 assert!(
13479 workspace.right_dock().read(cx).is_open(),
13480 "dock should be open before switch"
13481 );
13482 assert!(
13483 panel.is_zoomed(window, cx),
13484 "panel should be zoomed before switch"
13485 );
13486 assert!(
13487 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13488 "panel should be focused before switch"
13489 );
13490 });
13491
13492 // Switch to workspace B
13493 multi_workspace_handle
13494 .update(cx, |mw, window, cx| {
13495 mw.activate_index(1, window, cx);
13496 })
13497 .unwrap();
13498 cx.run_until_parked();
13499
13500 // Switch back to workspace A
13501 multi_workspace_handle
13502 .update(cx, |mw, window, cx| {
13503 mw.activate_index(0, window, cx);
13504 })
13505 .unwrap();
13506 cx.run_until_parked();
13507
13508 // Verify the panel is still zoomed and the dock is still open
13509 workspace_a.update_in(cx, |workspace, window, cx| {
13510 assert!(
13511 workspace.right_dock().read(cx).is_open(),
13512 "dock should still be open after switching back"
13513 );
13514 assert!(
13515 panel.is_zoomed(window, cx),
13516 "panel should still be zoomed after switching back"
13517 );
13518 });
13519 }
13520
13521 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13522 pane.read(cx)
13523 .items()
13524 .flat_map(|item| {
13525 item.project_paths(cx)
13526 .into_iter()
13527 .map(|path| path.path.display(PathStyle::local()).into_owned())
13528 })
13529 .collect()
13530 }
13531
13532 pub fn init_test(cx: &mut TestAppContext) {
13533 cx.update(|cx| {
13534 let settings_store = SettingsStore::test(cx);
13535 cx.set_global(settings_store);
13536 theme::init(theme::LoadThemes::JustBase, cx);
13537 });
13538 }
13539
13540 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13541 let item = TestProjectItem::new(id, path, cx);
13542 item.update(cx, |item, _| {
13543 item.is_dirty = true;
13544 });
13545 item
13546 }
13547
13548 #[gpui::test]
13549 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13550 cx: &mut gpui::TestAppContext,
13551 ) {
13552 init_test(cx);
13553 let fs = FakeFs::new(cx.executor());
13554
13555 let project = Project::test(fs, [], cx).await;
13556 let (workspace, cx) =
13557 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13558
13559 let panel = workspace.update_in(cx, |workspace, window, cx| {
13560 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13561 workspace.add_panel(panel.clone(), window, cx);
13562 workspace
13563 .right_dock()
13564 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13565 panel
13566 });
13567
13568 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13569 pane.update_in(cx, |pane, window, cx| {
13570 let item = cx.new(TestItem::new);
13571 pane.add_item(Box::new(item), true, true, None, window, cx);
13572 });
13573
13574 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13575 // mirrors the real-world flow and avoids side effects from directly
13576 // focusing the panel while the center pane is active.
13577 workspace.update_in(cx, |workspace, window, cx| {
13578 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13579 });
13580
13581 panel.update_in(cx, |panel, window, cx| {
13582 panel.set_zoomed(true, window, cx);
13583 });
13584
13585 workspace.update_in(cx, |workspace, window, cx| {
13586 assert!(workspace.right_dock().read(cx).is_open());
13587 assert!(panel.is_zoomed(window, cx));
13588 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13589 });
13590
13591 // Simulate a spurious pane::Event::Focus on the center pane while the
13592 // panel still has focus. This mirrors what happens during macOS window
13593 // activation: the center pane fires a focus event even though actual
13594 // focus remains on the dock panel.
13595 pane.update_in(cx, |_, _, cx| {
13596 cx.emit(pane::Event::Focus);
13597 });
13598
13599 // The dock must remain open because the panel had focus at the time the
13600 // event was processed. Before the fix, dock_to_preserve was None for
13601 // panels that don't implement pane(), causing the dock to close.
13602 workspace.update_in(cx, |workspace, window, cx| {
13603 assert!(
13604 workspace.right_dock().read(cx).is_open(),
13605 "Dock should stay open when its zoomed panel (without pane()) still has focus"
13606 );
13607 assert!(panel.is_zoomed(window, cx));
13608 });
13609 }
13610}