1pub mod dock;
2pub mod history_manager;
3pub mod invalid_item_view;
4pub mod item;
5mod modal_layer;
6mod multi_workspace;
7pub mod notifications;
8pub mod pane;
9pub mod pane_group;
10pub mod path_list {
11 pub use util::path_list::{PathList, SerializedPathList};
12}
13mod persistence;
14pub mod searchable;
15mod security_modal;
16pub mod shared_screen;
17use db::smol::future::yield_now;
18pub use shared_screen::SharedScreen;
19mod status_bar;
20pub mod tasks;
21mod theme_preview;
22mod toast_layer;
23mod toolbar;
24pub mod welcome;
25mod workspace_settings;
26
27pub use crate::notifications::NotificationFrame;
28pub use dock::Panel;
29pub use multi_workspace::{
30 DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace, MultiWorkspaceEvent,
31 NewWorkspaceInWindow, NextWorkspaceInWindow, PreviousWorkspaceInWindow,
32 SIDEBAR_RESIZE_HANDLE_SIZE, ToggleWorkspaceSidebar, multi_workspace_enabled,
33};
34pub use path_list::{PathList, SerializedPathList};
35pub use toast_layer::{ToastAction, ToastLayer, ToastView};
36
37use anyhow::{Context as _, Result, anyhow};
38use client::{
39 ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
40 proto::{self, ErrorCode, PanelId, PeerId},
41};
42use collections::{HashMap, HashSet, hash_map};
43use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
44use fs::Fs;
45use futures::{
46 Future, FutureExt, StreamExt,
47 channel::{
48 mpsc::{self, UnboundedReceiver, UnboundedSender},
49 oneshot,
50 },
51 future::{Shared, try_join_all},
52};
53use gpui::{
54 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
55 CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
56 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
57 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
58 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
59 WindowOptions, actions, canvas, point, relative, size, transparent_black,
60};
61pub use history_manager::*;
62pub use item::{
63 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
64 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
65};
66use itertools::Itertools;
67use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
68pub use modal_layer::*;
69use node_runtime::NodeRuntime;
70use notifications::{
71 DetachAndPromptErr, Notifications, dismiss_app_notification,
72 simple_message_notification::MessageNotification,
73};
74pub use pane::*;
75pub use pane_group::{
76 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
77 SplitDirection,
78};
79use persistence::{DB, SerializedWindowBounds, model::SerializedWorkspace};
80pub use persistence::{
81 DB as WORKSPACE_DB, WorkspaceDb, delete_unloaded_items,
82 model::{
83 DockStructure, ItemId, MultiWorkspaceId, SerializedMultiWorkspace,
84 SerializedWorkspaceLocation, SessionWorkspace,
85 },
86 read_serialized_multi_workspaces,
87};
88use postage::stream::Stream;
89use project::{
90 DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
91 WorktreeSettings,
92 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
93 project_settings::ProjectSettings,
94 toolchain_store::ToolchainStoreEvent,
95 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
96};
97use remote::{
98 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
99 remote_client::ConnectionIdentifier,
100};
101use schemars::JsonSchema;
102use serde::Deserialize;
103use session::AppSession;
104use settings::{
105 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
106};
107
108use sqlez::{
109 bindable::{Bind, Column, StaticColumnCount},
110 statement::Statement,
111};
112use status_bar::StatusBar;
113pub use status_bar::StatusItemView;
114use std::{
115 any::TypeId,
116 borrow::Cow,
117 cell::RefCell,
118 cmp,
119 collections::VecDeque,
120 env,
121 hash::Hash,
122 path::{Path, PathBuf},
123 process::ExitStatus,
124 rc::Rc,
125 sync::{
126 Arc, LazyLock, Weak,
127 atomic::{AtomicBool, AtomicUsize},
128 },
129 time::Duration,
130};
131use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
132use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
133pub use toolbar::{
134 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
135};
136pub use ui;
137use ui::{Window, prelude::*};
138use util::{
139 ResultExt, TryFutureExt,
140 paths::{PathStyle, SanitizedPath},
141 rel_path::RelPath,
142 serde::default_true,
143};
144use uuid::Uuid;
145pub use workspace_settings::{
146 AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
147 WorkspaceSettings,
148};
149use zed_actions::{Spawn, feedback::FileBugReport};
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 status_bar_visible(&self, cx: &App) -> bool {
2158 StatusBarSettings::get_global(cx).show
2159 }
2160
2161 pub fn app_state(&self) -> &Arc<AppState> {
2162 &self.app_state
2163 }
2164
2165 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2166 self._panels_task = Some(task);
2167 }
2168
2169 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2170 self._panels_task.take()
2171 }
2172
2173 pub fn user_store(&self) -> &Entity<UserStore> {
2174 &self.app_state.user_store
2175 }
2176
2177 pub fn project(&self) -> &Entity<Project> {
2178 &self.project
2179 }
2180
2181 pub fn path_style(&self, cx: &App) -> PathStyle {
2182 self.project.read(cx).path_style(cx)
2183 }
2184
2185 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2186 let mut history: HashMap<EntityId, usize> = HashMap::default();
2187
2188 for pane_handle in &self.panes {
2189 let pane = pane_handle.read(cx);
2190
2191 for entry in pane.activation_history() {
2192 history.insert(
2193 entry.entity_id,
2194 history
2195 .get(&entry.entity_id)
2196 .cloned()
2197 .unwrap_or(0)
2198 .max(entry.timestamp),
2199 );
2200 }
2201 }
2202
2203 history
2204 }
2205
2206 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2207 let mut recent_item: Option<Entity<T>> = None;
2208 let mut recent_timestamp = 0;
2209 for pane_handle in &self.panes {
2210 let pane = pane_handle.read(cx);
2211 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2212 pane.items().map(|item| (item.item_id(), item)).collect();
2213 for entry in pane.activation_history() {
2214 if entry.timestamp > recent_timestamp
2215 && let Some(&item) = item_map.get(&entry.entity_id)
2216 && let Some(typed_item) = item.act_as::<T>(cx)
2217 {
2218 recent_timestamp = entry.timestamp;
2219 recent_item = Some(typed_item);
2220 }
2221 }
2222 }
2223 recent_item
2224 }
2225
2226 pub fn recent_navigation_history_iter(
2227 &self,
2228 cx: &App,
2229 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2230 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2231 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2232
2233 for pane in &self.panes {
2234 let pane = pane.read(cx);
2235
2236 pane.nav_history()
2237 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2238 if let Some(fs_path) = &fs_path {
2239 abs_paths_opened
2240 .entry(fs_path.clone())
2241 .or_default()
2242 .insert(project_path.clone());
2243 }
2244 let timestamp = entry.timestamp;
2245 match history.entry(project_path) {
2246 hash_map::Entry::Occupied(mut entry) => {
2247 let (_, old_timestamp) = entry.get();
2248 if ×tamp > old_timestamp {
2249 entry.insert((fs_path, timestamp));
2250 }
2251 }
2252 hash_map::Entry::Vacant(entry) => {
2253 entry.insert((fs_path, timestamp));
2254 }
2255 }
2256 });
2257
2258 if let Some(item) = pane.active_item()
2259 && let Some(project_path) = item.project_path(cx)
2260 {
2261 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2262
2263 if let Some(fs_path) = &fs_path {
2264 abs_paths_opened
2265 .entry(fs_path.clone())
2266 .or_default()
2267 .insert(project_path.clone());
2268 }
2269
2270 history.insert(project_path, (fs_path, std::usize::MAX));
2271 }
2272 }
2273
2274 history
2275 .into_iter()
2276 .sorted_by_key(|(_, (_, order))| *order)
2277 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2278 .rev()
2279 .filter(move |(history_path, abs_path)| {
2280 let latest_project_path_opened = abs_path
2281 .as_ref()
2282 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2283 .and_then(|project_paths| {
2284 project_paths
2285 .iter()
2286 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2287 });
2288
2289 latest_project_path_opened.is_none_or(|path| path == history_path)
2290 })
2291 }
2292
2293 pub fn recent_navigation_history(
2294 &self,
2295 limit: Option<usize>,
2296 cx: &App,
2297 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2298 self.recent_navigation_history_iter(cx)
2299 .take(limit.unwrap_or(usize::MAX))
2300 .collect()
2301 }
2302
2303 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2304 for pane in &self.panes {
2305 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2306 }
2307 }
2308
2309 fn navigate_history(
2310 &mut self,
2311 pane: WeakEntity<Pane>,
2312 mode: NavigationMode,
2313 window: &mut Window,
2314 cx: &mut Context<Workspace>,
2315 ) -> Task<Result<()>> {
2316 self.navigate_history_impl(
2317 pane,
2318 mode,
2319 window,
2320 &mut |history, cx| history.pop(mode, cx),
2321 cx,
2322 )
2323 }
2324
2325 fn navigate_tag_history(
2326 &mut self,
2327 pane: WeakEntity<Pane>,
2328 mode: TagNavigationMode,
2329 window: &mut Window,
2330 cx: &mut Context<Workspace>,
2331 ) -> Task<Result<()>> {
2332 self.navigate_history_impl(
2333 pane,
2334 NavigationMode::Normal,
2335 window,
2336 &mut |history, _cx| history.pop_tag(mode),
2337 cx,
2338 )
2339 }
2340
2341 fn navigate_history_impl(
2342 &mut self,
2343 pane: WeakEntity<Pane>,
2344 mode: NavigationMode,
2345 window: &mut Window,
2346 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2347 cx: &mut Context<Workspace>,
2348 ) -> Task<Result<()>> {
2349 let to_load = if let Some(pane) = pane.upgrade() {
2350 pane.update(cx, |pane, cx| {
2351 window.focus(&pane.focus_handle(cx), cx);
2352 loop {
2353 // Retrieve the weak item handle from the history.
2354 let entry = cb(pane.nav_history_mut(), cx)?;
2355
2356 // If the item is still present in this pane, then activate it.
2357 if let Some(index) = entry
2358 .item
2359 .upgrade()
2360 .and_then(|v| pane.index_for_item(v.as_ref()))
2361 {
2362 let prev_active_item_index = pane.active_item_index();
2363 pane.nav_history_mut().set_mode(mode);
2364 pane.activate_item(index, true, true, window, cx);
2365 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2366
2367 let mut navigated = prev_active_item_index != pane.active_item_index();
2368 if let Some(data) = entry.data {
2369 navigated |= pane.active_item()?.navigate(data, window, cx);
2370 }
2371
2372 if navigated {
2373 break None;
2374 }
2375 } else {
2376 // If the item is no longer present in this pane, then retrieve its
2377 // path info in order to reopen it.
2378 break pane
2379 .nav_history()
2380 .path_for_item(entry.item.id())
2381 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2382 }
2383 }
2384 })
2385 } else {
2386 None
2387 };
2388
2389 if let Some((project_path, abs_path, entry)) = to_load {
2390 // If the item was no longer present, then load it again from its previous path, first try the local path
2391 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2392
2393 cx.spawn_in(window, async move |workspace, cx| {
2394 let open_by_project_path = open_by_project_path.await;
2395 let mut navigated = false;
2396 match open_by_project_path
2397 .with_context(|| format!("Navigating to {project_path:?}"))
2398 {
2399 Ok((project_entry_id, build_item)) => {
2400 let prev_active_item_id = pane.update(cx, |pane, _| {
2401 pane.nav_history_mut().set_mode(mode);
2402 pane.active_item().map(|p| p.item_id())
2403 })?;
2404
2405 pane.update_in(cx, |pane, window, cx| {
2406 let item = pane.open_item(
2407 project_entry_id,
2408 project_path,
2409 true,
2410 entry.is_preview,
2411 true,
2412 None,
2413 window, cx,
2414 build_item,
2415 );
2416 navigated |= Some(item.item_id()) != prev_active_item_id;
2417 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2418 if let Some(data) = entry.data {
2419 navigated |= item.navigate(data, window, cx);
2420 }
2421 })?;
2422 }
2423 Err(open_by_project_path_e) => {
2424 // Fall back to opening by abs path, in case an external file was opened and closed,
2425 // and its worktree is now dropped
2426 if let Some(abs_path) = abs_path {
2427 let prev_active_item_id = pane.update(cx, |pane, _| {
2428 pane.nav_history_mut().set_mode(mode);
2429 pane.active_item().map(|p| p.item_id())
2430 })?;
2431 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2432 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2433 })?;
2434 match open_by_abs_path
2435 .await
2436 .with_context(|| format!("Navigating to {abs_path:?}"))
2437 {
2438 Ok(item) => {
2439 pane.update_in(cx, |pane, window, cx| {
2440 navigated |= Some(item.item_id()) != prev_active_item_id;
2441 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2442 if let Some(data) = entry.data {
2443 navigated |= item.navigate(data, window, cx);
2444 }
2445 })?;
2446 }
2447 Err(open_by_abs_path_e) => {
2448 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2449 }
2450 }
2451 }
2452 }
2453 }
2454
2455 if !navigated {
2456 workspace
2457 .update_in(cx, |workspace, window, cx| {
2458 Self::navigate_history(workspace, pane, mode, window, cx)
2459 })?
2460 .await?;
2461 }
2462
2463 Ok(())
2464 })
2465 } else {
2466 Task::ready(Ok(()))
2467 }
2468 }
2469
2470 pub fn go_back(
2471 &mut self,
2472 pane: WeakEntity<Pane>,
2473 window: &mut Window,
2474 cx: &mut Context<Workspace>,
2475 ) -> Task<Result<()>> {
2476 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2477 }
2478
2479 pub fn go_forward(
2480 &mut self,
2481 pane: WeakEntity<Pane>,
2482 window: &mut Window,
2483 cx: &mut Context<Workspace>,
2484 ) -> Task<Result<()>> {
2485 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2486 }
2487
2488 pub fn reopen_closed_item(
2489 &mut self,
2490 window: &mut Window,
2491 cx: &mut Context<Workspace>,
2492 ) -> Task<Result<()>> {
2493 self.navigate_history(
2494 self.active_pane().downgrade(),
2495 NavigationMode::ReopeningClosedItem,
2496 window,
2497 cx,
2498 )
2499 }
2500
2501 pub fn client(&self) -> &Arc<Client> {
2502 &self.app_state.client
2503 }
2504
2505 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2506 self.titlebar_item = Some(item);
2507 cx.notify();
2508 }
2509
2510 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2511 self.on_prompt_for_new_path = Some(prompt)
2512 }
2513
2514 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2515 self.on_prompt_for_open_path = Some(prompt)
2516 }
2517
2518 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2519 self.terminal_provider = Some(Box::new(provider));
2520 }
2521
2522 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2523 self.debugger_provider = Some(Arc::new(provider));
2524 }
2525
2526 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2527 self.debugger_provider.clone()
2528 }
2529
2530 pub fn prompt_for_open_path(
2531 &mut self,
2532 path_prompt_options: PathPromptOptions,
2533 lister: DirectoryLister,
2534 window: &mut Window,
2535 cx: &mut Context<Self>,
2536 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2537 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2538 let prompt = self.on_prompt_for_open_path.take().unwrap();
2539 let rx = prompt(self, lister, window, cx);
2540 self.on_prompt_for_open_path = Some(prompt);
2541 rx
2542 } else {
2543 let (tx, rx) = oneshot::channel();
2544 let abs_path = cx.prompt_for_paths(path_prompt_options);
2545
2546 cx.spawn_in(window, async move |workspace, cx| {
2547 let Ok(result) = abs_path.await else {
2548 return Ok(());
2549 };
2550
2551 match result {
2552 Ok(result) => {
2553 tx.send(result).ok();
2554 }
2555 Err(err) => {
2556 let rx = workspace.update_in(cx, |workspace, window, cx| {
2557 workspace.show_portal_error(err.to_string(), cx);
2558 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2559 let rx = prompt(workspace, lister, window, cx);
2560 workspace.on_prompt_for_open_path = Some(prompt);
2561 rx
2562 })?;
2563 if let Ok(path) = rx.await {
2564 tx.send(path).ok();
2565 }
2566 }
2567 };
2568 anyhow::Ok(())
2569 })
2570 .detach();
2571
2572 rx
2573 }
2574 }
2575
2576 pub fn prompt_for_new_path(
2577 &mut self,
2578 lister: DirectoryLister,
2579 suggested_name: Option<String>,
2580 window: &mut Window,
2581 cx: &mut Context<Self>,
2582 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2583 if self.project.read(cx).is_via_collab()
2584 || self.project.read(cx).is_via_remote_server()
2585 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2586 {
2587 let prompt = self.on_prompt_for_new_path.take().unwrap();
2588 let rx = prompt(self, lister, suggested_name, window, cx);
2589 self.on_prompt_for_new_path = Some(prompt);
2590 return rx;
2591 }
2592
2593 let (tx, rx) = oneshot::channel();
2594 cx.spawn_in(window, async move |workspace, cx| {
2595 let abs_path = workspace.update(cx, |workspace, cx| {
2596 let relative_to = workspace
2597 .most_recent_active_path(cx)
2598 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2599 .or_else(|| {
2600 let project = workspace.project.read(cx);
2601 project.visible_worktrees(cx).find_map(|worktree| {
2602 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2603 })
2604 })
2605 .or_else(std::env::home_dir)
2606 .unwrap_or_else(|| PathBuf::from(""));
2607 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2608 })?;
2609 let abs_path = match abs_path.await? {
2610 Ok(path) => path,
2611 Err(err) => {
2612 let rx = workspace.update_in(cx, |workspace, window, cx| {
2613 workspace.show_portal_error(err.to_string(), cx);
2614
2615 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2616 let rx = prompt(workspace, lister, suggested_name, window, cx);
2617 workspace.on_prompt_for_new_path = Some(prompt);
2618 rx
2619 })?;
2620 if let Ok(path) = rx.await {
2621 tx.send(path).ok();
2622 }
2623 return anyhow::Ok(());
2624 }
2625 };
2626
2627 tx.send(abs_path.map(|path| vec![path])).ok();
2628 anyhow::Ok(())
2629 })
2630 .detach();
2631
2632 rx
2633 }
2634
2635 pub fn titlebar_item(&self) -> Option<AnyView> {
2636 self.titlebar_item.clone()
2637 }
2638
2639 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2640 /// When set, git-related operations should use this worktree instead of deriving
2641 /// the active worktree from the focused file.
2642 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2643 self.active_worktree_override
2644 }
2645
2646 pub fn set_active_worktree_override(
2647 &mut self,
2648 worktree_id: Option<WorktreeId>,
2649 cx: &mut Context<Self>,
2650 ) {
2651 self.active_worktree_override = worktree_id;
2652 cx.notify();
2653 }
2654
2655 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2656 self.active_worktree_override = None;
2657 cx.notify();
2658 }
2659
2660 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2661 ///
2662 /// If the given workspace has a local project, then it will be passed
2663 /// to the callback. Otherwise, a new empty window will be created.
2664 pub fn with_local_workspace<T, F>(
2665 &mut self,
2666 window: &mut Window,
2667 cx: &mut Context<Self>,
2668 callback: F,
2669 ) -> Task<Result<T>>
2670 where
2671 T: 'static,
2672 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2673 {
2674 if self.project.read(cx).is_local() {
2675 Task::ready(Ok(callback(self, window, cx)))
2676 } else {
2677 let env = self.project.read(cx).cli_environment(cx);
2678 let task = Self::new_local(
2679 Vec::new(),
2680 self.app_state.clone(),
2681 None,
2682 env,
2683 None,
2684 true,
2685 cx,
2686 );
2687 cx.spawn_in(window, async move |_vh, cx| {
2688 let (multi_workspace_window, _) = task.await?;
2689 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2690 let workspace = multi_workspace.workspace().clone();
2691 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2692 })
2693 })
2694 }
2695 }
2696
2697 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2698 ///
2699 /// If the given workspace has a local project, then it will be passed
2700 /// to the callback. Otherwise, a new empty window will be created.
2701 pub fn with_local_or_wsl_workspace<T, F>(
2702 &mut self,
2703 window: &mut Window,
2704 cx: &mut Context<Self>,
2705 callback: F,
2706 ) -> Task<Result<T>>
2707 where
2708 T: 'static,
2709 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2710 {
2711 let project = self.project.read(cx);
2712 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
2713 Task::ready(Ok(callback(self, window, cx)))
2714 } else {
2715 let env = self.project.read(cx).cli_environment(cx);
2716 let task = Self::new_local(
2717 Vec::new(),
2718 self.app_state.clone(),
2719 None,
2720 env,
2721 None,
2722 true,
2723 cx,
2724 );
2725 cx.spawn_in(window, async move |_vh, cx| {
2726 let (multi_workspace_window, _) = task.await?;
2727 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2728 let workspace = multi_workspace.workspace().clone();
2729 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2730 })
2731 })
2732 }
2733 }
2734
2735 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2736 self.project.read(cx).worktrees(cx)
2737 }
2738
2739 pub fn visible_worktrees<'a>(
2740 &self,
2741 cx: &'a App,
2742 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2743 self.project.read(cx).visible_worktrees(cx)
2744 }
2745
2746 #[cfg(any(test, feature = "test-support"))]
2747 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
2748 let futures = self
2749 .worktrees(cx)
2750 .filter_map(|worktree| worktree.read(cx).as_local())
2751 .map(|worktree| worktree.scan_complete())
2752 .collect::<Vec<_>>();
2753 async move {
2754 for future in futures {
2755 future.await;
2756 }
2757 }
2758 }
2759
2760 pub fn close_global(cx: &mut App) {
2761 cx.defer(|cx| {
2762 cx.windows().iter().find(|window| {
2763 window
2764 .update(cx, |_, window, _| {
2765 if window.is_window_active() {
2766 //This can only get called when the window's project connection has been lost
2767 //so we don't need to prompt the user for anything and instead just close the window
2768 window.remove_window();
2769 true
2770 } else {
2771 false
2772 }
2773 })
2774 .unwrap_or(false)
2775 });
2776 });
2777 }
2778
2779 pub fn move_focused_panel_to_next_position(
2780 &mut self,
2781 _: &MoveFocusedPanelToNextPosition,
2782 window: &mut Window,
2783 cx: &mut Context<Self>,
2784 ) {
2785 let docks = self.all_docks();
2786 let active_dock = docks
2787 .into_iter()
2788 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
2789
2790 if let Some(dock) = active_dock {
2791 dock.update(cx, |dock, cx| {
2792 let active_panel = dock
2793 .active_panel()
2794 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
2795
2796 if let Some(panel) = active_panel {
2797 panel.move_to_next_position(window, cx);
2798 }
2799 })
2800 }
2801 }
2802
2803 pub fn prepare_to_close(
2804 &mut self,
2805 close_intent: CloseIntent,
2806 window: &mut Window,
2807 cx: &mut Context<Self>,
2808 ) -> Task<Result<bool>> {
2809 let active_call = self.active_global_call();
2810
2811 cx.spawn_in(window, async move |this, cx| {
2812 this.update(cx, |this, _| {
2813 if close_intent == CloseIntent::CloseWindow {
2814 this.removing = true;
2815 }
2816 })?;
2817
2818 let workspace_count = cx.update(|_window, cx| {
2819 cx.windows()
2820 .iter()
2821 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
2822 .count()
2823 })?;
2824
2825 #[cfg(target_os = "macos")]
2826 let save_last_workspace = false;
2827
2828 // On Linux and Windows, closing the last window should restore the last workspace.
2829 #[cfg(not(target_os = "macos"))]
2830 let save_last_workspace = {
2831 let remaining_workspaces = cx.update(|_window, cx| {
2832 cx.windows()
2833 .iter()
2834 .filter_map(|window| window.downcast::<MultiWorkspace>())
2835 .filter_map(|multi_workspace| {
2836 multi_workspace
2837 .update(cx, |multi_workspace, _, cx| {
2838 multi_workspace.workspace().read(cx).removing
2839 })
2840 .ok()
2841 })
2842 .filter(|removing| !removing)
2843 .count()
2844 })?;
2845
2846 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
2847 };
2848
2849 if let Some(active_call) = active_call
2850 && workspace_count == 1
2851 && cx
2852 .update(|_window, cx| active_call.0.is_in_room(cx))
2853 .unwrap_or(false)
2854 {
2855 if close_intent == CloseIntent::CloseWindow {
2856 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
2857 let answer = cx.update(|window, cx| {
2858 window.prompt(
2859 PromptLevel::Warning,
2860 "Do you want to leave the current call?",
2861 None,
2862 &["Close window and hang up", "Cancel"],
2863 cx,
2864 )
2865 })?;
2866
2867 if answer.await.log_err() == Some(1) {
2868 return anyhow::Ok(false);
2869 } else {
2870 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
2871 task.await.log_err();
2872 }
2873 }
2874 }
2875 if close_intent == CloseIntent::ReplaceWindow {
2876 _ = cx.update(|_window, cx| {
2877 let multi_workspace = cx
2878 .windows()
2879 .iter()
2880 .filter_map(|window| window.downcast::<MultiWorkspace>())
2881 .next()
2882 .unwrap();
2883 let project = multi_workspace
2884 .read(cx)?
2885 .workspace()
2886 .read(cx)
2887 .project
2888 .clone();
2889 if project.read(cx).is_shared() {
2890 active_call.0.unshare_project(project, cx)?;
2891 }
2892 Ok::<_, anyhow::Error>(())
2893 });
2894 }
2895 }
2896
2897 let save_result = this
2898 .update_in(cx, |this, window, cx| {
2899 this.save_all_internal(SaveIntent::Close, window, cx)
2900 })?
2901 .await;
2902
2903 // If we're not quitting, but closing, we remove the workspace from
2904 // the current session.
2905 if close_intent != CloseIntent::Quit
2906 && !save_last_workspace
2907 && save_result.as_ref().is_ok_and(|&res| res)
2908 {
2909 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
2910 .await;
2911 }
2912
2913 save_result
2914 })
2915 }
2916
2917 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
2918 self.save_all_internal(
2919 action.save_intent.unwrap_or(SaveIntent::SaveAll),
2920 window,
2921 cx,
2922 )
2923 .detach_and_log_err(cx);
2924 }
2925
2926 fn send_keystrokes(
2927 &mut self,
2928 action: &SendKeystrokes,
2929 window: &mut Window,
2930 cx: &mut Context<Self>,
2931 ) {
2932 let keystrokes: Vec<Keystroke> = action
2933 .0
2934 .split(' ')
2935 .flat_map(|k| Keystroke::parse(k).log_err())
2936 .map(|k| {
2937 cx.keyboard_mapper()
2938 .map_key_equivalent(k, false)
2939 .inner()
2940 .clone()
2941 })
2942 .collect();
2943 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
2944 }
2945
2946 pub fn send_keystrokes_impl(
2947 &mut self,
2948 keystrokes: Vec<Keystroke>,
2949 window: &mut Window,
2950 cx: &mut Context<Self>,
2951 ) -> Shared<Task<()>> {
2952 let mut state = self.dispatching_keystrokes.borrow_mut();
2953 if !state.dispatched.insert(keystrokes.clone()) {
2954 cx.propagate();
2955 return state.task.clone().unwrap();
2956 }
2957
2958 state.queue.extend(keystrokes);
2959
2960 let keystrokes = self.dispatching_keystrokes.clone();
2961 if state.task.is_none() {
2962 state.task = Some(
2963 window
2964 .spawn(cx, async move |cx| {
2965 // limit to 100 keystrokes to avoid infinite recursion.
2966 for _ in 0..100 {
2967 let keystroke = {
2968 let mut state = keystrokes.borrow_mut();
2969 let Some(keystroke) = state.queue.pop_front() else {
2970 state.dispatched.clear();
2971 state.task.take();
2972 return;
2973 };
2974 keystroke
2975 };
2976 cx.update(|window, cx| {
2977 let focused = window.focused(cx);
2978 window.dispatch_keystroke(keystroke.clone(), cx);
2979 if window.focused(cx) != focused {
2980 // dispatch_keystroke may cause the focus to change.
2981 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
2982 // And we need that to happen before the next keystroke to keep vim mode happy...
2983 // (Note that the tests always do this implicitly, so you must manually test with something like:
2984 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
2985 // )
2986 window.draw(cx).clear();
2987 }
2988 })
2989 .ok();
2990
2991 // Yield between synthetic keystrokes so deferred focus and
2992 // other effects can settle before dispatching the next key.
2993 yield_now().await;
2994 }
2995
2996 *keystrokes.borrow_mut() = Default::default();
2997 log::error!("over 100 keystrokes passed to send_keystrokes");
2998 })
2999 .shared(),
3000 );
3001 }
3002 state.task.clone().unwrap()
3003 }
3004
3005 fn save_all_internal(
3006 &mut self,
3007 mut save_intent: SaveIntent,
3008 window: &mut Window,
3009 cx: &mut Context<Self>,
3010 ) -> Task<Result<bool>> {
3011 if self.project.read(cx).is_disconnected(cx) {
3012 return Task::ready(Ok(true));
3013 }
3014 let dirty_items = self
3015 .panes
3016 .iter()
3017 .flat_map(|pane| {
3018 pane.read(cx).items().filter_map(|item| {
3019 if item.is_dirty(cx) {
3020 item.tab_content_text(0, cx);
3021 Some((pane.downgrade(), item.boxed_clone()))
3022 } else {
3023 None
3024 }
3025 })
3026 })
3027 .collect::<Vec<_>>();
3028
3029 let project = self.project.clone();
3030 cx.spawn_in(window, async move |workspace, cx| {
3031 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3032 let (serialize_tasks, remaining_dirty_items) =
3033 workspace.update_in(cx, |workspace, window, cx| {
3034 let mut remaining_dirty_items = Vec::new();
3035 let mut serialize_tasks = Vec::new();
3036 for (pane, item) in dirty_items {
3037 if let Some(task) = item
3038 .to_serializable_item_handle(cx)
3039 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3040 {
3041 serialize_tasks.push(task);
3042 } else {
3043 remaining_dirty_items.push((pane, item));
3044 }
3045 }
3046 (serialize_tasks, remaining_dirty_items)
3047 })?;
3048
3049 futures::future::try_join_all(serialize_tasks).await?;
3050
3051 if !remaining_dirty_items.is_empty() {
3052 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3053 }
3054
3055 if remaining_dirty_items.len() > 1 {
3056 let answer = workspace.update_in(cx, |_, window, cx| {
3057 let detail = Pane::file_names_for_prompt(
3058 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3059 cx,
3060 );
3061 window.prompt(
3062 PromptLevel::Warning,
3063 "Do you want to save all changes in the following files?",
3064 Some(&detail),
3065 &["Save all", "Discard all", "Cancel"],
3066 cx,
3067 )
3068 })?;
3069 match answer.await.log_err() {
3070 Some(0) => save_intent = SaveIntent::SaveAll,
3071 Some(1) => save_intent = SaveIntent::Skip,
3072 Some(2) => return Ok(false),
3073 _ => {}
3074 }
3075 }
3076
3077 remaining_dirty_items
3078 } else {
3079 dirty_items
3080 };
3081
3082 for (pane, item) in dirty_items {
3083 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3084 (
3085 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3086 item.project_entry_ids(cx),
3087 )
3088 })?;
3089 if (singleton || !project_entry_ids.is_empty())
3090 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3091 {
3092 return Ok(false);
3093 }
3094 }
3095 Ok(true)
3096 })
3097 }
3098
3099 pub fn open_workspace_for_paths(
3100 &mut self,
3101 replace_current_window: bool,
3102 paths: Vec<PathBuf>,
3103 window: &mut Window,
3104 cx: &mut Context<Self>,
3105 ) -> Task<Result<()>> {
3106 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
3107 let is_remote = self.project.read(cx).is_via_collab();
3108 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3109 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3110
3111 let window_to_replace = if replace_current_window {
3112 window_handle
3113 } else if is_remote || has_worktree || has_dirty_items {
3114 None
3115 } else {
3116 window_handle
3117 };
3118 let app_state = self.app_state.clone();
3119
3120 cx.spawn(async move |_, cx| {
3121 cx.update(|cx| {
3122 open_paths(
3123 &paths,
3124 app_state,
3125 OpenOptions {
3126 replace_window: window_to_replace,
3127 ..Default::default()
3128 },
3129 cx,
3130 )
3131 })
3132 .await?;
3133 Ok(())
3134 })
3135 }
3136
3137 #[allow(clippy::type_complexity)]
3138 pub fn open_paths(
3139 &mut self,
3140 mut abs_paths: Vec<PathBuf>,
3141 options: OpenOptions,
3142 pane: Option<WeakEntity<Pane>>,
3143 window: &mut Window,
3144 cx: &mut Context<Self>,
3145 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3146 let fs = self.app_state.fs.clone();
3147
3148 let caller_ordered_abs_paths = abs_paths.clone();
3149
3150 // Sort the paths to ensure we add worktrees for parents before their children.
3151 abs_paths.sort_unstable();
3152 cx.spawn_in(window, async move |this, cx| {
3153 let mut tasks = Vec::with_capacity(abs_paths.len());
3154
3155 for abs_path in &abs_paths {
3156 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3157 OpenVisible::All => Some(true),
3158 OpenVisible::None => Some(false),
3159 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3160 Some(Some(metadata)) => Some(!metadata.is_dir),
3161 Some(None) => Some(true),
3162 None => None,
3163 },
3164 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3165 Some(Some(metadata)) => Some(metadata.is_dir),
3166 Some(None) => Some(false),
3167 None => None,
3168 },
3169 };
3170 let project_path = match visible {
3171 Some(visible) => match this
3172 .update(cx, |this, cx| {
3173 Workspace::project_path_for_path(
3174 this.project.clone(),
3175 abs_path,
3176 visible,
3177 cx,
3178 )
3179 })
3180 .log_err()
3181 {
3182 Some(project_path) => project_path.await.log_err(),
3183 None => None,
3184 },
3185 None => None,
3186 };
3187
3188 let this = this.clone();
3189 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3190 let fs = fs.clone();
3191 let pane = pane.clone();
3192 let task = cx.spawn(async move |cx| {
3193 let (_worktree, project_path) = project_path?;
3194 if fs.is_dir(&abs_path).await {
3195 // Opening a directory should not race to update the active entry.
3196 // We'll select/reveal a deterministic final entry after all paths finish opening.
3197 None
3198 } else {
3199 Some(
3200 this.update_in(cx, |this, window, cx| {
3201 this.open_path(
3202 project_path,
3203 pane,
3204 options.focus.unwrap_or(true),
3205 window,
3206 cx,
3207 )
3208 })
3209 .ok()?
3210 .await,
3211 )
3212 }
3213 });
3214 tasks.push(task);
3215 }
3216
3217 let results = futures::future::join_all(tasks).await;
3218
3219 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3220 let mut winner: Option<(PathBuf, bool)> = None;
3221 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3222 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3223 if !metadata.is_dir {
3224 winner = Some((abs_path, false));
3225 break;
3226 }
3227 if winner.is_none() {
3228 winner = Some((abs_path, true));
3229 }
3230 } else if winner.is_none() {
3231 winner = Some((abs_path, false));
3232 }
3233 }
3234
3235 // Compute the winner entry id on the foreground thread and emit once, after all
3236 // paths finish opening. This avoids races between concurrently-opening paths
3237 // (directories in particular) and makes the resulting project panel selection
3238 // deterministic.
3239 if let Some((winner_abs_path, winner_is_dir)) = winner {
3240 'emit_winner: {
3241 let winner_abs_path: Arc<Path> =
3242 SanitizedPath::new(&winner_abs_path).as_path().into();
3243
3244 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3245 OpenVisible::All => true,
3246 OpenVisible::None => false,
3247 OpenVisible::OnlyFiles => !winner_is_dir,
3248 OpenVisible::OnlyDirectories => winner_is_dir,
3249 };
3250
3251 let Some(worktree_task) = this
3252 .update(cx, |workspace, cx| {
3253 workspace.project.update(cx, |project, cx| {
3254 project.find_or_create_worktree(
3255 winner_abs_path.as_ref(),
3256 visible,
3257 cx,
3258 )
3259 })
3260 })
3261 .ok()
3262 else {
3263 break 'emit_winner;
3264 };
3265
3266 let Ok((worktree, _)) = worktree_task.await else {
3267 break 'emit_winner;
3268 };
3269
3270 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3271 let worktree = worktree.read(cx);
3272 let worktree_abs_path = worktree.abs_path();
3273 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3274 worktree.root_entry()
3275 } else {
3276 winner_abs_path
3277 .strip_prefix(worktree_abs_path.as_ref())
3278 .ok()
3279 .and_then(|relative_path| {
3280 let relative_path =
3281 RelPath::new(relative_path, PathStyle::local())
3282 .log_err()?;
3283 worktree.entry_for_path(&relative_path)
3284 })
3285 }?;
3286 Some(entry.id)
3287 }) else {
3288 break 'emit_winner;
3289 };
3290
3291 this.update(cx, |workspace, cx| {
3292 workspace.project.update(cx, |_, cx| {
3293 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3294 });
3295 })
3296 .ok();
3297 }
3298 }
3299
3300 results
3301 })
3302 }
3303
3304 pub fn open_resolved_path(
3305 &mut self,
3306 path: ResolvedPath,
3307 window: &mut Window,
3308 cx: &mut Context<Self>,
3309 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3310 match path {
3311 ResolvedPath::ProjectPath { project_path, .. } => {
3312 self.open_path(project_path, None, true, window, cx)
3313 }
3314 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3315 PathBuf::from(path),
3316 OpenOptions {
3317 visible: Some(OpenVisible::None),
3318 ..Default::default()
3319 },
3320 window,
3321 cx,
3322 ),
3323 }
3324 }
3325
3326 pub fn absolute_path_of_worktree(
3327 &self,
3328 worktree_id: WorktreeId,
3329 cx: &mut Context<Self>,
3330 ) -> Option<PathBuf> {
3331 self.project
3332 .read(cx)
3333 .worktree_for_id(worktree_id, cx)
3334 // TODO: use `abs_path` or `root_dir`
3335 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3336 }
3337
3338 fn add_folder_to_project(
3339 &mut self,
3340 _: &AddFolderToProject,
3341 window: &mut Window,
3342 cx: &mut Context<Self>,
3343 ) {
3344 let project = self.project.read(cx);
3345 if project.is_via_collab() {
3346 self.show_error(
3347 &anyhow!("You cannot add folders to someone else's project"),
3348 cx,
3349 );
3350 return;
3351 }
3352 let paths = self.prompt_for_open_path(
3353 PathPromptOptions {
3354 files: false,
3355 directories: true,
3356 multiple: true,
3357 prompt: None,
3358 },
3359 DirectoryLister::Project(self.project.clone()),
3360 window,
3361 cx,
3362 );
3363 cx.spawn_in(window, async move |this, cx| {
3364 if let Some(paths) = paths.await.log_err().flatten() {
3365 let results = this
3366 .update_in(cx, |this, window, cx| {
3367 this.open_paths(
3368 paths,
3369 OpenOptions {
3370 visible: Some(OpenVisible::All),
3371 ..Default::default()
3372 },
3373 None,
3374 window,
3375 cx,
3376 )
3377 })?
3378 .await;
3379 for result in results.into_iter().flatten() {
3380 result.log_err();
3381 }
3382 }
3383 anyhow::Ok(())
3384 })
3385 .detach_and_log_err(cx);
3386 }
3387
3388 pub fn project_path_for_path(
3389 project: Entity<Project>,
3390 abs_path: &Path,
3391 visible: bool,
3392 cx: &mut App,
3393 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3394 let entry = project.update(cx, |project, cx| {
3395 project.find_or_create_worktree(abs_path, visible, cx)
3396 });
3397 cx.spawn(async move |cx| {
3398 let (worktree, path) = entry.await?;
3399 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3400 Ok((worktree, ProjectPath { worktree_id, path }))
3401 })
3402 }
3403
3404 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3405 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3406 }
3407
3408 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3409 self.items_of_type(cx).max_by_key(|item| item.item_id())
3410 }
3411
3412 pub fn items_of_type<'a, T: Item>(
3413 &'a self,
3414 cx: &'a App,
3415 ) -> impl 'a + Iterator<Item = Entity<T>> {
3416 self.panes
3417 .iter()
3418 .flat_map(|pane| pane.read(cx).items_of_type())
3419 }
3420
3421 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3422 self.active_pane().read(cx).active_item()
3423 }
3424
3425 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3426 let item = self.active_item(cx)?;
3427 item.to_any_view().downcast::<I>().ok()
3428 }
3429
3430 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3431 self.active_item(cx).and_then(|item| item.project_path(cx))
3432 }
3433
3434 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3435 self.recent_navigation_history_iter(cx)
3436 .filter_map(|(path, abs_path)| {
3437 let worktree = self
3438 .project
3439 .read(cx)
3440 .worktree_for_id(path.worktree_id, cx)?;
3441 if worktree.read(cx).is_visible() {
3442 abs_path
3443 } else {
3444 None
3445 }
3446 })
3447 .next()
3448 }
3449
3450 pub fn save_active_item(
3451 &mut self,
3452 save_intent: SaveIntent,
3453 window: &mut Window,
3454 cx: &mut App,
3455 ) -> Task<Result<()>> {
3456 let project = self.project.clone();
3457 let pane = self.active_pane();
3458 let item = pane.read(cx).active_item();
3459 let pane = pane.downgrade();
3460
3461 window.spawn(cx, async move |cx| {
3462 if let Some(item) = item {
3463 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3464 .await
3465 .map(|_| ())
3466 } else {
3467 Ok(())
3468 }
3469 })
3470 }
3471
3472 pub fn close_inactive_items_and_panes(
3473 &mut self,
3474 action: &CloseInactiveTabsAndPanes,
3475 window: &mut Window,
3476 cx: &mut Context<Self>,
3477 ) {
3478 if let Some(task) = self.close_all_internal(
3479 true,
3480 action.save_intent.unwrap_or(SaveIntent::Close),
3481 window,
3482 cx,
3483 ) {
3484 task.detach_and_log_err(cx)
3485 }
3486 }
3487
3488 pub fn close_all_items_and_panes(
3489 &mut self,
3490 action: &CloseAllItemsAndPanes,
3491 window: &mut Window,
3492 cx: &mut Context<Self>,
3493 ) {
3494 if let Some(task) = self.close_all_internal(
3495 false,
3496 action.save_intent.unwrap_or(SaveIntent::Close),
3497 window,
3498 cx,
3499 ) {
3500 task.detach_and_log_err(cx)
3501 }
3502 }
3503
3504 /// Closes the active item across all panes.
3505 pub fn close_item_in_all_panes(
3506 &mut self,
3507 action: &CloseItemInAllPanes,
3508 window: &mut Window,
3509 cx: &mut Context<Self>,
3510 ) {
3511 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3512 return;
3513 };
3514
3515 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3516 let close_pinned = action.close_pinned;
3517
3518 if let Some(project_path) = active_item.project_path(cx) {
3519 self.close_items_with_project_path(
3520 &project_path,
3521 save_intent,
3522 close_pinned,
3523 window,
3524 cx,
3525 );
3526 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3527 let item_id = active_item.item_id();
3528 self.active_pane().update(cx, |pane, cx| {
3529 pane.close_item_by_id(item_id, save_intent, window, cx)
3530 .detach_and_log_err(cx);
3531 });
3532 }
3533 }
3534
3535 /// Closes all items with the given project path across all panes.
3536 pub fn close_items_with_project_path(
3537 &mut self,
3538 project_path: &ProjectPath,
3539 save_intent: SaveIntent,
3540 close_pinned: bool,
3541 window: &mut Window,
3542 cx: &mut Context<Self>,
3543 ) {
3544 let panes = self.panes().to_vec();
3545 for pane in panes {
3546 pane.update(cx, |pane, cx| {
3547 pane.close_items_for_project_path(
3548 project_path,
3549 save_intent,
3550 close_pinned,
3551 window,
3552 cx,
3553 )
3554 .detach_and_log_err(cx);
3555 });
3556 }
3557 }
3558
3559 fn close_all_internal(
3560 &mut self,
3561 retain_active_pane: bool,
3562 save_intent: SaveIntent,
3563 window: &mut Window,
3564 cx: &mut Context<Self>,
3565 ) -> Option<Task<Result<()>>> {
3566 let current_pane = self.active_pane();
3567
3568 let mut tasks = Vec::new();
3569
3570 if retain_active_pane {
3571 let current_pane_close = current_pane.update(cx, |pane, cx| {
3572 pane.close_other_items(
3573 &CloseOtherItems {
3574 save_intent: None,
3575 close_pinned: false,
3576 },
3577 None,
3578 window,
3579 cx,
3580 )
3581 });
3582
3583 tasks.push(current_pane_close);
3584 }
3585
3586 for pane in self.panes() {
3587 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3588 continue;
3589 }
3590
3591 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3592 pane.close_all_items(
3593 &CloseAllItems {
3594 save_intent: Some(save_intent),
3595 close_pinned: false,
3596 },
3597 window,
3598 cx,
3599 )
3600 });
3601
3602 tasks.push(close_pane_items)
3603 }
3604
3605 if tasks.is_empty() {
3606 None
3607 } else {
3608 Some(cx.spawn_in(window, async move |_, _| {
3609 for task in tasks {
3610 task.await?
3611 }
3612 Ok(())
3613 }))
3614 }
3615 }
3616
3617 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3618 self.dock_at_position(position).read(cx).is_open()
3619 }
3620
3621 pub fn toggle_dock(
3622 &mut self,
3623 dock_side: DockPosition,
3624 window: &mut Window,
3625 cx: &mut Context<Self>,
3626 ) {
3627 let mut focus_center = false;
3628 let mut reveal_dock = false;
3629
3630 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3631 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3632
3633 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3634 telemetry::event!(
3635 "Panel Button Clicked",
3636 name = panel.persistent_name(),
3637 toggle_state = !was_visible
3638 );
3639 }
3640 if was_visible {
3641 self.save_open_dock_positions(cx);
3642 }
3643
3644 let dock = self.dock_at_position(dock_side);
3645 dock.update(cx, |dock, cx| {
3646 dock.set_open(!was_visible, window, cx);
3647
3648 if dock.active_panel().is_none() {
3649 let Some(panel_ix) = dock
3650 .first_enabled_panel_idx(cx)
3651 .log_with_level(log::Level::Info)
3652 else {
3653 return;
3654 };
3655 dock.activate_panel(panel_ix, window, cx);
3656 }
3657
3658 if let Some(active_panel) = dock.active_panel() {
3659 if was_visible {
3660 if active_panel
3661 .panel_focus_handle(cx)
3662 .contains_focused(window, cx)
3663 {
3664 focus_center = true;
3665 }
3666 } else {
3667 let focus_handle = &active_panel.panel_focus_handle(cx);
3668 window.focus(focus_handle, cx);
3669 reveal_dock = true;
3670 }
3671 }
3672 });
3673
3674 if reveal_dock {
3675 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3676 }
3677
3678 if focus_center {
3679 self.active_pane
3680 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3681 }
3682
3683 cx.notify();
3684 self.serialize_workspace(window, cx);
3685 }
3686
3687 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3688 self.all_docks().into_iter().find(|&dock| {
3689 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3690 })
3691 }
3692
3693 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3694 if let Some(dock) = self.active_dock(window, cx).cloned() {
3695 self.save_open_dock_positions(cx);
3696 dock.update(cx, |dock, cx| {
3697 dock.set_open(false, window, cx);
3698 });
3699 return true;
3700 }
3701 false
3702 }
3703
3704 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3705 self.save_open_dock_positions(cx);
3706 for dock in self.all_docks() {
3707 dock.update(cx, |dock, cx| {
3708 dock.set_open(false, window, cx);
3709 });
3710 }
3711
3712 cx.focus_self(window);
3713 cx.notify();
3714 self.serialize_workspace(window, cx);
3715 }
3716
3717 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
3718 self.all_docks()
3719 .into_iter()
3720 .filter_map(|dock| {
3721 let dock_ref = dock.read(cx);
3722 if dock_ref.is_open() {
3723 Some(dock_ref.position())
3724 } else {
3725 None
3726 }
3727 })
3728 .collect()
3729 }
3730
3731 /// Saves the positions of currently open docks.
3732 ///
3733 /// Updates `last_open_dock_positions` with positions of all currently open
3734 /// docks, to later be restored by the 'Toggle All Docks' action.
3735 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
3736 let open_dock_positions = self.get_open_dock_positions(cx);
3737 if !open_dock_positions.is_empty() {
3738 self.last_open_dock_positions = open_dock_positions;
3739 }
3740 }
3741
3742 /// Toggles all docks between open and closed states.
3743 ///
3744 /// If any docks are open, closes all and remembers their positions. If all
3745 /// docks are closed, restores the last remembered dock configuration.
3746 fn toggle_all_docks(
3747 &mut self,
3748 _: &ToggleAllDocks,
3749 window: &mut Window,
3750 cx: &mut Context<Self>,
3751 ) {
3752 let open_dock_positions = self.get_open_dock_positions(cx);
3753
3754 if !open_dock_positions.is_empty() {
3755 self.close_all_docks(window, cx);
3756 } else if !self.last_open_dock_positions.is_empty() {
3757 self.restore_last_open_docks(window, cx);
3758 }
3759 }
3760
3761 /// Reopens docks from the most recently remembered configuration.
3762 ///
3763 /// Opens all docks whose positions are stored in `last_open_dock_positions`
3764 /// and clears the stored positions.
3765 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3766 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
3767
3768 for position in positions_to_open {
3769 let dock = self.dock_at_position(position);
3770 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
3771 }
3772
3773 cx.focus_self(window);
3774 cx.notify();
3775 self.serialize_workspace(window, cx);
3776 }
3777
3778 /// Transfer focus to the panel of the given type.
3779 pub fn focus_panel<T: Panel>(
3780 &mut self,
3781 window: &mut Window,
3782 cx: &mut Context<Self>,
3783 ) -> Option<Entity<T>> {
3784 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
3785 panel.to_any().downcast().ok()
3786 }
3787
3788 /// Focus the panel of the given type if it isn't already focused. If it is
3789 /// already focused, then transfer focus back to the workspace center.
3790 /// When the `close_panel_on_toggle` setting is enabled, also closes the
3791 /// panel when transferring focus back to the center.
3792 pub fn toggle_panel_focus<T: Panel>(
3793 &mut self,
3794 window: &mut Window,
3795 cx: &mut Context<Self>,
3796 ) -> bool {
3797 let mut did_focus_panel = false;
3798 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
3799 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
3800 did_focus_panel
3801 });
3802
3803 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
3804 self.close_panel::<T>(window, cx);
3805 }
3806
3807 telemetry::event!(
3808 "Panel Button Clicked",
3809 name = T::persistent_name(),
3810 toggle_state = did_focus_panel
3811 );
3812
3813 did_focus_panel
3814 }
3815
3816 pub fn activate_panel_for_proto_id(
3817 &mut self,
3818 panel_id: PanelId,
3819 window: &mut Window,
3820 cx: &mut Context<Self>,
3821 ) -> Option<Arc<dyn PanelHandle>> {
3822 let mut panel = None;
3823 for dock in self.all_docks() {
3824 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
3825 panel = dock.update(cx, |dock, cx| {
3826 dock.activate_panel(panel_index, window, cx);
3827 dock.set_open(true, window, cx);
3828 dock.active_panel().cloned()
3829 });
3830 break;
3831 }
3832 }
3833
3834 if panel.is_some() {
3835 cx.notify();
3836 self.serialize_workspace(window, cx);
3837 }
3838
3839 panel
3840 }
3841
3842 /// Focus or unfocus the given panel type, depending on the given callback.
3843 fn focus_or_unfocus_panel<T: Panel>(
3844 &mut self,
3845 window: &mut Window,
3846 cx: &mut Context<Self>,
3847 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
3848 ) -> Option<Arc<dyn PanelHandle>> {
3849 let mut result_panel = None;
3850 let mut serialize = false;
3851 for dock in self.all_docks() {
3852 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3853 let mut focus_center = false;
3854 let panel = dock.update(cx, |dock, cx| {
3855 dock.activate_panel(panel_index, window, cx);
3856
3857 let panel = dock.active_panel().cloned();
3858 if let Some(panel) = panel.as_ref() {
3859 if should_focus(&**panel, window, cx) {
3860 dock.set_open(true, window, cx);
3861 panel.panel_focus_handle(cx).focus(window, cx);
3862 } else {
3863 focus_center = true;
3864 }
3865 }
3866 panel
3867 });
3868
3869 if focus_center {
3870 self.active_pane
3871 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3872 }
3873
3874 result_panel = panel;
3875 serialize = true;
3876 break;
3877 }
3878 }
3879
3880 if serialize {
3881 self.serialize_workspace(window, cx);
3882 }
3883
3884 cx.notify();
3885 result_panel
3886 }
3887
3888 /// Open the panel of the given type
3889 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3890 for dock in self.all_docks() {
3891 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3892 dock.update(cx, |dock, cx| {
3893 dock.activate_panel(panel_index, window, cx);
3894 dock.set_open(true, window, cx);
3895 });
3896 }
3897 }
3898 }
3899
3900 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
3901 for dock in self.all_docks().iter() {
3902 dock.update(cx, |dock, cx| {
3903 if dock.panel::<T>().is_some() {
3904 dock.set_open(false, window, cx)
3905 }
3906 })
3907 }
3908 }
3909
3910 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
3911 self.all_docks()
3912 .iter()
3913 .find_map(|dock| dock.read(cx).panel::<T>())
3914 }
3915
3916 fn dismiss_zoomed_items_to_reveal(
3917 &mut self,
3918 dock_to_reveal: Option<DockPosition>,
3919 window: &mut Window,
3920 cx: &mut Context<Self>,
3921 ) {
3922 // If a center pane is zoomed, unzoom it.
3923 for pane in &self.panes {
3924 if pane != &self.active_pane || dock_to_reveal.is_some() {
3925 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
3926 }
3927 }
3928
3929 // If another dock is zoomed, hide it.
3930 let mut focus_center = false;
3931 for dock in self.all_docks() {
3932 dock.update(cx, |dock, cx| {
3933 if Some(dock.position()) != dock_to_reveal
3934 && let Some(panel) = dock.active_panel()
3935 && panel.is_zoomed(window, cx)
3936 {
3937 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
3938 dock.set_open(false, window, cx);
3939 }
3940 });
3941 }
3942
3943 if focus_center {
3944 self.active_pane
3945 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3946 }
3947
3948 if self.zoomed_position != dock_to_reveal {
3949 self.zoomed = None;
3950 self.zoomed_position = None;
3951 cx.emit(Event::ZoomChanged);
3952 }
3953
3954 cx.notify();
3955 }
3956
3957 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
3958 let pane = cx.new(|cx| {
3959 let mut pane = Pane::new(
3960 self.weak_handle(),
3961 self.project.clone(),
3962 self.pane_history_timestamp.clone(),
3963 None,
3964 NewFile.boxed_clone(),
3965 true,
3966 window,
3967 cx,
3968 );
3969 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
3970 pane
3971 });
3972 cx.subscribe_in(&pane, window, Self::handle_pane_event)
3973 .detach();
3974 self.panes.push(pane.clone());
3975
3976 window.focus(&pane.focus_handle(cx), cx);
3977
3978 cx.emit(Event::PaneAdded(pane.clone()));
3979 pane
3980 }
3981
3982 pub fn add_item_to_center(
3983 &mut self,
3984 item: Box<dyn ItemHandle>,
3985 window: &mut Window,
3986 cx: &mut Context<Self>,
3987 ) -> bool {
3988 if let Some(center_pane) = self.last_active_center_pane.clone() {
3989 if let Some(center_pane) = center_pane.upgrade() {
3990 center_pane.update(cx, |pane, cx| {
3991 pane.add_item(item, true, true, None, window, cx)
3992 });
3993 true
3994 } else {
3995 false
3996 }
3997 } else {
3998 false
3999 }
4000 }
4001
4002 pub fn add_item_to_active_pane(
4003 &mut self,
4004 item: Box<dyn ItemHandle>,
4005 destination_index: Option<usize>,
4006 focus_item: bool,
4007 window: &mut Window,
4008 cx: &mut App,
4009 ) {
4010 self.add_item(
4011 self.active_pane.clone(),
4012 item,
4013 destination_index,
4014 false,
4015 focus_item,
4016 window,
4017 cx,
4018 )
4019 }
4020
4021 pub fn add_item(
4022 &mut self,
4023 pane: Entity<Pane>,
4024 item: Box<dyn ItemHandle>,
4025 destination_index: Option<usize>,
4026 activate_pane: bool,
4027 focus_item: bool,
4028 window: &mut Window,
4029 cx: &mut App,
4030 ) {
4031 pane.update(cx, |pane, cx| {
4032 pane.add_item(
4033 item,
4034 activate_pane,
4035 focus_item,
4036 destination_index,
4037 window,
4038 cx,
4039 )
4040 });
4041 }
4042
4043 pub fn split_item(
4044 &mut self,
4045 split_direction: SplitDirection,
4046 item: Box<dyn ItemHandle>,
4047 window: &mut Window,
4048 cx: &mut Context<Self>,
4049 ) {
4050 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4051 self.add_item(new_pane, item, None, true, true, window, cx);
4052 }
4053
4054 pub fn open_abs_path(
4055 &mut self,
4056 abs_path: PathBuf,
4057 options: OpenOptions,
4058 window: &mut Window,
4059 cx: &mut Context<Self>,
4060 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4061 cx.spawn_in(window, async move |workspace, cx| {
4062 let open_paths_task_result = workspace
4063 .update_in(cx, |workspace, window, cx| {
4064 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4065 })
4066 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4067 .await;
4068 anyhow::ensure!(
4069 open_paths_task_result.len() == 1,
4070 "open abs path {abs_path:?} task returned incorrect number of results"
4071 );
4072 match open_paths_task_result
4073 .into_iter()
4074 .next()
4075 .expect("ensured single task result")
4076 {
4077 Some(open_result) => {
4078 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4079 }
4080 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4081 }
4082 })
4083 }
4084
4085 pub fn split_abs_path(
4086 &mut self,
4087 abs_path: PathBuf,
4088 visible: bool,
4089 window: &mut Window,
4090 cx: &mut Context<Self>,
4091 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4092 let project_path_task =
4093 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4094 cx.spawn_in(window, async move |this, cx| {
4095 let (_, path) = project_path_task.await?;
4096 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4097 .await
4098 })
4099 }
4100
4101 pub fn open_path(
4102 &mut self,
4103 path: impl Into<ProjectPath>,
4104 pane: Option<WeakEntity<Pane>>,
4105 focus_item: bool,
4106 window: &mut Window,
4107 cx: &mut App,
4108 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4109 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4110 }
4111
4112 pub fn open_path_preview(
4113 &mut self,
4114 path: impl Into<ProjectPath>,
4115 pane: Option<WeakEntity<Pane>>,
4116 focus_item: bool,
4117 allow_preview: bool,
4118 activate: bool,
4119 window: &mut Window,
4120 cx: &mut App,
4121 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4122 let pane = pane.unwrap_or_else(|| {
4123 self.last_active_center_pane.clone().unwrap_or_else(|| {
4124 self.panes
4125 .first()
4126 .expect("There must be an active pane")
4127 .downgrade()
4128 })
4129 });
4130
4131 let project_path = path.into();
4132 let task = self.load_path(project_path.clone(), window, cx);
4133 window.spawn(cx, async move |cx| {
4134 let (project_entry_id, build_item) = task.await?;
4135
4136 pane.update_in(cx, |pane, window, cx| {
4137 pane.open_item(
4138 project_entry_id,
4139 project_path,
4140 focus_item,
4141 allow_preview,
4142 activate,
4143 None,
4144 window,
4145 cx,
4146 build_item,
4147 )
4148 })
4149 })
4150 }
4151
4152 pub fn split_path(
4153 &mut self,
4154 path: impl Into<ProjectPath>,
4155 window: &mut Window,
4156 cx: &mut Context<Self>,
4157 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4158 self.split_path_preview(path, false, None, window, cx)
4159 }
4160
4161 pub fn split_path_preview(
4162 &mut self,
4163 path: impl Into<ProjectPath>,
4164 allow_preview: bool,
4165 split_direction: Option<SplitDirection>,
4166 window: &mut Window,
4167 cx: &mut Context<Self>,
4168 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4169 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4170 self.panes
4171 .first()
4172 .expect("There must be an active pane")
4173 .downgrade()
4174 });
4175
4176 if let Member::Pane(center_pane) = &self.center.root
4177 && center_pane.read(cx).items_len() == 0
4178 {
4179 return self.open_path(path, Some(pane), true, window, cx);
4180 }
4181
4182 let project_path = path.into();
4183 let task = self.load_path(project_path.clone(), window, cx);
4184 cx.spawn_in(window, async move |this, cx| {
4185 let (project_entry_id, build_item) = task.await?;
4186 this.update_in(cx, move |this, window, cx| -> Option<_> {
4187 let pane = pane.upgrade()?;
4188 let new_pane = this.split_pane(
4189 pane,
4190 split_direction.unwrap_or(SplitDirection::Right),
4191 window,
4192 cx,
4193 );
4194 new_pane.update(cx, |new_pane, cx| {
4195 Some(new_pane.open_item(
4196 project_entry_id,
4197 project_path,
4198 true,
4199 allow_preview,
4200 true,
4201 None,
4202 window,
4203 cx,
4204 build_item,
4205 ))
4206 })
4207 })
4208 .map(|option| option.context("pane was dropped"))?
4209 })
4210 }
4211
4212 fn load_path(
4213 &mut self,
4214 path: ProjectPath,
4215 window: &mut Window,
4216 cx: &mut App,
4217 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4218 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4219 registry.open_path(self.project(), &path, window, cx)
4220 }
4221
4222 pub fn find_project_item<T>(
4223 &self,
4224 pane: &Entity<Pane>,
4225 project_item: &Entity<T::Item>,
4226 cx: &App,
4227 ) -> Option<Entity<T>>
4228 where
4229 T: ProjectItem,
4230 {
4231 use project::ProjectItem as _;
4232 let project_item = project_item.read(cx);
4233 let entry_id = project_item.entry_id(cx);
4234 let project_path = project_item.project_path(cx);
4235
4236 let mut item = None;
4237 if let Some(entry_id) = entry_id {
4238 item = pane.read(cx).item_for_entry(entry_id, cx);
4239 }
4240 if item.is_none()
4241 && let Some(project_path) = project_path
4242 {
4243 item = pane.read(cx).item_for_path(project_path, cx);
4244 }
4245
4246 item.and_then(|item| item.downcast::<T>())
4247 }
4248
4249 pub fn is_project_item_open<T>(
4250 &self,
4251 pane: &Entity<Pane>,
4252 project_item: &Entity<T::Item>,
4253 cx: &App,
4254 ) -> bool
4255 where
4256 T: ProjectItem,
4257 {
4258 self.find_project_item::<T>(pane, project_item, cx)
4259 .is_some()
4260 }
4261
4262 pub fn open_project_item<T>(
4263 &mut self,
4264 pane: Entity<Pane>,
4265 project_item: Entity<T::Item>,
4266 activate_pane: bool,
4267 focus_item: bool,
4268 keep_old_preview: bool,
4269 allow_new_preview: bool,
4270 window: &mut Window,
4271 cx: &mut Context<Self>,
4272 ) -> Entity<T>
4273 where
4274 T: ProjectItem,
4275 {
4276 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4277
4278 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4279 if !keep_old_preview
4280 && let Some(old_id) = old_item_id
4281 && old_id != item.item_id()
4282 {
4283 // switching to a different item, so unpreview old active item
4284 pane.update(cx, |pane, _| {
4285 pane.unpreview_item_if_preview(old_id);
4286 });
4287 }
4288
4289 self.activate_item(&item, activate_pane, focus_item, window, cx);
4290 if !allow_new_preview {
4291 pane.update(cx, |pane, _| {
4292 pane.unpreview_item_if_preview(item.item_id());
4293 });
4294 }
4295 return item;
4296 }
4297
4298 let item = pane.update(cx, |pane, cx| {
4299 cx.new(|cx| {
4300 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4301 })
4302 });
4303 let mut destination_index = None;
4304 pane.update(cx, |pane, cx| {
4305 if !keep_old_preview && let Some(old_id) = old_item_id {
4306 pane.unpreview_item_if_preview(old_id);
4307 }
4308 if allow_new_preview {
4309 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4310 }
4311 });
4312
4313 self.add_item(
4314 pane,
4315 Box::new(item.clone()),
4316 destination_index,
4317 activate_pane,
4318 focus_item,
4319 window,
4320 cx,
4321 );
4322 item
4323 }
4324
4325 pub fn open_shared_screen(
4326 &mut self,
4327 peer_id: PeerId,
4328 window: &mut Window,
4329 cx: &mut Context<Self>,
4330 ) {
4331 if let Some(shared_screen) =
4332 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4333 {
4334 self.active_pane.update(cx, |pane, cx| {
4335 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4336 });
4337 }
4338 }
4339
4340 pub fn activate_item(
4341 &mut self,
4342 item: &dyn ItemHandle,
4343 activate_pane: bool,
4344 focus_item: bool,
4345 window: &mut Window,
4346 cx: &mut App,
4347 ) -> bool {
4348 let result = self.panes.iter().find_map(|pane| {
4349 pane.read(cx)
4350 .index_for_item(item)
4351 .map(|ix| (pane.clone(), ix))
4352 });
4353 if let Some((pane, ix)) = result {
4354 pane.update(cx, |pane, cx| {
4355 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4356 });
4357 true
4358 } else {
4359 false
4360 }
4361 }
4362
4363 fn activate_pane_at_index(
4364 &mut self,
4365 action: &ActivatePane,
4366 window: &mut Window,
4367 cx: &mut Context<Self>,
4368 ) {
4369 let panes = self.center.panes();
4370 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4371 window.focus(&pane.focus_handle(cx), cx);
4372 } else {
4373 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4374 .detach();
4375 }
4376 }
4377
4378 fn move_item_to_pane_at_index(
4379 &mut self,
4380 action: &MoveItemToPane,
4381 window: &mut Window,
4382 cx: &mut Context<Self>,
4383 ) {
4384 let panes = self.center.panes();
4385 let destination = match panes.get(action.destination) {
4386 Some(&destination) => destination.clone(),
4387 None => {
4388 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4389 return;
4390 }
4391 let direction = SplitDirection::Right;
4392 let split_off_pane = self
4393 .find_pane_in_direction(direction, cx)
4394 .unwrap_or_else(|| self.active_pane.clone());
4395 let new_pane = self.add_pane(window, cx);
4396 self.center.split(&split_off_pane, &new_pane, direction, cx);
4397 new_pane
4398 }
4399 };
4400
4401 if action.clone {
4402 if self
4403 .active_pane
4404 .read(cx)
4405 .active_item()
4406 .is_some_and(|item| item.can_split(cx))
4407 {
4408 clone_active_item(
4409 self.database_id(),
4410 &self.active_pane,
4411 &destination,
4412 action.focus,
4413 window,
4414 cx,
4415 );
4416 return;
4417 }
4418 }
4419 move_active_item(
4420 &self.active_pane,
4421 &destination,
4422 action.focus,
4423 true,
4424 window,
4425 cx,
4426 )
4427 }
4428
4429 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4430 let panes = self.center.panes();
4431 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4432 let next_ix = (ix + 1) % panes.len();
4433 let next_pane = panes[next_ix].clone();
4434 window.focus(&next_pane.focus_handle(cx), cx);
4435 }
4436 }
4437
4438 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4439 let panes = self.center.panes();
4440 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4441 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4442 let prev_pane = panes[prev_ix].clone();
4443 window.focus(&prev_pane.focus_handle(cx), cx);
4444 }
4445 }
4446
4447 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4448 let last_pane = self.center.last_pane();
4449 window.focus(&last_pane.focus_handle(cx), cx);
4450 }
4451
4452 pub fn activate_pane_in_direction(
4453 &mut self,
4454 direction: SplitDirection,
4455 window: &mut Window,
4456 cx: &mut App,
4457 ) {
4458 use ActivateInDirectionTarget as Target;
4459 enum Origin {
4460 LeftDock,
4461 RightDock,
4462 BottomDock,
4463 Center,
4464 }
4465
4466 let origin: Origin = [
4467 (&self.left_dock, Origin::LeftDock),
4468 (&self.right_dock, Origin::RightDock),
4469 (&self.bottom_dock, Origin::BottomDock),
4470 ]
4471 .into_iter()
4472 .find_map(|(dock, origin)| {
4473 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4474 Some(origin)
4475 } else {
4476 None
4477 }
4478 })
4479 .unwrap_or(Origin::Center);
4480
4481 let get_last_active_pane = || {
4482 let pane = self
4483 .last_active_center_pane
4484 .clone()
4485 .unwrap_or_else(|| {
4486 self.panes
4487 .first()
4488 .expect("There must be an active pane")
4489 .downgrade()
4490 })
4491 .upgrade()?;
4492 (pane.read(cx).items_len() != 0).then_some(pane)
4493 };
4494
4495 let try_dock =
4496 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4497
4498 let target = match (origin, direction) {
4499 // We're in the center, so we first try to go to a different pane,
4500 // otherwise try to go to a dock.
4501 (Origin::Center, direction) => {
4502 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4503 Some(Target::Pane(pane))
4504 } else {
4505 match direction {
4506 SplitDirection::Up => None,
4507 SplitDirection::Down => try_dock(&self.bottom_dock),
4508 SplitDirection::Left => try_dock(&self.left_dock),
4509 SplitDirection::Right => try_dock(&self.right_dock),
4510 }
4511 }
4512 }
4513
4514 (Origin::LeftDock, SplitDirection::Right) => {
4515 if let Some(last_active_pane) = get_last_active_pane() {
4516 Some(Target::Pane(last_active_pane))
4517 } else {
4518 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4519 }
4520 }
4521
4522 (Origin::LeftDock, SplitDirection::Down)
4523 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4524
4525 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4526 (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
4527 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4528
4529 (Origin::RightDock, SplitDirection::Left) => {
4530 if let Some(last_active_pane) = get_last_active_pane() {
4531 Some(Target::Pane(last_active_pane))
4532 } else {
4533 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
4534 }
4535 }
4536
4537 _ => None,
4538 };
4539
4540 match target {
4541 Some(ActivateInDirectionTarget::Pane(pane)) => {
4542 let pane = pane.read(cx);
4543 if let Some(item) = pane.active_item() {
4544 item.item_focus_handle(cx).focus(window, cx);
4545 } else {
4546 log::error!(
4547 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4548 );
4549 }
4550 }
4551 Some(ActivateInDirectionTarget::Dock(dock)) => {
4552 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4553 window.defer(cx, move |window, cx| {
4554 let dock = dock.read(cx);
4555 if let Some(panel) = dock.active_panel() {
4556 panel.panel_focus_handle(cx).focus(window, cx);
4557 } else {
4558 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4559 }
4560 })
4561 }
4562 None => {}
4563 }
4564 }
4565
4566 pub fn move_item_to_pane_in_direction(
4567 &mut self,
4568 action: &MoveItemToPaneInDirection,
4569 window: &mut Window,
4570 cx: &mut Context<Self>,
4571 ) {
4572 let destination = match self.find_pane_in_direction(action.direction, cx) {
4573 Some(destination) => destination,
4574 None => {
4575 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4576 return;
4577 }
4578 let new_pane = self.add_pane(window, cx);
4579 self.center
4580 .split(&self.active_pane, &new_pane, action.direction, cx);
4581 new_pane
4582 }
4583 };
4584
4585 if action.clone {
4586 if self
4587 .active_pane
4588 .read(cx)
4589 .active_item()
4590 .is_some_and(|item| item.can_split(cx))
4591 {
4592 clone_active_item(
4593 self.database_id(),
4594 &self.active_pane,
4595 &destination,
4596 action.focus,
4597 window,
4598 cx,
4599 );
4600 return;
4601 }
4602 }
4603 move_active_item(
4604 &self.active_pane,
4605 &destination,
4606 action.focus,
4607 true,
4608 window,
4609 cx,
4610 );
4611 }
4612
4613 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4614 self.center.bounding_box_for_pane(pane)
4615 }
4616
4617 pub fn find_pane_in_direction(
4618 &mut self,
4619 direction: SplitDirection,
4620 cx: &App,
4621 ) -> Option<Entity<Pane>> {
4622 self.center
4623 .find_pane_in_direction(&self.active_pane, direction, cx)
4624 .cloned()
4625 }
4626
4627 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4628 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4629 self.center.swap(&self.active_pane, &to, cx);
4630 cx.notify();
4631 }
4632 }
4633
4634 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4635 if self
4636 .center
4637 .move_to_border(&self.active_pane, direction, cx)
4638 .unwrap()
4639 {
4640 cx.notify();
4641 }
4642 }
4643
4644 pub fn resize_pane(
4645 &mut self,
4646 axis: gpui::Axis,
4647 amount: Pixels,
4648 window: &mut Window,
4649 cx: &mut Context<Self>,
4650 ) {
4651 let docks = self.all_docks();
4652 let active_dock = docks
4653 .into_iter()
4654 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4655
4656 if let Some(dock) = active_dock {
4657 let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
4658 return;
4659 };
4660 match dock.read(cx).position() {
4661 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4662 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4663 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4664 }
4665 } else {
4666 self.center
4667 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
4668 }
4669 cx.notify();
4670 }
4671
4672 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
4673 self.center.reset_pane_sizes(cx);
4674 cx.notify();
4675 }
4676
4677 fn handle_pane_focused(
4678 &mut self,
4679 pane: Entity<Pane>,
4680 window: &mut Window,
4681 cx: &mut Context<Self>,
4682 ) {
4683 // This is explicitly hoisted out of the following check for pane identity as
4684 // terminal panel panes are not registered as a center panes.
4685 self.status_bar.update(cx, |status_bar, cx| {
4686 status_bar.set_active_pane(&pane, window, cx);
4687 });
4688 if self.active_pane != pane {
4689 self.set_active_pane(&pane, window, cx);
4690 }
4691
4692 if self.last_active_center_pane.is_none() {
4693 self.last_active_center_pane = Some(pane.downgrade());
4694 }
4695
4696 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
4697 // This prevents the dock from closing when focus events fire during window activation.
4698 // We also preserve any dock whose active panel itself has focus — this covers
4699 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
4700 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
4701 let dock_read = dock.read(cx);
4702 if let Some(panel) = dock_read.active_panel() {
4703 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
4704 || panel.panel_focus_handle(cx).contains_focused(window, cx)
4705 {
4706 return Some(dock_read.position());
4707 }
4708 }
4709 None
4710 });
4711
4712 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
4713 if pane.read(cx).is_zoomed() {
4714 self.zoomed = Some(pane.downgrade().into());
4715 } else {
4716 self.zoomed = None;
4717 }
4718 self.zoomed_position = None;
4719 cx.emit(Event::ZoomChanged);
4720 self.update_active_view_for_followers(window, cx);
4721 pane.update(cx, |pane, _| {
4722 pane.track_alternate_file_items();
4723 });
4724
4725 cx.notify();
4726 }
4727
4728 fn set_active_pane(
4729 &mut self,
4730 pane: &Entity<Pane>,
4731 window: &mut Window,
4732 cx: &mut Context<Self>,
4733 ) {
4734 self.active_pane = pane.clone();
4735 self.active_item_path_changed(true, window, cx);
4736 self.last_active_center_pane = Some(pane.downgrade());
4737 }
4738
4739 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4740 self.update_active_view_for_followers(window, cx);
4741 }
4742
4743 fn handle_pane_event(
4744 &mut self,
4745 pane: &Entity<Pane>,
4746 event: &pane::Event,
4747 window: &mut Window,
4748 cx: &mut Context<Self>,
4749 ) {
4750 let mut serialize_workspace = true;
4751 match event {
4752 pane::Event::AddItem { item } => {
4753 item.added_to_pane(self, pane.clone(), window, cx);
4754 cx.emit(Event::ItemAdded {
4755 item: item.boxed_clone(),
4756 });
4757 }
4758 pane::Event::Split { direction, mode } => {
4759 match mode {
4760 SplitMode::ClonePane => {
4761 self.split_and_clone(pane.clone(), *direction, window, cx)
4762 .detach();
4763 }
4764 SplitMode::EmptyPane => {
4765 self.split_pane(pane.clone(), *direction, window, cx);
4766 }
4767 SplitMode::MovePane => {
4768 self.split_and_move(pane.clone(), *direction, window, cx);
4769 }
4770 };
4771 }
4772 pane::Event::JoinIntoNext => {
4773 self.join_pane_into_next(pane.clone(), window, cx);
4774 }
4775 pane::Event::JoinAll => {
4776 self.join_all_panes(window, cx);
4777 }
4778 pane::Event::Remove { focus_on_pane } => {
4779 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
4780 }
4781 pane::Event::ActivateItem {
4782 local,
4783 focus_changed,
4784 } => {
4785 window.invalidate_character_coordinates();
4786
4787 pane.update(cx, |pane, _| {
4788 pane.track_alternate_file_items();
4789 });
4790 if *local {
4791 self.unfollow_in_pane(pane, window, cx);
4792 }
4793 serialize_workspace = *focus_changed || pane != self.active_pane();
4794 if pane == self.active_pane() {
4795 self.active_item_path_changed(*focus_changed, window, cx);
4796 self.update_active_view_for_followers(window, cx);
4797 } else if *local {
4798 self.set_active_pane(pane, window, cx);
4799 }
4800 }
4801 pane::Event::UserSavedItem { item, save_intent } => {
4802 cx.emit(Event::UserSavedItem {
4803 pane: pane.downgrade(),
4804 item: item.boxed_clone(),
4805 save_intent: *save_intent,
4806 });
4807 serialize_workspace = false;
4808 }
4809 pane::Event::ChangeItemTitle => {
4810 if *pane == self.active_pane {
4811 self.active_item_path_changed(false, window, cx);
4812 }
4813 serialize_workspace = false;
4814 }
4815 pane::Event::RemovedItem { item } => {
4816 cx.emit(Event::ActiveItemChanged);
4817 self.update_window_edited(window, cx);
4818 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
4819 && entry.get().entity_id() == pane.entity_id()
4820 {
4821 entry.remove();
4822 }
4823 cx.emit(Event::ItemRemoved {
4824 item_id: item.item_id(),
4825 });
4826 }
4827 pane::Event::Focus => {
4828 window.invalidate_character_coordinates();
4829 self.handle_pane_focused(pane.clone(), window, cx);
4830 }
4831 pane::Event::ZoomIn => {
4832 if *pane == self.active_pane {
4833 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
4834 if pane.read(cx).has_focus(window, cx) {
4835 self.zoomed = Some(pane.downgrade().into());
4836 self.zoomed_position = None;
4837 cx.emit(Event::ZoomChanged);
4838 }
4839 cx.notify();
4840 }
4841 }
4842 pane::Event::ZoomOut => {
4843 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4844 if self.zoomed_position.is_none() {
4845 self.zoomed = None;
4846 cx.emit(Event::ZoomChanged);
4847 }
4848 cx.notify();
4849 }
4850 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
4851 }
4852
4853 if serialize_workspace {
4854 self.serialize_workspace(window, cx);
4855 }
4856 }
4857
4858 pub fn unfollow_in_pane(
4859 &mut self,
4860 pane: &Entity<Pane>,
4861 window: &mut Window,
4862 cx: &mut Context<Workspace>,
4863 ) -> Option<CollaboratorId> {
4864 let leader_id = self.leader_for_pane(pane)?;
4865 self.unfollow(leader_id, window, cx);
4866 Some(leader_id)
4867 }
4868
4869 pub fn split_pane(
4870 &mut self,
4871 pane_to_split: Entity<Pane>,
4872 split_direction: SplitDirection,
4873 window: &mut Window,
4874 cx: &mut Context<Self>,
4875 ) -> Entity<Pane> {
4876 let new_pane = self.add_pane(window, cx);
4877 self.center
4878 .split(&pane_to_split, &new_pane, split_direction, cx);
4879 cx.notify();
4880 new_pane
4881 }
4882
4883 pub fn split_and_move(
4884 &mut self,
4885 pane: Entity<Pane>,
4886 direction: SplitDirection,
4887 window: &mut Window,
4888 cx: &mut Context<Self>,
4889 ) {
4890 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
4891 return;
4892 };
4893 let new_pane = self.add_pane(window, cx);
4894 new_pane.update(cx, |pane, cx| {
4895 pane.add_item(item, true, true, None, window, cx)
4896 });
4897 self.center.split(&pane, &new_pane, direction, cx);
4898 cx.notify();
4899 }
4900
4901 pub fn split_and_clone(
4902 &mut self,
4903 pane: Entity<Pane>,
4904 direction: SplitDirection,
4905 window: &mut Window,
4906 cx: &mut Context<Self>,
4907 ) -> Task<Option<Entity<Pane>>> {
4908 let Some(item) = pane.read(cx).active_item() else {
4909 return Task::ready(None);
4910 };
4911 if !item.can_split(cx) {
4912 return Task::ready(None);
4913 }
4914 let task = item.clone_on_split(self.database_id(), window, cx);
4915 cx.spawn_in(window, async move |this, cx| {
4916 if let Some(clone) = task.await {
4917 this.update_in(cx, |this, window, cx| {
4918 let new_pane = this.add_pane(window, cx);
4919 let nav_history = pane.read(cx).fork_nav_history();
4920 new_pane.update(cx, |pane, cx| {
4921 pane.set_nav_history(nav_history, cx);
4922 pane.add_item(clone, true, true, None, window, cx)
4923 });
4924 this.center.split(&pane, &new_pane, direction, cx);
4925 cx.notify();
4926 new_pane
4927 })
4928 .ok()
4929 } else {
4930 None
4931 }
4932 })
4933 }
4934
4935 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4936 let active_item = self.active_pane.read(cx).active_item();
4937 for pane in &self.panes {
4938 join_pane_into_active(&self.active_pane, pane, window, cx);
4939 }
4940 if let Some(active_item) = active_item {
4941 self.activate_item(active_item.as_ref(), true, true, window, cx);
4942 }
4943 cx.notify();
4944 }
4945
4946 pub fn join_pane_into_next(
4947 &mut self,
4948 pane: Entity<Pane>,
4949 window: &mut Window,
4950 cx: &mut Context<Self>,
4951 ) {
4952 let next_pane = self
4953 .find_pane_in_direction(SplitDirection::Right, cx)
4954 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
4955 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
4956 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
4957 let Some(next_pane) = next_pane else {
4958 return;
4959 };
4960 move_all_items(&pane, &next_pane, window, cx);
4961 cx.notify();
4962 }
4963
4964 fn remove_pane(
4965 &mut self,
4966 pane: Entity<Pane>,
4967 focus_on: Option<Entity<Pane>>,
4968 window: &mut Window,
4969 cx: &mut Context<Self>,
4970 ) {
4971 if self.center.remove(&pane, cx).unwrap() {
4972 self.force_remove_pane(&pane, &focus_on, window, cx);
4973 self.unfollow_in_pane(&pane, window, cx);
4974 self.last_leaders_by_pane.remove(&pane.downgrade());
4975 for removed_item in pane.read(cx).items() {
4976 self.panes_by_item.remove(&removed_item.item_id());
4977 }
4978
4979 cx.notify();
4980 } else {
4981 self.active_item_path_changed(true, window, cx);
4982 }
4983 cx.emit(Event::PaneRemoved);
4984 }
4985
4986 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
4987 &mut self.panes
4988 }
4989
4990 pub fn panes(&self) -> &[Entity<Pane>] {
4991 &self.panes
4992 }
4993
4994 pub fn active_pane(&self) -> &Entity<Pane> {
4995 &self.active_pane
4996 }
4997
4998 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
4999 for dock in self.all_docks() {
5000 if dock.focus_handle(cx).contains_focused(window, cx)
5001 && let Some(pane) = dock
5002 .read(cx)
5003 .active_panel()
5004 .and_then(|panel| panel.pane(cx))
5005 {
5006 return pane;
5007 }
5008 }
5009 self.active_pane().clone()
5010 }
5011
5012 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5013 self.find_pane_in_direction(SplitDirection::Right, cx)
5014 .unwrap_or_else(|| {
5015 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5016 })
5017 }
5018
5019 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5020 self.pane_for_item_id(handle.item_id())
5021 }
5022
5023 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5024 let weak_pane = self.panes_by_item.get(&item_id)?;
5025 weak_pane.upgrade()
5026 }
5027
5028 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5029 self.panes
5030 .iter()
5031 .find(|pane| pane.entity_id() == entity_id)
5032 .cloned()
5033 }
5034
5035 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5036 self.follower_states.retain(|leader_id, state| {
5037 if *leader_id == CollaboratorId::PeerId(peer_id) {
5038 for item in state.items_by_leader_view_id.values() {
5039 item.view.set_leader_id(None, window, cx);
5040 }
5041 false
5042 } else {
5043 true
5044 }
5045 });
5046 cx.notify();
5047 }
5048
5049 pub fn start_following(
5050 &mut self,
5051 leader_id: impl Into<CollaboratorId>,
5052 window: &mut Window,
5053 cx: &mut Context<Self>,
5054 ) -> Option<Task<Result<()>>> {
5055 let leader_id = leader_id.into();
5056 let pane = self.active_pane().clone();
5057
5058 self.last_leaders_by_pane
5059 .insert(pane.downgrade(), leader_id);
5060 self.unfollow(leader_id, window, cx);
5061 self.unfollow_in_pane(&pane, window, cx);
5062 self.follower_states.insert(
5063 leader_id,
5064 FollowerState {
5065 center_pane: pane.clone(),
5066 dock_pane: None,
5067 active_view_id: None,
5068 items_by_leader_view_id: Default::default(),
5069 },
5070 );
5071 cx.notify();
5072
5073 match leader_id {
5074 CollaboratorId::PeerId(leader_peer_id) => {
5075 let room_id = self.active_call()?.room_id(cx)?;
5076 let project_id = self.project.read(cx).remote_id();
5077 let request = self.app_state.client.request(proto::Follow {
5078 room_id,
5079 project_id,
5080 leader_id: Some(leader_peer_id),
5081 });
5082
5083 Some(cx.spawn_in(window, async move |this, cx| {
5084 let response = request.await?;
5085 this.update(cx, |this, _| {
5086 let state = this
5087 .follower_states
5088 .get_mut(&leader_id)
5089 .context("following interrupted")?;
5090 state.active_view_id = response
5091 .active_view
5092 .as_ref()
5093 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5094 anyhow::Ok(())
5095 })??;
5096 if let Some(view) = response.active_view {
5097 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5098 }
5099 this.update_in(cx, |this, window, cx| {
5100 this.leader_updated(leader_id, window, cx)
5101 })?;
5102 Ok(())
5103 }))
5104 }
5105 CollaboratorId::Agent => {
5106 self.leader_updated(leader_id, window, cx)?;
5107 Some(Task::ready(Ok(())))
5108 }
5109 }
5110 }
5111
5112 pub fn follow_next_collaborator(
5113 &mut self,
5114 _: &FollowNextCollaborator,
5115 window: &mut Window,
5116 cx: &mut Context<Self>,
5117 ) {
5118 let collaborators = self.project.read(cx).collaborators();
5119 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5120 let mut collaborators = collaborators.keys().copied();
5121 for peer_id in collaborators.by_ref() {
5122 if CollaboratorId::PeerId(peer_id) == leader_id {
5123 break;
5124 }
5125 }
5126 collaborators.next().map(CollaboratorId::PeerId)
5127 } else if let Some(last_leader_id) =
5128 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5129 {
5130 match last_leader_id {
5131 CollaboratorId::PeerId(peer_id) => {
5132 if collaborators.contains_key(peer_id) {
5133 Some(*last_leader_id)
5134 } else {
5135 None
5136 }
5137 }
5138 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5139 }
5140 } else {
5141 None
5142 };
5143
5144 let pane = self.active_pane.clone();
5145 let Some(leader_id) = next_leader_id.or_else(|| {
5146 Some(CollaboratorId::PeerId(
5147 collaborators.keys().copied().next()?,
5148 ))
5149 }) else {
5150 return;
5151 };
5152 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5153 return;
5154 }
5155 if let Some(task) = self.start_following(leader_id, window, cx) {
5156 task.detach_and_log_err(cx)
5157 }
5158 }
5159
5160 pub fn follow(
5161 &mut self,
5162 leader_id: impl Into<CollaboratorId>,
5163 window: &mut Window,
5164 cx: &mut Context<Self>,
5165 ) {
5166 let leader_id = leader_id.into();
5167
5168 if let CollaboratorId::PeerId(peer_id) = leader_id {
5169 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5170 return;
5171 };
5172 let Some(remote_participant) =
5173 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5174 else {
5175 return;
5176 };
5177
5178 let project = self.project.read(cx);
5179
5180 let other_project_id = match remote_participant.location {
5181 ParticipantLocation::External => None,
5182 ParticipantLocation::UnsharedProject => None,
5183 ParticipantLocation::SharedProject { project_id } => {
5184 if Some(project_id) == project.remote_id() {
5185 None
5186 } else {
5187 Some(project_id)
5188 }
5189 }
5190 };
5191
5192 // if they are active in another project, follow there.
5193 if let Some(project_id) = other_project_id {
5194 let app_state = self.app_state.clone();
5195 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5196 .detach_and_log_err(cx);
5197 }
5198 }
5199
5200 // if you're already following, find the right pane and focus it.
5201 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5202 window.focus(&follower_state.pane().focus_handle(cx), cx);
5203
5204 return;
5205 }
5206
5207 // Otherwise, follow.
5208 if let Some(task) = self.start_following(leader_id, window, cx) {
5209 task.detach_and_log_err(cx)
5210 }
5211 }
5212
5213 pub fn unfollow(
5214 &mut self,
5215 leader_id: impl Into<CollaboratorId>,
5216 window: &mut Window,
5217 cx: &mut Context<Self>,
5218 ) -> Option<()> {
5219 cx.notify();
5220
5221 let leader_id = leader_id.into();
5222 let state = self.follower_states.remove(&leader_id)?;
5223 for (_, item) in state.items_by_leader_view_id {
5224 item.view.set_leader_id(None, window, cx);
5225 }
5226
5227 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5228 let project_id = self.project.read(cx).remote_id();
5229 let room_id = self.active_call()?.room_id(cx)?;
5230 self.app_state
5231 .client
5232 .send(proto::Unfollow {
5233 room_id,
5234 project_id,
5235 leader_id: Some(leader_peer_id),
5236 })
5237 .log_err();
5238 }
5239
5240 Some(())
5241 }
5242
5243 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5244 self.follower_states.contains_key(&id.into())
5245 }
5246
5247 fn active_item_path_changed(
5248 &mut self,
5249 focus_changed: bool,
5250 window: &mut Window,
5251 cx: &mut Context<Self>,
5252 ) {
5253 cx.emit(Event::ActiveItemChanged);
5254 let active_entry = self.active_project_path(cx);
5255 self.project.update(cx, |project, cx| {
5256 project.set_active_path(active_entry.clone(), cx)
5257 });
5258
5259 if focus_changed && let Some(project_path) = &active_entry {
5260 let git_store_entity = self.project.read(cx).git_store().clone();
5261 git_store_entity.update(cx, |git_store, cx| {
5262 git_store.set_active_repo_for_path(project_path, cx);
5263 });
5264 }
5265
5266 self.update_window_title(window, cx);
5267 }
5268
5269 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5270 let project = self.project().read(cx);
5271 let mut title = String::new();
5272
5273 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5274 let name = {
5275 let settings_location = SettingsLocation {
5276 worktree_id: worktree.read(cx).id(),
5277 path: RelPath::empty(),
5278 };
5279
5280 let settings = WorktreeSettings::get(Some(settings_location), cx);
5281 match &settings.project_name {
5282 Some(name) => name.as_str(),
5283 None => worktree.read(cx).root_name_str(),
5284 }
5285 };
5286 if i > 0 {
5287 title.push_str(", ");
5288 }
5289 title.push_str(name);
5290 }
5291
5292 if title.is_empty() {
5293 title = "empty project".to_string();
5294 }
5295
5296 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5297 let filename = path.path.file_name().or_else(|| {
5298 Some(
5299 project
5300 .worktree_for_id(path.worktree_id, cx)?
5301 .read(cx)
5302 .root_name_str(),
5303 )
5304 });
5305
5306 if let Some(filename) = filename {
5307 title.push_str(" — ");
5308 title.push_str(filename.as_ref());
5309 }
5310 }
5311
5312 if project.is_via_collab() {
5313 title.push_str(" ↙");
5314 } else if project.is_shared() {
5315 title.push_str(" ↗");
5316 }
5317
5318 if let Some(last_title) = self.last_window_title.as_ref()
5319 && &title == last_title
5320 {
5321 return;
5322 }
5323 window.set_window_title(&title);
5324 SystemWindowTabController::update_tab_title(
5325 cx,
5326 window.window_handle().window_id(),
5327 SharedString::from(&title),
5328 );
5329 self.last_window_title = Some(title);
5330 }
5331
5332 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5333 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5334 if is_edited != self.window_edited {
5335 self.window_edited = is_edited;
5336 window.set_window_edited(self.window_edited)
5337 }
5338 }
5339
5340 fn update_item_dirty_state(
5341 &mut self,
5342 item: &dyn ItemHandle,
5343 window: &mut Window,
5344 cx: &mut App,
5345 ) {
5346 let is_dirty = item.is_dirty(cx);
5347 let item_id = item.item_id();
5348 let was_dirty = self.dirty_items.contains_key(&item_id);
5349 if is_dirty == was_dirty {
5350 return;
5351 }
5352 if was_dirty {
5353 self.dirty_items.remove(&item_id);
5354 self.update_window_edited(window, cx);
5355 return;
5356 }
5357
5358 let workspace = self.weak_handle();
5359 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5360 return;
5361 };
5362 let on_release_callback = Box::new(move |cx: &mut App| {
5363 window_handle
5364 .update(cx, |_, window, cx| {
5365 workspace
5366 .update(cx, |workspace, cx| {
5367 workspace.dirty_items.remove(&item_id);
5368 workspace.update_window_edited(window, cx)
5369 })
5370 .ok();
5371 })
5372 .ok();
5373 });
5374
5375 let s = item.on_release(cx, on_release_callback);
5376 self.dirty_items.insert(item_id, s);
5377 self.update_window_edited(window, cx);
5378 }
5379
5380 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5381 if self.notifications.is_empty() {
5382 None
5383 } else {
5384 Some(
5385 div()
5386 .absolute()
5387 .right_3()
5388 .bottom_3()
5389 .w_112()
5390 .h_full()
5391 .flex()
5392 .flex_col()
5393 .justify_end()
5394 .gap_2()
5395 .children(
5396 self.notifications
5397 .iter()
5398 .map(|(_, notification)| notification.clone().into_any()),
5399 ),
5400 )
5401 }
5402 }
5403
5404 // RPC handlers
5405
5406 fn active_view_for_follower(
5407 &self,
5408 follower_project_id: Option<u64>,
5409 window: &mut Window,
5410 cx: &mut Context<Self>,
5411 ) -> Option<proto::View> {
5412 let (item, panel_id) = self.active_item_for_followers(window, cx);
5413 let item = item?;
5414 let leader_id = self
5415 .pane_for(&*item)
5416 .and_then(|pane| self.leader_for_pane(&pane));
5417 let leader_peer_id = match leader_id {
5418 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5419 Some(CollaboratorId::Agent) | None => None,
5420 };
5421
5422 let item_handle = item.to_followable_item_handle(cx)?;
5423 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5424 let variant = item_handle.to_state_proto(window, cx)?;
5425
5426 if item_handle.is_project_item(window, cx)
5427 && (follower_project_id.is_none()
5428 || follower_project_id != self.project.read(cx).remote_id())
5429 {
5430 return None;
5431 }
5432
5433 Some(proto::View {
5434 id: id.to_proto(),
5435 leader_id: leader_peer_id,
5436 variant: Some(variant),
5437 panel_id: panel_id.map(|id| id as i32),
5438 })
5439 }
5440
5441 fn handle_follow(
5442 &mut self,
5443 follower_project_id: Option<u64>,
5444 window: &mut Window,
5445 cx: &mut Context<Self>,
5446 ) -> proto::FollowResponse {
5447 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5448
5449 cx.notify();
5450 proto::FollowResponse {
5451 views: active_view.iter().cloned().collect(),
5452 active_view,
5453 }
5454 }
5455
5456 fn handle_update_followers(
5457 &mut self,
5458 leader_id: PeerId,
5459 message: proto::UpdateFollowers,
5460 _window: &mut Window,
5461 _cx: &mut Context<Self>,
5462 ) {
5463 self.leader_updates_tx
5464 .unbounded_send((leader_id, message))
5465 .ok();
5466 }
5467
5468 async fn process_leader_update(
5469 this: &WeakEntity<Self>,
5470 leader_id: PeerId,
5471 update: proto::UpdateFollowers,
5472 cx: &mut AsyncWindowContext,
5473 ) -> Result<()> {
5474 match update.variant.context("invalid update")? {
5475 proto::update_followers::Variant::CreateView(view) => {
5476 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5477 let should_add_view = this.update(cx, |this, _| {
5478 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5479 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5480 } else {
5481 anyhow::Ok(false)
5482 }
5483 })??;
5484
5485 if should_add_view {
5486 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5487 }
5488 }
5489 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5490 let should_add_view = this.update(cx, |this, _| {
5491 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5492 state.active_view_id = update_active_view
5493 .view
5494 .as_ref()
5495 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5496
5497 if state.active_view_id.is_some_and(|view_id| {
5498 !state.items_by_leader_view_id.contains_key(&view_id)
5499 }) {
5500 anyhow::Ok(true)
5501 } else {
5502 anyhow::Ok(false)
5503 }
5504 } else {
5505 anyhow::Ok(false)
5506 }
5507 })??;
5508
5509 if should_add_view && let Some(view) = update_active_view.view {
5510 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5511 }
5512 }
5513 proto::update_followers::Variant::UpdateView(update_view) => {
5514 let variant = update_view.variant.context("missing update view variant")?;
5515 let id = update_view.id.context("missing update view id")?;
5516 let mut tasks = Vec::new();
5517 this.update_in(cx, |this, window, cx| {
5518 let project = this.project.clone();
5519 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5520 let view_id = ViewId::from_proto(id.clone())?;
5521 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5522 tasks.push(item.view.apply_update_proto(
5523 &project,
5524 variant.clone(),
5525 window,
5526 cx,
5527 ));
5528 }
5529 }
5530 anyhow::Ok(())
5531 })??;
5532 try_join_all(tasks).await.log_err();
5533 }
5534 }
5535 this.update_in(cx, |this, window, cx| {
5536 this.leader_updated(leader_id, window, cx)
5537 })?;
5538 Ok(())
5539 }
5540
5541 async fn add_view_from_leader(
5542 this: WeakEntity<Self>,
5543 leader_id: PeerId,
5544 view: &proto::View,
5545 cx: &mut AsyncWindowContext,
5546 ) -> Result<()> {
5547 let this = this.upgrade().context("workspace dropped")?;
5548
5549 let Some(id) = view.id.clone() else {
5550 anyhow::bail!("no id for view");
5551 };
5552 let id = ViewId::from_proto(id)?;
5553 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5554
5555 let pane = this.update(cx, |this, _cx| {
5556 let state = this
5557 .follower_states
5558 .get(&leader_id.into())
5559 .context("stopped following")?;
5560 anyhow::Ok(state.pane().clone())
5561 })?;
5562 let existing_item = pane.update_in(cx, |pane, window, cx| {
5563 let client = this.read(cx).client().clone();
5564 pane.items().find_map(|item| {
5565 let item = item.to_followable_item_handle(cx)?;
5566 if item.remote_id(&client, window, cx) == Some(id) {
5567 Some(item)
5568 } else {
5569 None
5570 }
5571 })
5572 })?;
5573 let item = if let Some(existing_item) = existing_item {
5574 existing_item
5575 } else {
5576 let variant = view.variant.clone();
5577 anyhow::ensure!(variant.is_some(), "missing view variant");
5578
5579 let task = cx.update(|window, cx| {
5580 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5581 })?;
5582
5583 let Some(task) = task else {
5584 anyhow::bail!(
5585 "failed to construct view from leader (maybe from a different version of zed?)"
5586 );
5587 };
5588
5589 let mut new_item = task.await?;
5590 pane.update_in(cx, |pane, window, cx| {
5591 let mut item_to_remove = None;
5592 for (ix, item) in pane.items().enumerate() {
5593 if let Some(item) = item.to_followable_item_handle(cx) {
5594 match new_item.dedup(item.as_ref(), window, cx) {
5595 Some(item::Dedup::KeepExisting) => {
5596 new_item =
5597 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5598 break;
5599 }
5600 Some(item::Dedup::ReplaceExisting) => {
5601 item_to_remove = Some((ix, item.item_id()));
5602 break;
5603 }
5604 None => {}
5605 }
5606 }
5607 }
5608
5609 if let Some((ix, id)) = item_to_remove {
5610 pane.remove_item(id, false, false, window, cx);
5611 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5612 }
5613 })?;
5614
5615 new_item
5616 };
5617
5618 this.update_in(cx, |this, window, cx| {
5619 let state = this.follower_states.get_mut(&leader_id.into())?;
5620 item.set_leader_id(Some(leader_id.into()), window, cx);
5621 state.items_by_leader_view_id.insert(
5622 id,
5623 FollowerView {
5624 view: item,
5625 location: panel_id,
5626 },
5627 );
5628
5629 Some(())
5630 })
5631 .context("no follower state")?;
5632
5633 Ok(())
5634 }
5635
5636 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5637 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5638 return;
5639 };
5640
5641 if let Some(agent_location) = self.project.read(cx).agent_location() {
5642 let buffer_entity_id = agent_location.buffer.entity_id();
5643 let view_id = ViewId {
5644 creator: CollaboratorId::Agent,
5645 id: buffer_entity_id.as_u64(),
5646 };
5647 follower_state.active_view_id = Some(view_id);
5648
5649 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5650 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5651 hash_map::Entry::Vacant(entry) => {
5652 let existing_view =
5653 follower_state
5654 .center_pane
5655 .read(cx)
5656 .items()
5657 .find_map(|item| {
5658 let item = item.to_followable_item_handle(cx)?;
5659 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5660 && item.project_item_model_ids(cx).as_slice()
5661 == [buffer_entity_id]
5662 {
5663 Some(item)
5664 } else {
5665 None
5666 }
5667 });
5668 let view = existing_view.or_else(|| {
5669 agent_location.buffer.upgrade().and_then(|buffer| {
5670 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
5671 registry.build_item(buffer, self.project.clone(), None, window, cx)
5672 })?
5673 .to_followable_item_handle(cx)
5674 })
5675 });
5676
5677 view.map(|view| {
5678 entry.insert(FollowerView {
5679 view,
5680 location: None,
5681 })
5682 })
5683 }
5684 };
5685
5686 if let Some(item) = item {
5687 item.view
5688 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
5689 item.view
5690 .update_agent_location(agent_location.position, window, cx);
5691 }
5692 } else {
5693 follower_state.active_view_id = None;
5694 }
5695
5696 self.leader_updated(CollaboratorId::Agent, window, cx);
5697 }
5698
5699 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
5700 let mut is_project_item = true;
5701 let mut update = proto::UpdateActiveView::default();
5702 if window.is_window_active() {
5703 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
5704
5705 if let Some(item) = active_item
5706 && item.item_focus_handle(cx).contains_focused(window, cx)
5707 {
5708 let leader_id = self
5709 .pane_for(&*item)
5710 .and_then(|pane| self.leader_for_pane(&pane));
5711 let leader_peer_id = match leader_id {
5712 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5713 Some(CollaboratorId::Agent) | None => None,
5714 };
5715
5716 if let Some(item) = item.to_followable_item_handle(cx) {
5717 let id = item
5718 .remote_id(&self.app_state.client, window, cx)
5719 .map(|id| id.to_proto());
5720
5721 if let Some(id) = id
5722 && let Some(variant) = item.to_state_proto(window, cx)
5723 {
5724 let view = Some(proto::View {
5725 id,
5726 leader_id: leader_peer_id,
5727 variant: Some(variant),
5728 panel_id: panel_id.map(|id| id as i32),
5729 });
5730
5731 is_project_item = item.is_project_item(window, cx);
5732 update = proto::UpdateActiveView { view };
5733 };
5734 }
5735 }
5736 }
5737
5738 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
5739 if active_view_id != self.last_active_view_id.as_ref() {
5740 self.last_active_view_id = active_view_id.cloned();
5741 self.update_followers(
5742 is_project_item,
5743 proto::update_followers::Variant::UpdateActiveView(update),
5744 window,
5745 cx,
5746 );
5747 }
5748 }
5749
5750 fn active_item_for_followers(
5751 &self,
5752 window: &mut Window,
5753 cx: &mut App,
5754 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
5755 let mut active_item = None;
5756 let mut panel_id = None;
5757 for dock in self.all_docks() {
5758 if dock.focus_handle(cx).contains_focused(window, cx)
5759 && let Some(panel) = dock.read(cx).active_panel()
5760 && let Some(pane) = panel.pane(cx)
5761 && let Some(item) = pane.read(cx).active_item()
5762 {
5763 active_item = Some(item);
5764 panel_id = panel.remote_id();
5765 break;
5766 }
5767 }
5768
5769 if active_item.is_none() {
5770 active_item = self.active_pane().read(cx).active_item();
5771 }
5772 (active_item, panel_id)
5773 }
5774
5775 fn update_followers(
5776 &self,
5777 project_only: bool,
5778 update: proto::update_followers::Variant,
5779 _: &mut Window,
5780 cx: &mut App,
5781 ) -> Option<()> {
5782 // If this update only applies to for followers in the current project,
5783 // then skip it unless this project is shared. If it applies to all
5784 // followers, regardless of project, then set `project_id` to none,
5785 // indicating that it goes to all followers.
5786 let project_id = if project_only {
5787 Some(self.project.read(cx).remote_id()?)
5788 } else {
5789 None
5790 };
5791 self.app_state().workspace_store.update(cx, |store, cx| {
5792 store.update_followers(project_id, update, cx)
5793 })
5794 }
5795
5796 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
5797 self.follower_states.iter().find_map(|(leader_id, state)| {
5798 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
5799 Some(*leader_id)
5800 } else {
5801 None
5802 }
5803 })
5804 }
5805
5806 fn leader_updated(
5807 &mut self,
5808 leader_id: impl Into<CollaboratorId>,
5809 window: &mut Window,
5810 cx: &mut Context<Self>,
5811 ) -> Option<Box<dyn ItemHandle>> {
5812 cx.notify();
5813
5814 let leader_id = leader_id.into();
5815 let (panel_id, item) = match leader_id {
5816 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
5817 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
5818 };
5819
5820 let state = self.follower_states.get(&leader_id)?;
5821 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
5822 let pane;
5823 if let Some(panel_id) = panel_id {
5824 pane = self
5825 .activate_panel_for_proto_id(panel_id, window, cx)?
5826 .pane(cx)?;
5827 let state = self.follower_states.get_mut(&leader_id)?;
5828 state.dock_pane = Some(pane.clone());
5829 } else {
5830 pane = state.center_pane.clone();
5831 let state = self.follower_states.get_mut(&leader_id)?;
5832 if let Some(dock_pane) = state.dock_pane.take() {
5833 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
5834 }
5835 }
5836
5837 pane.update(cx, |pane, cx| {
5838 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
5839 if let Some(index) = pane.index_for_item(item.as_ref()) {
5840 pane.activate_item(index, false, false, window, cx);
5841 } else {
5842 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
5843 }
5844
5845 if focus_active_item {
5846 pane.focus_active_item(window, cx)
5847 }
5848 });
5849
5850 Some(item)
5851 }
5852
5853 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
5854 let state = self.follower_states.get(&CollaboratorId::Agent)?;
5855 let active_view_id = state.active_view_id?;
5856 Some(
5857 state
5858 .items_by_leader_view_id
5859 .get(&active_view_id)?
5860 .view
5861 .boxed_clone(),
5862 )
5863 }
5864
5865 fn active_item_for_peer(
5866 &self,
5867 peer_id: PeerId,
5868 window: &mut Window,
5869 cx: &mut Context<Self>,
5870 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
5871 let call = self.active_call()?;
5872 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
5873 let leader_in_this_app;
5874 let leader_in_this_project;
5875 match participant.location {
5876 ParticipantLocation::SharedProject { project_id } => {
5877 leader_in_this_app = true;
5878 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
5879 }
5880 ParticipantLocation::UnsharedProject => {
5881 leader_in_this_app = true;
5882 leader_in_this_project = false;
5883 }
5884 ParticipantLocation::External => {
5885 leader_in_this_app = false;
5886 leader_in_this_project = false;
5887 }
5888 };
5889 let state = self.follower_states.get(&peer_id.into())?;
5890 let mut item_to_activate = None;
5891 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
5892 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
5893 && (leader_in_this_project || !item.view.is_project_item(window, cx))
5894 {
5895 item_to_activate = Some((item.location, item.view.boxed_clone()));
5896 }
5897 } else if let Some(shared_screen) =
5898 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
5899 {
5900 item_to_activate = Some((None, Box::new(shared_screen)));
5901 }
5902 item_to_activate
5903 }
5904
5905 fn shared_screen_for_peer(
5906 &self,
5907 peer_id: PeerId,
5908 pane: &Entity<Pane>,
5909 window: &mut Window,
5910 cx: &mut App,
5911 ) -> Option<Entity<SharedScreen>> {
5912 self.active_call()?
5913 .create_shared_screen(peer_id, pane, window, cx)
5914 }
5915
5916 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5917 if window.is_window_active() {
5918 self.update_active_view_for_followers(window, cx);
5919
5920 if let Some(database_id) = self.database_id {
5921 cx.background_spawn(persistence::DB.update_timestamp(database_id))
5922 .detach();
5923 }
5924 } else {
5925 for pane in &self.panes {
5926 pane.update(cx, |pane, cx| {
5927 if let Some(item) = pane.active_item() {
5928 item.workspace_deactivated(window, cx);
5929 }
5930 for item in pane.items() {
5931 if matches!(
5932 item.workspace_settings(cx).autosave,
5933 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
5934 ) {
5935 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
5936 .detach_and_log_err(cx);
5937 }
5938 }
5939 });
5940 }
5941 }
5942 }
5943
5944 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
5945 self.active_call.as_ref().map(|(call, _)| &*call.0)
5946 }
5947
5948 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
5949 self.active_call.as_ref().map(|(call, _)| call.clone())
5950 }
5951
5952 fn on_active_call_event(
5953 &mut self,
5954 event: &ActiveCallEvent,
5955 window: &mut Window,
5956 cx: &mut Context<Self>,
5957 ) {
5958 match event {
5959 ActiveCallEvent::ParticipantLocationChanged { participant_id }
5960 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
5961 self.leader_updated(participant_id, window, cx);
5962 }
5963 }
5964 }
5965
5966 pub fn database_id(&self) -> Option<WorkspaceId> {
5967 self.database_id
5968 }
5969
5970 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
5971 self.database_id = Some(id);
5972 }
5973
5974 pub fn session_id(&self) -> Option<String> {
5975 self.session_id.clone()
5976 }
5977
5978 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
5979 let Some(display) = window.display(cx) else {
5980 return Task::ready(());
5981 };
5982 let Ok(display_uuid) = display.uuid() else {
5983 return Task::ready(());
5984 };
5985
5986 let window_bounds = window.inner_window_bounds();
5987 let database_id = self.database_id;
5988 let has_paths = !self.root_paths(cx).is_empty();
5989
5990 cx.background_executor().spawn(async move {
5991 if !has_paths {
5992 persistence::write_default_window_bounds(window_bounds, display_uuid)
5993 .await
5994 .log_err();
5995 }
5996 if let Some(database_id) = database_id {
5997 DB.set_window_open_status(
5998 database_id,
5999 SerializedWindowBounds(window_bounds),
6000 display_uuid,
6001 )
6002 .await
6003 .log_err();
6004 } else {
6005 persistence::write_default_window_bounds(window_bounds, display_uuid)
6006 .await
6007 .log_err();
6008 }
6009 })
6010 }
6011
6012 /// Bypass the 200ms serialization throttle and write workspace state to
6013 /// the DB immediately. Returns a task the caller can await to ensure the
6014 /// write completes. Used by the quit handler so the most recent state
6015 /// isn't lost to a pending throttle timer when the process exits.
6016 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6017 self._schedule_serialize_workspace.take();
6018 self._serialize_workspace_task.take();
6019 self.bounds_save_task_queued.take();
6020
6021 let bounds_task = self.save_window_bounds(window, cx);
6022 let serialize_task = self.serialize_workspace_internal(window, cx);
6023 cx.spawn(async move |_| {
6024 bounds_task.await;
6025 serialize_task.await;
6026 })
6027 }
6028
6029 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6030 let project = self.project().read(cx);
6031 project
6032 .visible_worktrees(cx)
6033 .map(|worktree| worktree.read(cx).abs_path())
6034 .collect::<Vec<_>>()
6035 }
6036
6037 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6038 match member {
6039 Member::Axis(PaneAxis { members, .. }) => {
6040 for child in members.iter() {
6041 self.remove_panes(child.clone(), window, cx)
6042 }
6043 }
6044 Member::Pane(pane) => {
6045 self.force_remove_pane(&pane, &None, window, cx);
6046 }
6047 }
6048 }
6049
6050 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6051 self.session_id.take();
6052 self.serialize_workspace_internal(window, cx)
6053 }
6054
6055 fn force_remove_pane(
6056 &mut self,
6057 pane: &Entity<Pane>,
6058 focus_on: &Option<Entity<Pane>>,
6059 window: &mut Window,
6060 cx: &mut Context<Workspace>,
6061 ) {
6062 self.panes.retain(|p| p != pane);
6063 if let Some(focus_on) = focus_on {
6064 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6065 } else if self.active_pane() == pane {
6066 self.panes
6067 .last()
6068 .unwrap()
6069 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6070 }
6071 if self.last_active_center_pane == Some(pane.downgrade()) {
6072 self.last_active_center_pane = None;
6073 }
6074 cx.notify();
6075 }
6076
6077 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6078 if self._schedule_serialize_workspace.is_none() {
6079 self._schedule_serialize_workspace =
6080 Some(cx.spawn_in(window, async move |this, cx| {
6081 cx.background_executor()
6082 .timer(SERIALIZATION_THROTTLE_TIME)
6083 .await;
6084 this.update_in(cx, |this, window, cx| {
6085 this._serialize_workspace_task =
6086 Some(this.serialize_workspace_internal(window, cx));
6087 this._schedule_serialize_workspace.take();
6088 })
6089 .log_err();
6090 }));
6091 }
6092 }
6093
6094 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6095 let Some(database_id) = self.database_id() else {
6096 return Task::ready(());
6097 };
6098
6099 fn serialize_pane_handle(
6100 pane_handle: &Entity<Pane>,
6101 window: &mut Window,
6102 cx: &mut App,
6103 ) -> SerializedPane {
6104 let (items, active, pinned_count) = {
6105 let pane = pane_handle.read(cx);
6106 let active_item_id = pane.active_item().map(|item| item.item_id());
6107 (
6108 pane.items()
6109 .filter_map(|handle| {
6110 let handle = handle.to_serializable_item_handle(cx)?;
6111
6112 Some(SerializedItem {
6113 kind: Arc::from(handle.serialized_item_kind()),
6114 item_id: handle.item_id().as_u64(),
6115 active: Some(handle.item_id()) == active_item_id,
6116 preview: pane.is_active_preview_item(handle.item_id()),
6117 })
6118 })
6119 .collect::<Vec<_>>(),
6120 pane.has_focus(window, cx),
6121 pane.pinned_count(),
6122 )
6123 };
6124
6125 SerializedPane::new(items, active, pinned_count)
6126 }
6127
6128 fn build_serialized_pane_group(
6129 pane_group: &Member,
6130 window: &mut Window,
6131 cx: &mut App,
6132 ) -> SerializedPaneGroup {
6133 match pane_group {
6134 Member::Axis(PaneAxis {
6135 axis,
6136 members,
6137 flexes,
6138 bounding_boxes: _,
6139 }) => SerializedPaneGroup::Group {
6140 axis: SerializedAxis(*axis),
6141 children: members
6142 .iter()
6143 .map(|member| build_serialized_pane_group(member, window, cx))
6144 .collect::<Vec<_>>(),
6145 flexes: Some(flexes.lock().clone()),
6146 },
6147 Member::Pane(pane_handle) => {
6148 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6149 }
6150 }
6151 }
6152
6153 fn build_serialized_docks(
6154 this: &Workspace,
6155 window: &mut Window,
6156 cx: &mut App,
6157 ) -> DockStructure {
6158 this.capture_dock_state(window, cx)
6159 }
6160
6161 match self.workspace_location(cx) {
6162 WorkspaceLocation::Location(location, paths) => {
6163 let breakpoints = self.project.update(cx, |project, cx| {
6164 project
6165 .breakpoint_store()
6166 .read(cx)
6167 .all_source_breakpoints(cx)
6168 });
6169 let user_toolchains = self
6170 .project
6171 .read(cx)
6172 .user_toolchains(cx)
6173 .unwrap_or_default();
6174
6175 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6176 let docks = build_serialized_docks(self, window, cx);
6177 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6178
6179 let serialized_workspace = SerializedWorkspace {
6180 id: database_id,
6181 location,
6182 paths,
6183 center_group,
6184 window_bounds,
6185 display: Default::default(),
6186 docks,
6187 centered_layout: self.centered_layout,
6188 session_id: self.session_id.clone(),
6189 breakpoints,
6190 window_id: Some(window.window_handle().window_id().as_u64()),
6191 user_toolchains,
6192 };
6193
6194 window.spawn(cx, async move |_| {
6195 persistence::DB.save_workspace(serialized_workspace).await;
6196 })
6197 }
6198 WorkspaceLocation::DetachFromSession => {
6199 let window_bounds = SerializedWindowBounds(window.window_bounds());
6200 let display = window.display(cx).and_then(|d| d.uuid().ok());
6201 // Save dock state for empty local workspaces
6202 let docks = build_serialized_docks(self, window, cx);
6203 window.spawn(cx, async move |_| {
6204 persistence::DB
6205 .set_window_open_status(
6206 database_id,
6207 window_bounds,
6208 display.unwrap_or_default(),
6209 )
6210 .await
6211 .log_err();
6212 persistence::DB
6213 .set_session_id(database_id, None)
6214 .await
6215 .log_err();
6216 persistence::write_default_dock_state(docks).await.log_err();
6217 })
6218 }
6219 WorkspaceLocation::None => {
6220 // Save dock state for empty non-local workspaces
6221 let docks = build_serialized_docks(self, window, cx);
6222 window.spawn(cx, async move |_| {
6223 persistence::write_default_dock_state(docks).await.log_err();
6224 })
6225 }
6226 }
6227 }
6228
6229 fn has_any_items_open(&self, cx: &App) -> bool {
6230 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6231 }
6232
6233 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6234 let paths = PathList::new(&self.root_paths(cx));
6235 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6236 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6237 } else if self.project.read(cx).is_local() {
6238 if !paths.is_empty() || self.has_any_items_open(cx) {
6239 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6240 } else {
6241 WorkspaceLocation::DetachFromSession
6242 }
6243 } else {
6244 WorkspaceLocation::None
6245 }
6246 }
6247
6248 fn update_history(&self, cx: &mut App) {
6249 let Some(id) = self.database_id() else {
6250 return;
6251 };
6252 if !self.project.read(cx).is_local() {
6253 return;
6254 }
6255 if let Some(manager) = HistoryManager::global(cx) {
6256 let paths = PathList::new(&self.root_paths(cx));
6257 manager.update(cx, |this, cx| {
6258 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6259 });
6260 }
6261 }
6262
6263 async fn serialize_items(
6264 this: &WeakEntity<Self>,
6265 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6266 cx: &mut AsyncWindowContext,
6267 ) -> Result<()> {
6268 const CHUNK_SIZE: usize = 200;
6269
6270 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6271
6272 while let Some(items_received) = serializable_items.next().await {
6273 let unique_items =
6274 items_received
6275 .into_iter()
6276 .fold(HashMap::default(), |mut acc, item| {
6277 acc.entry(item.item_id()).or_insert(item);
6278 acc
6279 });
6280
6281 // We use into_iter() here so that the references to the items are moved into
6282 // the tasks and not kept alive while we're sleeping.
6283 for (_, item) in unique_items.into_iter() {
6284 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6285 item.serialize(workspace, false, window, cx)
6286 }) {
6287 cx.background_spawn(async move { task.await.log_err() })
6288 .detach();
6289 }
6290 }
6291
6292 cx.background_executor()
6293 .timer(SERIALIZATION_THROTTLE_TIME)
6294 .await;
6295 }
6296
6297 Ok(())
6298 }
6299
6300 pub(crate) fn enqueue_item_serialization(
6301 &mut self,
6302 item: Box<dyn SerializableItemHandle>,
6303 ) -> Result<()> {
6304 self.serializable_items_tx
6305 .unbounded_send(item)
6306 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6307 }
6308
6309 pub(crate) fn load_workspace(
6310 serialized_workspace: SerializedWorkspace,
6311 paths_to_open: Vec<Option<ProjectPath>>,
6312 window: &mut Window,
6313 cx: &mut Context<Workspace>,
6314 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6315 cx.spawn_in(window, async move |workspace, cx| {
6316 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6317
6318 let mut center_group = None;
6319 let mut center_items = None;
6320
6321 // Traverse the splits tree and add to things
6322 if let Some((group, active_pane, items)) = serialized_workspace
6323 .center_group
6324 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6325 .await
6326 {
6327 center_items = Some(items);
6328 center_group = Some((group, active_pane))
6329 }
6330
6331 let mut items_by_project_path = HashMap::default();
6332 let mut item_ids_by_kind = HashMap::default();
6333 let mut all_deserialized_items = Vec::default();
6334 cx.update(|_, cx| {
6335 for item in center_items.unwrap_or_default().into_iter().flatten() {
6336 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6337 item_ids_by_kind
6338 .entry(serializable_item_handle.serialized_item_kind())
6339 .or_insert(Vec::new())
6340 .push(item.item_id().as_u64() as ItemId);
6341 }
6342
6343 if let Some(project_path) = item.project_path(cx) {
6344 items_by_project_path.insert(project_path, item.clone());
6345 }
6346 all_deserialized_items.push(item);
6347 }
6348 })?;
6349
6350 let opened_items = paths_to_open
6351 .into_iter()
6352 .map(|path_to_open| {
6353 path_to_open
6354 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6355 })
6356 .collect::<Vec<_>>();
6357
6358 // Remove old panes from workspace panes list
6359 workspace.update_in(cx, |workspace, window, cx| {
6360 if let Some((center_group, active_pane)) = center_group {
6361 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6362
6363 // Swap workspace center group
6364 workspace.center = PaneGroup::with_root(center_group);
6365 workspace.center.set_is_center(true);
6366 workspace.center.mark_positions(cx);
6367
6368 if let Some(active_pane) = active_pane {
6369 workspace.set_active_pane(&active_pane, window, cx);
6370 cx.focus_self(window);
6371 } else {
6372 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6373 }
6374 }
6375
6376 let docks = serialized_workspace.docks;
6377
6378 for (dock, serialized_dock) in [
6379 (&mut workspace.right_dock, docks.right),
6380 (&mut workspace.left_dock, docks.left),
6381 (&mut workspace.bottom_dock, docks.bottom),
6382 ]
6383 .iter_mut()
6384 {
6385 dock.update(cx, |dock, cx| {
6386 dock.serialized_dock = Some(serialized_dock.clone());
6387 dock.restore_state(window, cx);
6388 });
6389 }
6390
6391 cx.notify();
6392 })?;
6393
6394 let _ = project
6395 .update(cx, |project, cx| {
6396 project
6397 .breakpoint_store()
6398 .update(cx, |breakpoint_store, cx| {
6399 breakpoint_store
6400 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6401 })
6402 })
6403 .await;
6404
6405 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6406 // after loading the items, we might have different items and in order to avoid
6407 // the database filling up, we delete items that haven't been loaded now.
6408 //
6409 // The items that have been loaded, have been saved after they've been added to the workspace.
6410 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6411 item_ids_by_kind
6412 .into_iter()
6413 .map(|(item_kind, loaded_items)| {
6414 SerializableItemRegistry::cleanup(
6415 item_kind,
6416 serialized_workspace.id,
6417 loaded_items,
6418 window,
6419 cx,
6420 )
6421 .log_err()
6422 })
6423 .collect::<Vec<_>>()
6424 })?;
6425
6426 futures::future::join_all(clean_up_tasks).await;
6427
6428 workspace
6429 .update_in(cx, |workspace, window, cx| {
6430 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6431 workspace.serialize_workspace_internal(window, cx).detach();
6432
6433 // Ensure that we mark the window as edited if we did load dirty items
6434 workspace.update_window_edited(window, cx);
6435 })
6436 .ok();
6437
6438 Ok(opened_items)
6439 })
6440 }
6441
6442 pub fn key_context(&self, cx: &App) -> KeyContext {
6443 let mut context = KeyContext::new_with_defaults();
6444 context.add("Workspace");
6445 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6446 if let Some(status) = self
6447 .debugger_provider
6448 .as_ref()
6449 .and_then(|provider| provider.active_thread_state(cx))
6450 {
6451 match status {
6452 ThreadStatus::Running | ThreadStatus::Stepping => {
6453 context.add("debugger_running");
6454 }
6455 ThreadStatus::Stopped => context.add("debugger_stopped"),
6456 ThreadStatus::Exited | ThreadStatus::Ended => {}
6457 }
6458 }
6459
6460 if self.left_dock.read(cx).is_open() {
6461 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6462 context.set("left_dock", active_panel.panel_key());
6463 }
6464 }
6465
6466 if self.right_dock.read(cx).is_open() {
6467 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6468 context.set("right_dock", active_panel.panel_key());
6469 }
6470 }
6471
6472 if self.bottom_dock.read(cx).is_open() {
6473 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6474 context.set("bottom_dock", active_panel.panel_key());
6475 }
6476 }
6477
6478 context
6479 }
6480
6481 /// Multiworkspace uses this to add workspace action handling to itself
6482 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6483 self.add_workspace_actions_listeners(div, window, cx)
6484 .on_action(cx.listener(
6485 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6486 for action in &action_sequence.0 {
6487 window.dispatch_action(action.boxed_clone(), cx);
6488 }
6489 },
6490 ))
6491 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6492 .on_action(cx.listener(Self::close_all_items_and_panes))
6493 .on_action(cx.listener(Self::close_item_in_all_panes))
6494 .on_action(cx.listener(Self::save_all))
6495 .on_action(cx.listener(Self::send_keystrokes))
6496 .on_action(cx.listener(Self::add_folder_to_project))
6497 .on_action(cx.listener(Self::follow_next_collaborator))
6498 .on_action(cx.listener(Self::activate_pane_at_index))
6499 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6500 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6501 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6502 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6503 let pane = workspace.active_pane().clone();
6504 workspace.unfollow_in_pane(&pane, window, cx);
6505 }))
6506 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6507 workspace
6508 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6509 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6510 }))
6511 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6512 workspace
6513 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6514 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6515 }))
6516 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6517 workspace
6518 .save_active_item(SaveIntent::SaveAs, window, cx)
6519 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6520 }))
6521 .on_action(
6522 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6523 workspace.activate_previous_pane(window, cx)
6524 }),
6525 )
6526 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6527 workspace.activate_next_pane(window, cx)
6528 }))
6529 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6530 workspace.activate_last_pane(window, cx)
6531 }))
6532 .on_action(
6533 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6534 workspace.activate_next_window(cx)
6535 }),
6536 )
6537 .on_action(
6538 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6539 workspace.activate_previous_window(cx)
6540 }),
6541 )
6542 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6543 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6544 }))
6545 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6546 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6547 }))
6548 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6549 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6550 }))
6551 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6552 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6553 }))
6554 .on_action(cx.listener(
6555 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6556 workspace.move_item_to_pane_in_direction(action, window, cx)
6557 },
6558 ))
6559 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6560 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6561 }))
6562 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6563 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6564 }))
6565 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6566 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6567 }))
6568 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6569 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6570 }))
6571 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6572 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6573 SplitDirection::Down,
6574 SplitDirection::Up,
6575 SplitDirection::Right,
6576 SplitDirection::Left,
6577 ];
6578 for dir in DIRECTION_PRIORITY {
6579 if workspace.find_pane_in_direction(dir, cx).is_some() {
6580 workspace.swap_pane_in_direction(dir, cx);
6581 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6582 break;
6583 }
6584 }
6585 }))
6586 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6587 workspace.move_pane_to_border(SplitDirection::Left, cx)
6588 }))
6589 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6590 workspace.move_pane_to_border(SplitDirection::Right, cx)
6591 }))
6592 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6593 workspace.move_pane_to_border(SplitDirection::Up, cx)
6594 }))
6595 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6596 workspace.move_pane_to_border(SplitDirection::Down, cx)
6597 }))
6598 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6599 this.toggle_dock(DockPosition::Left, window, cx);
6600 }))
6601 .on_action(cx.listener(
6602 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6603 workspace.toggle_dock(DockPosition::Right, window, cx);
6604 },
6605 ))
6606 .on_action(cx.listener(
6607 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6608 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6609 },
6610 ))
6611 .on_action(cx.listener(
6612 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6613 if !workspace.close_active_dock(window, cx) {
6614 cx.propagate();
6615 }
6616 },
6617 ))
6618 .on_action(
6619 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6620 workspace.close_all_docks(window, cx);
6621 }),
6622 )
6623 .on_action(cx.listener(Self::toggle_all_docks))
6624 .on_action(cx.listener(
6625 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6626 workspace.clear_all_notifications(cx);
6627 },
6628 ))
6629 .on_action(cx.listener(
6630 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6631 workspace.clear_navigation_history(window, cx);
6632 },
6633 ))
6634 .on_action(cx.listener(
6635 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6636 if let Some((notification_id, _)) = workspace.notifications.pop() {
6637 workspace.suppress_notification(¬ification_id, cx);
6638 }
6639 },
6640 ))
6641 .on_action(cx.listener(
6642 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6643 workspace.show_worktree_trust_security_modal(true, window, cx);
6644 },
6645 ))
6646 .on_action(
6647 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6648 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6649 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6650 trusted_worktrees.clear_trusted_paths()
6651 });
6652 let clear_task = persistence::DB.clear_trusted_worktrees();
6653 cx.spawn(async move |_, cx| {
6654 if clear_task.await.log_err().is_some() {
6655 cx.update(|cx| reload(cx));
6656 }
6657 })
6658 .detach();
6659 }
6660 }),
6661 )
6662 .on_action(cx.listener(
6663 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
6664 workspace.reopen_closed_item(window, cx).detach();
6665 },
6666 ))
6667 .on_action(cx.listener(
6668 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
6669 for dock in workspace.all_docks() {
6670 if dock.focus_handle(cx).contains_focused(window, cx) {
6671 let Some(panel) = dock.read(cx).active_panel() else {
6672 return;
6673 };
6674
6675 // Set to `None`, then the size will fall back to the default.
6676 panel.clone().set_size(None, window, cx);
6677
6678 return;
6679 }
6680 }
6681 },
6682 ))
6683 .on_action(cx.listener(
6684 |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
6685 for dock in workspace.all_docks() {
6686 if let Some(panel) = dock.read(cx).visible_panel() {
6687 // Set to `None`, then the size will fall back to the default.
6688 panel.clone().set_size(None, window, cx);
6689 }
6690 }
6691 },
6692 ))
6693 .on_action(cx.listener(
6694 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
6695 adjust_active_dock_size_by_px(
6696 px_with_ui_font_fallback(act.px, cx),
6697 workspace,
6698 window,
6699 cx,
6700 );
6701 },
6702 ))
6703 .on_action(cx.listener(
6704 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
6705 adjust_active_dock_size_by_px(
6706 px_with_ui_font_fallback(act.px, cx) * -1.,
6707 workspace,
6708 window,
6709 cx,
6710 );
6711 },
6712 ))
6713 .on_action(cx.listener(
6714 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
6715 adjust_open_docks_size_by_px(
6716 px_with_ui_font_fallback(act.px, cx),
6717 workspace,
6718 window,
6719 cx,
6720 );
6721 },
6722 ))
6723 .on_action(cx.listener(
6724 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
6725 adjust_open_docks_size_by_px(
6726 px_with_ui_font_fallback(act.px, cx) * -1.,
6727 workspace,
6728 window,
6729 cx,
6730 );
6731 },
6732 ))
6733 .on_action(cx.listener(Workspace::toggle_centered_layout))
6734 .on_action(cx.listener(
6735 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
6736 if let Some(active_dock) = workspace.active_dock(window, cx) {
6737 let dock = active_dock.read(cx);
6738 if let Some(active_panel) = dock.active_panel() {
6739 if active_panel.pane(cx).is_none() {
6740 let mut recent_pane: Option<Entity<Pane>> = None;
6741 let mut recent_timestamp = 0;
6742 for pane_handle in workspace.panes() {
6743 let pane = pane_handle.read(cx);
6744 for entry in pane.activation_history() {
6745 if entry.timestamp > recent_timestamp {
6746 recent_timestamp = entry.timestamp;
6747 recent_pane = Some(pane_handle.clone());
6748 }
6749 }
6750 }
6751
6752 if let Some(pane) = recent_pane {
6753 pane.update(cx, |pane, cx| {
6754 let current_index = pane.active_item_index();
6755 let items_len = pane.items_len();
6756 if items_len > 0 {
6757 let next_index = if current_index + 1 < items_len {
6758 current_index + 1
6759 } else {
6760 0
6761 };
6762 pane.activate_item(
6763 next_index, false, false, window, cx,
6764 );
6765 }
6766 });
6767 return;
6768 }
6769 }
6770 }
6771 }
6772 cx.propagate();
6773 },
6774 ))
6775 .on_action(cx.listener(
6776 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
6777 if let Some(active_dock) = workspace.active_dock(window, cx) {
6778 let dock = active_dock.read(cx);
6779 if let Some(active_panel) = dock.active_panel() {
6780 if active_panel.pane(cx).is_none() {
6781 let mut recent_pane: Option<Entity<Pane>> = None;
6782 let mut recent_timestamp = 0;
6783 for pane_handle in workspace.panes() {
6784 let pane = pane_handle.read(cx);
6785 for entry in pane.activation_history() {
6786 if entry.timestamp > recent_timestamp {
6787 recent_timestamp = entry.timestamp;
6788 recent_pane = Some(pane_handle.clone());
6789 }
6790 }
6791 }
6792
6793 if let Some(pane) = recent_pane {
6794 pane.update(cx, |pane, cx| {
6795 let current_index = pane.active_item_index();
6796 let items_len = pane.items_len();
6797 if items_len > 0 {
6798 let prev_index = if current_index > 0 {
6799 current_index - 1
6800 } else {
6801 items_len.saturating_sub(1)
6802 };
6803 pane.activate_item(
6804 prev_index, false, false, window, cx,
6805 );
6806 }
6807 });
6808 return;
6809 }
6810 }
6811 }
6812 }
6813 cx.propagate();
6814 },
6815 ))
6816 .on_action(cx.listener(
6817 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
6818 if let Some(active_dock) = workspace.active_dock(window, cx) {
6819 let dock = active_dock.read(cx);
6820 if let Some(active_panel) = dock.active_panel() {
6821 if active_panel.pane(cx).is_none() {
6822 let active_pane = workspace.active_pane().clone();
6823 active_pane.update(cx, |pane, cx| {
6824 pane.close_active_item(action, window, cx)
6825 .detach_and_log_err(cx);
6826 });
6827 return;
6828 }
6829 }
6830 }
6831 cx.propagate();
6832 },
6833 ))
6834 .on_action(
6835 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
6836 let pane = workspace.active_pane().clone();
6837 if let Some(item) = pane.read(cx).active_item() {
6838 item.toggle_read_only(window, cx);
6839 }
6840 }),
6841 )
6842 .on_action(cx.listener(Workspace::cancel))
6843 }
6844
6845 #[cfg(any(test, feature = "test-support"))]
6846 pub fn set_random_database_id(&mut self) {
6847 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
6848 }
6849
6850 #[cfg(any(test, feature = "test-support"))]
6851 pub(crate) fn test_new(
6852 project: Entity<Project>,
6853 window: &mut Window,
6854 cx: &mut Context<Self>,
6855 ) -> Self {
6856 use node_runtime::NodeRuntime;
6857 use session::Session;
6858
6859 let client = project.read(cx).client();
6860 let user_store = project.read(cx).user_store();
6861 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
6862 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
6863 window.activate_window();
6864 let app_state = Arc::new(AppState {
6865 languages: project.read(cx).languages().clone(),
6866 workspace_store,
6867 client,
6868 user_store,
6869 fs: project.read(cx).fs().clone(),
6870 build_window_options: |_, _| Default::default(),
6871 node_runtime: NodeRuntime::unavailable(),
6872 session,
6873 });
6874 let workspace = Self::new(Default::default(), project, app_state, window, cx);
6875 workspace
6876 .active_pane
6877 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6878 workspace
6879 }
6880
6881 pub fn register_action<A: Action>(
6882 &mut self,
6883 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
6884 ) -> &mut Self {
6885 let callback = Arc::new(callback);
6886
6887 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
6888 let callback = callback.clone();
6889 div.on_action(cx.listener(move |workspace, event, window, cx| {
6890 (callback)(workspace, event, window, cx)
6891 }))
6892 }));
6893 self
6894 }
6895 pub fn register_action_renderer(
6896 &mut self,
6897 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
6898 ) -> &mut Self {
6899 self.workspace_actions.push(Box::new(callback));
6900 self
6901 }
6902
6903 fn add_workspace_actions_listeners(
6904 &self,
6905 mut div: Div,
6906 window: &mut Window,
6907 cx: &mut Context<Self>,
6908 ) -> Div {
6909 for action in self.workspace_actions.iter() {
6910 div = (action)(div, self, window, cx)
6911 }
6912 div
6913 }
6914
6915 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
6916 self.modal_layer.read(cx).has_active_modal()
6917 }
6918
6919 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
6920 self.modal_layer.read(cx).active_modal()
6921 }
6922
6923 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
6924 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
6925 /// If no modal is active, the new modal will be shown.
6926 ///
6927 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
6928 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
6929 /// will not be shown.
6930 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
6931 where
6932 B: FnOnce(&mut Window, &mut Context<V>) -> V,
6933 {
6934 self.modal_layer.update(cx, |modal_layer, cx| {
6935 modal_layer.toggle_modal(window, cx, build)
6936 })
6937 }
6938
6939 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
6940 self.modal_layer
6941 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
6942 }
6943
6944 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
6945 self.toast_layer
6946 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
6947 }
6948
6949 pub fn toggle_centered_layout(
6950 &mut self,
6951 _: &ToggleCenteredLayout,
6952 _: &mut Window,
6953 cx: &mut Context<Self>,
6954 ) {
6955 self.centered_layout = !self.centered_layout;
6956 if let Some(database_id) = self.database_id() {
6957 cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
6958 .detach_and_log_err(cx);
6959 }
6960 cx.notify();
6961 }
6962
6963 fn adjust_padding(padding: Option<f32>) -> f32 {
6964 padding
6965 .unwrap_or(CenteredPaddingSettings::default().0)
6966 .clamp(
6967 CenteredPaddingSettings::MIN_PADDING,
6968 CenteredPaddingSettings::MAX_PADDING,
6969 )
6970 }
6971
6972 fn render_dock(
6973 &self,
6974 position: DockPosition,
6975 dock: &Entity<Dock>,
6976 window: &mut Window,
6977 cx: &mut App,
6978 ) -> Option<Div> {
6979 if self.zoomed_position == Some(position) {
6980 return None;
6981 }
6982
6983 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
6984 let pane = panel.pane(cx)?;
6985 let follower_states = &self.follower_states;
6986 leader_border_for_pane(follower_states, &pane, window, cx)
6987 });
6988
6989 Some(
6990 div()
6991 .flex()
6992 .flex_none()
6993 .overflow_hidden()
6994 .child(dock.clone())
6995 .children(leader_border),
6996 )
6997 }
6998
6999 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7000 window
7001 .root::<MultiWorkspace>()
7002 .flatten()
7003 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7004 }
7005
7006 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7007 self.zoomed.as_ref()
7008 }
7009
7010 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7011 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7012 return;
7013 };
7014 let windows = cx.windows();
7015 let next_window =
7016 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7017 || {
7018 windows
7019 .iter()
7020 .cycle()
7021 .skip_while(|window| window.window_id() != current_window_id)
7022 .nth(1)
7023 },
7024 );
7025
7026 if let Some(window) = next_window {
7027 window
7028 .update(cx, |_, window, _| window.activate_window())
7029 .ok();
7030 }
7031 }
7032
7033 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7034 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7035 return;
7036 };
7037 let windows = cx.windows();
7038 let prev_window =
7039 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7040 || {
7041 windows
7042 .iter()
7043 .rev()
7044 .cycle()
7045 .skip_while(|window| window.window_id() != current_window_id)
7046 .nth(1)
7047 },
7048 );
7049
7050 if let Some(window) = prev_window {
7051 window
7052 .update(cx, |_, window, _| window.activate_window())
7053 .ok();
7054 }
7055 }
7056
7057 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7058 if cx.stop_active_drag(window) {
7059 } else if let Some((notification_id, _)) = self.notifications.pop() {
7060 dismiss_app_notification(¬ification_id, cx);
7061 } else {
7062 cx.propagate();
7063 }
7064 }
7065
7066 fn adjust_dock_size_by_px(
7067 &mut self,
7068 panel_size: Pixels,
7069 dock_pos: DockPosition,
7070 px: Pixels,
7071 window: &mut Window,
7072 cx: &mut Context<Self>,
7073 ) {
7074 match dock_pos {
7075 DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
7076 DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
7077 DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
7078 }
7079 }
7080
7081 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7082 let workspace_width = self.bounds.size.width;
7083 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7084
7085 self.right_dock.read_with(cx, |right_dock, cx| {
7086 let right_dock_size = right_dock
7087 .active_panel_size(window, cx)
7088 .unwrap_or(Pixels::ZERO);
7089 if right_dock_size + size > workspace_width {
7090 size = workspace_width - right_dock_size
7091 }
7092 });
7093
7094 self.left_dock.update(cx, |left_dock, cx| {
7095 if WorkspaceSettings::get_global(cx)
7096 .resize_all_panels_in_dock
7097 .contains(&DockPosition::Left)
7098 {
7099 left_dock.resize_all_panels(Some(size), window, cx);
7100 } else {
7101 left_dock.resize_active_panel(Some(size), window, cx);
7102 }
7103 });
7104 }
7105
7106 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7107 let workspace_width = self.bounds.size.width;
7108 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7109 self.left_dock.read_with(cx, |left_dock, cx| {
7110 let left_dock_size = left_dock
7111 .active_panel_size(window, cx)
7112 .unwrap_or(Pixels::ZERO);
7113 if left_dock_size + size > workspace_width {
7114 size = workspace_width - left_dock_size
7115 }
7116 });
7117 self.right_dock.update(cx, |right_dock, cx| {
7118 if WorkspaceSettings::get_global(cx)
7119 .resize_all_panels_in_dock
7120 .contains(&DockPosition::Right)
7121 {
7122 right_dock.resize_all_panels(Some(size), window, cx);
7123 } else {
7124 right_dock.resize_active_panel(Some(size), window, cx);
7125 }
7126 });
7127 }
7128
7129 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7130 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7131 self.bottom_dock.update(cx, |bottom_dock, cx| {
7132 if WorkspaceSettings::get_global(cx)
7133 .resize_all_panels_in_dock
7134 .contains(&DockPosition::Bottom)
7135 {
7136 bottom_dock.resize_all_panels(Some(size), window, cx);
7137 } else {
7138 bottom_dock.resize_active_panel(Some(size), window, cx);
7139 }
7140 });
7141 }
7142
7143 fn toggle_edit_predictions_all_files(
7144 &mut self,
7145 _: &ToggleEditPrediction,
7146 _window: &mut Window,
7147 cx: &mut Context<Self>,
7148 ) {
7149 let fs = self.project().read(cx).fs().clone();
7150 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7151 update_settings_file(fs, cx, move |file, _| {
7152 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7153 });
7154 }
7155
7156 pub fn show_worktree_trust_security_modal(
7157 &mut self,
7158 toggle: bool,
7159 window: &mut Window,
7160 cx: &mut Context<Self>,
7161 ) {
7162 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7163 if toggle {
7164 security_modal.update(cx, |security_modal, cx| {
7165 security_modal.dismiss(cx);
7166 })
7167 } else {
7168 security_modal.update(cx, |security_modal, cx| {
7169 security_modal.refresh_restricted_paths(cx);
7170 });
7171 }
7172 } else {
7173 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7174 .map(|trusted_worktrees| {
7175 trusted_worktrees
7176 .read(cx)
7177 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7178 })
7179 .unwrap_or(false);
7180 if has_restricted_worktrees {
7181 let project = self.project().read(cx);
7182 let remote_host = project
7183 .remote_connection_options(cx)
7184 .map(RemoteHostLocation::from);
7185 let worktree_store = project.worktree_store().downgrade();
7186 self.toggle_modal(window, cx, |_, cx| {
7187 SecurityModal::new(worktree_store, remote_host, cx)
7188 });
7189 }
7190 }
7191 }
7192}
7193
7194pub trait AnyActiveCall {
7195 fn entity(&self) -> AnyEntity;
7196 fn is_in_room(&self, _: &App) -> bool;
7197 fn room_id(&self, _: &App) -> Option<u64>;
7198 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7199 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7200 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7201 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7202 fn is_sharing_project(&self, _: &App) -> bool;
7203 fn has_remote_participants(&self, _: &App) -> bool;
7204 fn local_participant_is_guest(&self, _: &App) -> bool;
7205 fn client(&self, _: &App) -> Arc<Client>;
7206 fn share_on_join(&self, _: &App) -> bool;
7207 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7208 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7209 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7210 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7211 fn join_project(
7212 &self,
7213 _: u64,
7214 _: Arc<LanguageRegistry>,
7215 _: Arc<dyn Fs>,
7216 _: &mut App,
7217 ) -> Task<Result<Entity<Project>>>;
7218 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7219 fn subscribe(
7220 &self,
7221 _: &mut Window,
7222 _: &mut Context<Workspace>,
7223 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7224 ) -> Subscription;
7225 fn create_shared_screen(
7226 &self,
7227 _: PeerId,
7228 _: &Entity<Pane>,
7229 _: &mut Window,
7230 _: &mut App,
7231 ) -> Option<Entity<SharedScreen>>;
7232}
7233
7234#[derive(Clone)]
7235pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7236impl Global for GlobalAnyActiveCall {}
7237
7238impl GlobalAnyActiveCall {
7239 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7240 cx.try_global()
7241 }
7242
7243 pub(crate) fn global(cx: &App) -> &Self {
7244 cx.global()
7245 }
7246}
7247/// Workspace-local view of a remote participant's location.
7248#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7249pub enum ParticipantLocation {
7250 SharedProject { project_id: u64 },
7251 UnsharedProject,
7252 External,
7253}
7254
7255impl ParticipantLocation {
7256 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7257 match location
7258 .and_then(|l| l.variant)
7259 .context("participant location was not provided")?
7260 {
7261 proto::participant_location::Variant::SharedProject(project) => {
7262 Ok(Self::SharedProject {
7263 project_id: project.id,
7264 })
7265 }
7266 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7267 proto::participant_location::Variant::External(_) => Ok(Self::External),
7268 }
7269 }
7270}
7271/// Workspace-local view of a remote collaborator's state.
7272/// This is the subset of `call::RemoteParticipant` that workspace needs.
7273#[derive(Clone)]
7274pub struct RemoteCollaborator {
7275 pub user: Arc<User>,
7276 pub peer_id: PeerId,
7277 pub location: ParticipantLocation,
7278 pub participant_index: ParticipantIndex,
7279}
7280
7281pub enum ActiveCallEvent {
7282 ParticipantLocationChanged { participant_id: PeerId },
7283 RemoteVideoTracksChanged { participant_id: PeerId },
7284}
7285
7286fn leader_border_for_pane(
7287 follower_states: &HashMap<CollaboratorId, FollowerState>,
7288 pane: &Entity<Pane>,
7289 _: &Window,
7290 cx: &App,
7291) -> Option<Div> {
7292 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7293 if state.pane() == pane {
7294 Some((*leader_id, state))
7295 } else {
7296 None
7297 }
7298 })?;
7299
7300 let mut leader_color = match leader_id {
7301 CollaboratorId::PeerId(leader_peer_id) => {
7302 let leader = GlobalAnyActiveCall::try_global(cx)?
7303 .0
7304 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7305
7306 cx.theme()
7307 .players()
7308 .color_for_participant(leader.participant_index.0)
7309 .cursor
7310 }
7311 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7312 };
7313 leader_color.fade_out(0.3);
7314 Some(
7315 div()
7316 .absolute()
7317 .size_full()
7318 .left_0()
7319 .top_0()
7320 .border_2()
7321 .border_color(leader_color),
7322 )
7323}
7324
7325fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7326 ZED_WINDOW_POSITION
7327 .zip(*ZED_WINDOW_SIZE)
7328 .map(|(position, size)| Bounds {
7329 origin: position,
7330 size,
7331 })
7332}
7333
7334fn open_items(
7335 serialized_workspace: Option<SerializedWorkspace>,
7336 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7337 window: &mut Window,
7338 cx: &mut Context<Workspace>,
7339) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7340 let restored_items = serialized_workspace.map(|serialized_workspace| {
7341 Workspace::load_workspace(
7342 serialized_workspace,
7343 project_paths_to_open
7344 .iter()
7345 .map(|(_, project_path)| project_path)
7346 .cloned()
7347 .collect(),
7348 window,
7349 cx,
7350 )
7351 });
7352
7353 cx.spawn_in(window, async move |workspace, cx| {
7354 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7355
7356 if let Some(restored_items) = restored_items {
7357 let restored_items = restored_items.await?;
7358
7359 let restored_project_paths = restored_items
7360 .iter()
7361 .filter_map(|item| {
7362 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7363 .ok()
7364 .flatten()
7365 })
7366 .collect::<HashSet<_>>();
7367
7368 for restored_item in restored_items {
7369 opened_items.push(restored_item.map(Ok));
7370 }
7371
7372 project_paths_to_open
7373 .iter_mut()
7374 .for_each(|(_, project_path)| {
7375 if let Some(project_path_to_open) = project_path
7376 && restored_project_paths.contains(project_path_to_open)
7377 {
7378 *project_path = None;
7379 }
7380 });
7381 } else {
7382 for _ in 0..project_paths_to_open.len() {
7383 opened_items.push(None);
7384 }
7385 }
7386 assert!(opened_items.len() == project_paths_to_open.len());
7387
7388 let tasks =
7389 project_paths_to_open
7390 .into_iter()
7391 .enumerate()
7392 .map(|(ix, (abs_path, project_path))| {
7393 let workspace = workspace.clone();
7394 cx.spawn(async move |cx| {
7395 let file_project_path = project_path?;
7396 let abs_path_task = workspace.update(cx, |workspace, cx| {
7397 workspace.project().update(cx, |project, cx| {
7398 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7399 })
7400 });
7401
7402 // We only want to open file paths here. If one of the items
7403 // here is a directory, it was already opened further above
7404 // with a `find_or_create_worktree`.
7405 if let Ok(task) = abs_path_task
7406 && task.await.is_none_or(|p| p.is_file())
7407 {
7408 return Some((
7409 ix,
7410 workspace
7411 .update_in(cx, |workspace, window, cx| {
7412 workspace.open_path(
7413 file_project_path,
7414 None,
7415 true,
7416 window,
7417 cx,
7418 )
7419 })
7420 .log_err()?
7421 .await,
7422 ));
7423 }
7424 None
7425 })
7426 });
7427
7428 let tasks = tasks.collect::<Vec<_>>();
7429
7430 let tasks = futures::future::join_all(tasks);
7431 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7432 opened_items[ix] = Some(path_open_result);
7433 }
7434
7435 Ok(opened_items)
7436 })
7437}
7438
7439enum ActivateInDirectionTarget {
7440 Pane(Entity<Pane>),
7441 Dock(Entity<Dock>),
7442}
7443
7444fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7445 window
7446 .update(cx, |multi_workspace, _, cx| {
7447 let workspace = multi_workspace.workspace().clone();
7448 workspace.update(cx, |workspace, cx| {
7449 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7450 struct DatabaseFailedNotification;
7451
7452 workspace.show_notification(
7453 NotificationId::unique::<DatabaseFailedNotification>(),
7454 cx,
7455 |cx| {
7456 cx.new(|cx| {
7457 MessageNotification::new("Failed to load the database file.", cx)
7458 .primary_message("File an Issue")
7459 .primary_icon(IconName::Plus)
7460 .primary_on_click(|window, cx| {
7461 window.dispatch_action(Box::new(FileBugReport), cx)
7462 })
7463 })
7464 },
7465 );
7466 }
7467 });
7468 })
7469 .log_err();
7470}
7471
7472fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7473 if val == 0 {
7474 ThemeSettings::get_global(cx).ui_font_size(cx)
7475 } else {
7476 px(val as f32)
7477 }
7478}
7479
7480fn adjust_active_dock_size_by_px(
7481 px: Pixels,
7482 workspace: &mut Workspace,
7483 window: &mut Window,
7484 cx: &mut Context<Workspace>,
7485) {
7486 let Some(active_dock) = workspace
7487 .all_docks()
7488 .into_iter()
7489 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7490 else {
7491 return;
7492 };
7493 let dock = active_dock.read(cx);
7494 let Some(panel_size) = dock.active_panel_size(window, cx) else {
7495 return;
7496 };
7497 let dock_pos = dock.position();
7498 workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
7499}
7500
7501fn adjust_open_docks_size_by_px(
7502 px: Pixels,
7503 workspace: &mut Workspace,
7504 window: &mut Window,
7505 cx: &mut Context<Workspace>,
7506) {
7507 let docks = workspace
7508 .all_docks()
7509 .into_iter()
7510 .filter_map(|dock| {
7511 if dock.read(cx).is_open() {
7512 let dock = dock.read(cx);
7513 let panel_size = dock.active_panel_size(window, cx)?;
7514 let dock_pos = dock.position();
7515 Some((panel_size, dock_pos, px))
7516 } else {
7517 None
7518 }
7519 })
7520 .collect::<Vec<_>>();
7521
7522 docks
7523 .into_iter()
7524 .for_each(|(panel_size, dock_pos, offset)| {
7525 workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
7526 });
7527}
7528
7529impl Focusable for Workspace {
7530 fn focus_handle(&self, cx: &App) -> FocusHandle {
7531 self.active_pane.focus_handle(cx)
7532 }
7533}
7534
7535#[derive(Clone)]
7536struct DraggedDock(DockPosition);
7537
7538impl Render for DraggedDock {
7539 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7540 gpui::Empty
7541 }
7542}
7543
7544impl Render for Workspace {
7545 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7546 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7547 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7548 log::info!("Rendered first frame");
7549 }
7550
7551 let centered_layout = self.centered_layout
7552 && self.center.panes().len() == 1
7553 && self.active_item(cx).is_some();
7554 let render_padding = |size| {
7555 (size > 0.0).then(|| {
7556 div()
7557 .h_full()
7558 .w(relative(size))
7559 .bg(cx.theme().colors().editor_background)
7560 .border_color(cx.theme().colors().pane_group_border)
7561 })
7562 };
7563 let paddings = if centered_layout {
7564 let settings = WorkspaceSettings::get_global(cx).centered_layout;
7565 (
7566 render_padding(Self::adjust_padding(
7567 settings.left_padding.map(|padding| padding.0),
7568 )),
7569 render_padding(Self::adjust_padding(
7570 settings.right_padding.map(|padding| padding.0),
7571 )),
7572 )
7573 } else {
7574 (None, None)
7575 };
7576 let ui_font = theme::setup_ui_font(window, cx);
7577
7578 let theme = cx.theme().clone();
7579 let colors = theme.colors();
7580 let notification_entities = self
7581 .notifications
7582 .iter()
7583 .map(|(_, notification)| notification.entity_id())
7584 .collect::<Vec<_>>();
7585 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
7586
7587 div()
7588 .relative()
7589 .size_full()
7590 .flex()
7591 .flex_col()
7592 .font(ui_font)
7593 .gap_0()
7594 .justify_start()
7595 .items_start()
7596 .text_color(colors.text)
7597 .overflow_hidden()
7598 .children(self.titlebar_item.clone())
7599 .on_modifiers_changed(move |_, _, cx| {
7600 for &id in ¬ification_entities {
7601 cx.notify(id);
7602 }
7603 })
7604 .child(
7605 div()
7606 .size_full()
7607 .relative()
7608 .flex_1()
7609 .flex()
7610 .flex_col()
7611 .child(
7612 div()
7613 .id("workspace")
7614 .bg(colors.background)
7615 .relative()
7616 .flex_1()
7617 .w_full()
7618 .flex()
7619 .flex_col()
7620 .overflow_hidden()
7621 .border_t_1()
7622 .border_b_1()
7623 .border_color(colors.border)
7624 .child({
7625 let this = cx.entity();
7626 canvas(
7627 move |bounds, window, cx| {
7628 this.update(cx, |this, cx| {
7629 let bounds_changed = this.bounds != bounds;
7630 this.bounds = bounds;
7631
7632 if bounds_changed {
7633 this.left_dock.update(cx, |dock, cx| {
7634 dock.clamp_panel_size(
7635 bounds.size.width,
7636 window,
7637 cx,
7638 )
7639 });
7640
7641 this.right_dock.update(cx, |dock, cx| {
7642 dock.clamp_panel_size(
7643 bounds.size.width,
7644 window,
7645 cx,
7646 )
7647 });
7648
7649 this.bottom_dock.update(cx, |dock, cx| {
7650 dock.clamp_panel_size(
7651 bounds.size.height,
7652 window,
7653 cx,
7654 )
7655 });
7656 }
7657 })
7658 },
7659 |_, _, _, _| {},
7660 )
7661 .absolute()
7662 .size_full()
7663 })
7664 .when(self.zoomed.is_none(), |this| {
7665 this.on_drag_move(cx.listener(
7666 move |workspace,
7667 e: &DragMoveEvent<DraggedDock>,
7668 window,
7669 cx| {
7670 if workspace.previous_dock_drag_coordinates
7671 != Some(e.event.position)
7672 {
7673 workspace.previous_dock_drag_coordinates =
7674 Some(e.event.position);
7675
7676 match e.drag(cx).0 {
7677 DockPosition::Left => {
7678 workspace.resize_left_dock(
7679 e.event.position.x
7680 - workspace.bounds.left(),
7681 window,
7682 cx,
7683 );
7684 }
7685 DockPosition::Right => {
7686 workspace.resize_right_dock(
7687 workspace.bounds.right()
7688 - e.event.position.x,
7689 window,
7690 cx,
7691 );
7692 }
7693 DockPosition::Bottom => {
7694 workspace.resize_bottom_dock(
7695 workspace.bounds.bottom()
7696 - e.event.position.y,
7697 window,
7698 cx,
7699 );
7700 }
7701 };
7702 workspace.serialize_workspace(window, cx);
7703 }
7704 },
7705 ))
7706
7707 })
7708 .child({
7709 match bottom_dock_layout {
7710 BottomDockLayout::Full => div()
7711 .flex()
7712 .flex_col()
7713 .h_full()
7714 .child(
7715 div()
7716 .flex()
7717 .flex_row()
7718 .flex_1()
7719 .overflow_hidden()
7720 .children(self.render_dock(
7721 DockPosition::Left,
7722 &self.left_dock,
7723 window,
7724 cx,
7725 ))
7726
7727 .child(
7728 div()
7729 .flex()
7730 .flex_col()
7731 .flex_1()
7732 .overflow_hidden()
7733 .child(
7734 h_flex()
7735 .flex_1()
7736 .when_some(
7737 paddings.0,
7738 |this, p| {
7739 this.child(
7740 p.border_r_1(),
7741 )
7742 },
7743 )
7744 .child(self.center.render(
7745 self.zoomed.as_ref(),
7746 &PaneRenderContext {
7747 follower_states:
7748 &self.follower_states,
7749 active_call: self.active_call(),
7750 active_pane: &self.active_pane,
7751 app_state: &self.app_state,
7752 project: &self.project,
7753 workspace: &self.weak_self,
7754 },
7755 window,
7756 cx,
7757 ))
7758 .when_some(
7759 paddings.1,
7760 |this, p| {
7761 this.child(
7762 p.border_l_1(),
7763 )
7764 },
7765 ),
7766 ),
7767 )
7768
7769 .children(self.render_dock(
7770 DockPosition::Right,
7771 &self.right_dock,
7772 window,
7773 cx,
7774 )),
7775 )
7776 .child(div().w_full().children(self.render_dock(
7777 DockPosition::Bottom,
7778 &self.bottom_dock,
7779 window,
7780 cx
7781 ))),
7782
7783 BottomDockLayout::LeftAligned => div()
7784 .flex()
7785 .flex_row()
7786 .h_full()
7787 .child(
7788 div()
7789 .flex()
7790 .flex_col()
7791 .flex_1()
7792 .h_full()
7793 .child(
7794 div()
7795 .flex()
7796 .flex_row()
7797 .flex_1()
7798 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
7799
7800 .child(
7801 div()
7802 .flex()
7803 .flex_col()
7804 .flex_1()
7805 .overflow_hidden()
7806 .child(
7807 h_flex()
7808 .flex_1()
7809 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7810 .child(self.center.render(
7811 self.zoomed.as_ref(),
7812 &PaneRenderContext {
7813 follower_states:
7814 &self.follower_states,
7815 active_call: self.active_call(),
7816 active_pane: &self.active_pane,
7817 app_state: &self.app_state,
7818 project: &self.project,
7819 workspace: &self.weak_self,
7820 },
7821 window,
7822 cx,
7823 ))
7824 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7825 )
7826 )
7827
7828 )
7829 .child(
7830 div()
7831 .w_full()
7832 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7833 ),
7834 )
7835 .children(self.render_dock(
7836 DockPosition::Right,
7837 &self.right_dock,
7838 window,
7839 cx,
7840 )),
7841
7842 BottomDockLayout::RightAligned => div()
7843 .flex()
7844 .flex_row()
7845 .h_full()
7846 .children(self.render_dock(
7847 DockPosition::Left,
7848 &self.left_dock,
7849 window,
7850 cx,
7851 ))
7852
7853 .child(
7854 div()
7855 .flex()
7856 .flex_col()
7857 .flex_1()
7858 .h_full()
7859 .child(
7860 div()
7861 .flex()
7862 .flex_row()
7863 .flex_1()
7864 .child(
7865 div()
7866 .flex()
7867 .flex_col()
7868 .flex_1()
7869 .overflow_hidden()
7870 .child(
7871 h_flex()
7872 .flex_1()
7873 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7874 .child(self.center.render(
7875 self.zoomed.as_ref(),
7876 &PaneRenderContext {
7877 follower_states:
7878 &self.follower_states,
7879 active_call: self.active_call(),
7880 active_pane: &self.active_pane,
7881 app_state: &self.app_state,
7882 project: &self.project,
7883 workspace: &self.weak_self,
7884 },
7885 window,
7886 cx,
7887 ))
7888 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7889 )
7890 )
7891
7892 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
7893 )
7894 .child(
7895 div()
7896 .w_full()
7897 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7898 ),
7899 ),
7900
7901 BottomDockLayout::Contained => div()
7902 .flex()
7903 .flex_row()
7904 .h_full()
7905 .children(self.render_dock(
7906 DockPosition::Left,
7907 &self.left_dock,
7908 window,
7909 cx,
7910 ))
7911
7912 .child(
7913 div()
7914 .flex()
7915 .flex_col()
7916 .flex_1()
7917 .overflow_hidden()
7918 .child(
7919 h_flex()
7920 .flex_1()
7921 .when_some(paddings.0, |this, p| {
7922 this.child(p.border_r_1())
7923 })
7924 .child(self.center.render(
7925 self.zoomed.as_ref(),
7926 &PaneRenderContext {
7927 follower_states:
7928 &self.follower_states,
7929 active_call: self.active_call(),
7930 active_pane: &self.active_pane,
7931 app_state: &self.app_state,
7932 project: &self.project,
7933 workspace: &self.weak_self,
7934 },
7935 window,
7936 cx,
7937 ))
7938 .when_some(paddings.1, |this, p| {
7939 this.child(p.border_l_1())
7940 }),
7941 )
7942 .children(self.render_dock(
7943 DockPosition::Bottom,
7944 &self.bottom_dock,
7945 window,
7946 cx,
7947 )),
7948 )
7949
7950 .children(self.render_dock(
7951 DockPosition::Right,
7952 &self.right_dock,
7953 window,
7954 cx,
7955 )),
7956 }
7957 })
7958 .children(self.zoomed.as_ref().and_then(|view| {
7959 let zoomed_view = view.upgrade()?;
7960 let div = div()
7961 .occlude()
7962 .absolute()
7963 .overflow_hidden()
7964 .border_color(colors.border)
7965 .bg(colors.background)
7966 .child(zoomed_view)
7967 .inset_0()
7968 .shadow_lg();
7969
7970 if !WorkspaceSettings::get_global(cx).zoomed_padding {
7971 return Some(div);
7972 }
7973
7974 Some(match self.zoomed_position {
7975 Some(DockPosition::Left) => div.right_2().border_r_1(),
7976 Some(DockPosition::Right) => div.left_2().border_l_1(),
7977 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
7978 None => {
7979 div.top_2().bottom_2().left_2().right_2().border_1()
7980 }
7981 })
7982 }))
7983 .children(self.render_notifications(window, cx)),
7984 )
7985 .when(self.status_bar_visible(cx), |parent| {
7986 parent.child(self.status_bar.clone())
7987 })
7988 .child(self.toast_layer.clone()),
7989 )
7990 }
7991}
7992
7993impl WorkspaceStore {
7994 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
7995 Self {
7996 workspaces: Default::default(),
7997 _subscriptions: vec![
7998 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
7999 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8000 ],
8001 client,
8002 }
8003 }
8004
8005 pub fn update_followers(
8006 &self,
8007 project_id: Option<u64>,
8008 update: proto::update_followers::Variant,
8009 cx: &App,
8010 ) -> Option<()> {
8011 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8012 let room_id = active_call.0.room_id(cx)?;
8013 self.client
8014 .send(proto::UpdateFollowers {
8015 room_id,
8016 project_id,
8017 variant: Some(update),
8018 })
8019 .log_err()
8020 }
8021
8022 pub async fn handle_follow(
8023 this: Entity<Self>,
8024 envelope: TypedEnvelope<proto::Follow>,
8025 mut cx: AsyncApp,
8026 ) -> Result<proto::FollowResponse> {
8027 this.update(&mut cx, |this, cx| {
8028 let follower = Follower {
8029 project_id: envelope.payload.project_id,
8030 peer_id: envelope.original_sender_id()?,
8031 };
8032
8033 let mut response = proto::FollowResponse::default();
8034
8035 this.workspaces.retain(|(window_handle, weak_workspace)| {
8036 let Some(workspace) = weak_workspace.upgrade() else {
8037 return false;
8038 };
8039 window_handle
8040 .update(cx, |_, window, cx| {
8041 workspace.update(cx, |workspace, cx| {
8042 let handler_response =
8043 workspace.handle_follow(follower.project_id, window, cx);
8044 if let Some(active_view) = handler_response.active_view
8045 && workspace.project.read(cx).remote_id() == follower.project_id
8046 {
8047 response.active_view = Some(active_view)
8048 }
8049 });
8050 })
8051 .is_ok()
8052 });
8053
8054 Ok(response)
8055 })
8056 }
8057
8058 async fn handle_update_followers(
8059 this: Entity<Self>,
8060 envelope: TypedEnvelope<proto::UpdateFollowers>,
8061 mut cx: AsyncApp,
8062 ) -> Result<()> {
8063 let leader_id = envelope.original_sender_id()?;
8064 let update = envelope.payload;
8065
8066 this.update(&mut cx, |this, cx| {
8067 this.workspaces.retain(|(window_handle, weak_workspace)| {
8068 let Some(workspace) = weak_workspace.upgrade() else {
8069 return false;
8070 };
8071 window_handle
8072 .update(cx, |_, window, cx| {
8073 workspace.update(cx, |workspace, cx| {
8074 let project_id = workspace.project.read(cx).remote_id();
8075 if update.project_id != project_id && update.project_id.is_some() {
8076 return;
8077 }
8078 workspace.handle_update_followers(
8079 leader_id,
8080 update.clone(),
8081 window,
8082 cx,
8083 );
8084 });
8085 })
8086 .is_ok()
8087 });
8088 Ok(())
8089 })
8090 }
8091
8092 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8093 self.workspaces.iter().map(|(_, weak)| weak)
8094 }
8095
8096 pub fn workspaces_with_windows(
8097 &self,
8098 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8099 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8100 }
8101}
8102
8103impl ViewId {
8104 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8105 Ok(Self {
8106 creator: message
8107 .creator
8108 .map(CollaboratorId::PeerId)
8109 .context("creator is missing")?,
8110 id: message.id,
8111 })
8112 }
8113
8114 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8115 if let CollaboratorId::PeerId(peer_id) = self.creator {
8116 Some(proto::ViewId {
8117 creator: Some(peer_id),
8118 id: self.id,
8119 })
8120 } else {
8121 None
8122 }
8123 }
8124}
8125
8126impl FollowerState {
8127 fn pane(&self) -> &Entity<Pane> {
8128 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8129 }
8130}
8131
8132pub trait WorkspaceHandle {
8133 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8134}
8135
8136impl WorkspaceHandle for Entity<Workspace> {
8137 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8138 self.read(cx)
8139 .worktrees(cx)
8140 .flat_map(|worktree| {
8141 let worktree_id = worktree.read(cx).id();
8142 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8143 worktree_id,
8144 path: f.path.clone(),
8145 })
8146 })
8147 .collect::<Vec<_>>()
8148 }
8149}
8150
8151pub async fn last_opened_workspace_location(
8152 fs: &dyn fs::Fs,
8153) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8154 DB.last_workspace(fs)
8155 .await
8156 .log_err()
8157 .flatten()
8158 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8159}
8160
8161pub async fn last_session_workspace_locations(
8162 last_session_id: &str,
8163 last_session_window_stack: Option<Vec<WindowId>>,
8164 fs: &dyn fs::Fs,
8165) -> Option<Vec<SessionWorkspace>> {
8166 DB.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8167 .await
8168 .log_err()
8169}
8170
8171pub struct MultiWorkspaceRestoreResult {
8172 pub window_handle: WindowHandle<MultiWorkspace>,
8173 pub errors: Vec<anyhow::Error>,
8174}
8175
8176pub async fn restore_multiworkspace(
8177 multi_workspace: SerializedMultiWorkspace,
8178 app_state: Arc<AppState>,
8179 cx: &mut AsyncApp,
8180) -> anyhow::Result<MultiWorkspaceRestoreResult> {
8181 let SerializedMultiWorkspace {
8182 workspaces,
8183 state,
8184 id: window_id,
8185 } = multi_workspace;
8186 let mut group_iter = workspaces.into_iter();
8187 let first = group_iter
8188 .next()
8189 .context("window group must not be empty")?;
8190
8191 let window_handle = if first.paths.is_empty() {
8192 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
8193 .await?
8194 } else {
8195 let (window, _items) = cx
8196 .update(|cx| {
8197 Workspace::new_local(
8198 first.paths.paths().to_vec(),
8199 app_state.clone(),
8200 None,
8201 None,
8202 None,
8203 true,
8204 cx,
8205 )
8206 })
8207 .await?;
8208 window
8209 };
8210
8211 let mut errors = Vec::new();
8212
8213 for session_workspace in group_iter {
8214 let error = if session_workspace.paths.is_empty() {
8215 cx.update(|cx| {
8216 open_workspace_by_id(
8217 session_workspace.workspace_id,
8218 app_state.clone(),
8219 Some(window_handle),
8220 cx,
8221 )
8222 })
8223 .await
8224 .err()
8225 } else {
8226 cx.update(|cx| {
8227 Workspace::new_local(
8228 session_workspace.paths.paths().to_vec(),
8229 app_state.clone(),
8230 Some(window_handle),
8231 None,
8232 None,
8233 true,
8234 cx,
8235 )
8236 })
8237 .await
8238 .err()
8239 };
8240
8241 if let Some(error) = error {
8242 errors.push(error);
8243 }
8244 }
8245
8246 if let Some(target_id) = state.active_workspace_id {
8247 window_handle
8248 .update(cx, |multi_workspace, window, cx| {
8249 multi_workspace.set_database_id(window_id);
8250 let target_index = multi_workspace
8251 .workspaces()
8252 .iter()
8253 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8254 if let Some(index) = target_index {
8255 multi_workspace.activate_index(index, window, cx);
8256 } else if !multi_workspace.workspaces().is_empty() {
8257 multi_workspace.activate_index(0, window, cx);
8258 }
8259 })
8260 .ok();
8261 } else {
8262 window_handle
8263 .update(cx, |multi_workspace, window, cx| {
8264 if !multi_workspace.workspaces().is_empty() {
8265 multi_workspace.activate_index(0, window, cx);
8266 }
8267 })
8268 .ok();
8269 }
8270
8271 window_handle
8272 .update(cx, |_, window, _cx| {
8273 window.activate_window();
8274 })
8275 .ok();
8276
8277 Ok(MultiWorkspaceRestoreResult {
8278 window_handle,
8279 errors,
8280 })
8281}
8282
8283actions!(
8284 collab,
8285 [
8286 /// Opens the channel notes for the current call.
8287 ///
8288 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8289 /// channel in the collab panel.
8290 ///
8291 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8292 /// can be copied via "Copy link to section" in the context menu of the channel notes
8293 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8294 OpenChannelNotes,
8295 /// Mutes your microphone.
8296 Mute,
8297 /// Deafens yourself (mute both microphone and speakers).
8298 Deafen,
8299 /// Leaves the current call.
8300 LeaveCall,
8301 /// Shares the current project with collaborators.
8302 ShareProject,
8303 /// Shares your screen with collaborators.
8304 ScreenShare,
8305 /// Copies the current room name and session id for debugging purposes.
8306 CopyRoomId,
8307 ]
8308);
8309actions!(
8310 zed,
8311 [
8312 /// Opens the Zed log file.
8313 OpenLog,
8314 /// Reveals the Zed log file in the system file manager.
8315 RevealLogInFileManager
8316 ]
8317);
8318
8319async fn join_channel_internal(
8320 channel_id: ChannelId,
8321 app_state: &Arc<AppState>,
8322 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8323 requesting_workspace: Option<WeakEntity<Workspace>>,
8324 active_call: &dyn AnyActiveCall,
8325 cx: &mut AsyncApp,
8326) -> Result<bool> {
8327 let (should_prompt, already_in_channel) = cx.update(|cx| {
8328 if !active_call.is_in_room(cx) {
8329 return (false, false);
8330 }
8331
8332 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8333 let should_prompt = active_call.is_sharing_project(cx)
8334 && active_call.has_remote_participants(cx)
8335 && !already_in_channel;
8336 (should_prompt, already_in_channel)
8337 });
8338
8339 if already_in_channel {
8340 let task = cx.update(|cx| {
8341 if let Some((project, host)) = active_call.most_active_project(cx) {
8342 Some(join_in_room_project(project, host, app_state.clone(), cx))
8343 } else {
8344 None
8345 }
8346 });
8347 if let Some(task) = task {
8348 task.await?;
8349 }
8350 return anyhow::Ok(true);
8351 }
8352
8353 if should_prompt {
8354 if let Some(multi_workspace) = requesting_window {
8355 let answer = multi_workspace
8356 .update(cx, |_, window, cx| {
8357 window.prompt(
8358 PromptLevel::Warning,
8359 "Do you want to switch channels?",
8360 Some("Leaving this call will unshare your current project."),
8361 &["Yes, Join Channel", "Cancel"],
8362 cx,
8363 )
8364 })?
8365 .await;
8366
8367 if answer == Ok(1) {
8368 return Ok(false);
8369 }
8370 } else {
8371 return Ok(false);
8372 }
8373 }
8374
8375 let client = cx.update(|cx| active_call.client(cx));
8376
8377 let mut client_status = client.status();
8378
8379 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8380 'outer: loop {
8381 let Some(status) = client_status.recv().await else {
8382 anyhow::bail!("error connecting");
8383 };
8384
8385 match status {
8386 Status::Connecting
8387 | Status::Authenticating
8388 | Status::Authenticated
8389 | Status::Reconnecting
8390 | Status::Reauthenticating
8391 | Status::Reauthenticated => continue,
8392 Status::Connected { .. } => break 'outer,
8393 Status::SignedOut | Status::AuthenticationError => {
8394 return Err(ErrorCode::SignedOut.into());
8395 }
8396 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8397 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8398 return Err(ErrorCode::Disconnected.into());
8399 }
8400 }
8401 }
8402
8403 let joined = cx
8404 .update(|cx| active_call.join_channel(channel_id, cx))
8405 .await?;
8406
8407 if !joined {
8408 return anyhow::Ok(true);
8409 }
8410
8411 cx.update(|cx| active_call.room_update_completed(cx)).await;
8412
8413 let task = cx.update(|cx| {
8414 if let Some((project, host)) = active_call.most_active_project(cx) {
8415 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8416 }
8417
8418 // If you are the first to join a channel, see if you should share your project.
8419 if !active_call.has_remote_participants(cx)
8420 && !active_call.local_participant_is_guest(cx)
8421 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8422 {
8423 let project = workspace.update(cx, |workspace, cx| {
8424 let project = workspace.project.read(cx);
8425
8426 if !active_call.share_on_join(cx) {
8427 return None;
8428 }
8429
8430 if (project.is_local() || project.is_via_remote_server())
8431 && project.visible_worktrees(cx).any(|tree| {
8432 tree.read(cx)
8433 .root_entry()
8434 .is_some_and(|entry| entry.is_dir())
8435 })
8436 {
8437 Some(workspace.project.clone())
8438 } else {
8439 None
8440 }
8441 });
8442 if let Some(project) = project {
8443 let share_task = active_call.share_project(project, cx);
8444 return Some(cx.spawn(async move |_cx| -> Result<()> {
8445 share_task.await?;
8446 Ok(())
8447 }));
8448 }
8449 }
8450
8451 None
8452 });
8453 if let Some(task) = task {
8454 task.await?;
8455 return anyhow::Ok(true);
8456 }
8457 anyhow::Ok(false)
8458}
8459
8460pub fn join_channel(
8461 channel_id: ChannelId,
8462 app_state: Arc<AppState>,
8463 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8464 requesting_workspace: Option<WeakEntity<Workspace>>,
8465 cx: &mut App,
8466) -> Task<Result<()>> {
8467 let active_call = GlobalAnyActiveCall::global(cx).clone();
8468 cx.spawn(async move |cx| {
8469 let result = join_channel_internal(
8470 channel_id,
8471 &app_state,
8472 requesting_window,
8473 requesting_workspace,
8474 &*active_call.0,
8475 cx,
8476 )
8477 .await;
8478
8479 // join channel succeeded, and opened a window
8480 if matches!(result, Ok(true)) {
8481 return anyhow::Ok(());
8482 }
8483
8484 // find an existing workspace to focus and show call controls
8485 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8486 if active_window.is_none() {
8487 // no open workspaces, make one to show the error in (blergh)
8488 let (window_handle, _) = cx
8489 .update(|cx| {
8490 Workspace::new_local(
8491 vec![],
8492 app_state.clone(),
8493 requesting_window,
8494 None,
8495 None,
8496 true,
8497 cx,
8498 )
8499 })
8500 .await?;
8501
8502 window_handle
8503 .update(cx, |_, window, _cx| {
8504 window.activate_window();
8505 })
8506 .ok();
8507
8508 if result.is_ok() {
8509 cx.update(|cx| {
8510 cx.dispatch_action(&OpenChannelNotes);
8511 });
8512 }
8513
8514 active_window = Some(window_handle);
8515 }
8516
8517 if let Err(err) = result {
8518 log::error!("failed to join channel: {}", err);
8519 if let Some(active_window) = active_window {
8520 active_window
8521 .update(cx, |_, window, cx| {
8522 let detail: SharedString = match err.error_code() {
8523 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8524 ErrorCode::UpgradeRequired => concat!(
8525 "Your are running an unsupported version of Zed. ",
8526 "Please update to continue."
8527 )
8528 .into(),
8529 ErrorCode::NoSuchChannel => concat!(
8530 "No matching channel was found. ",
8531 "Please check the link and try again."
8532 )
8533 .into(),
8534 ErrorCode::Forbidden => concat!(
8535 "This channel is private, and you do not have access. ",
8536 "Please ask someone to add you and try again."
8537 )
8538 .into(),
8539 ErrorCode::Disconnected => {
8540 "Please check your internet connection and try again.".into()
8541 }
8542 _ => format!("{}\n\nPlease try again.", err).into(),
8543 };
8544 window.prompt(
8545 PromptLevel::Critical,
8546 "Failed to join channel",
8547 Some(&detail),
8548 &["Ok"],
8549 cx,
8550 )
8551 })?
8552 .await
8553 .ok();
8554 }
8555 }
8556
8557 // return ok, we showed the error to the user.
8558 anyhow::Ok(())
8559 })
8560}
8561
8562pub async fn get_any_active_multi_workspace(
8563 app_state: Arc<AppState>,
8564 mut cx: AsyncApp,
8565) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8566 // find an existing workspace to focus and show call controls
8567 let active_window = activate_any_workspace_window(&mut cx);
8568 if active_window.is_none() {
8569 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
8570 .await?;
8571 }
8572 activate_any_workspace_window(&mut cx).context("could not open zed")
8573}
8574
8575fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
8576 cx.update(|cx| {
8577 if let Some(workspace_window) = cx
8578 .active_window()
8579 .and_then(|window| window.downcast::<MultiWorkspace>())
8580 {
8581 return Some(workspace_window);
8582 }
8583
8584 for window in cx.windows() {
8585 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
8586 workspace_window
8587 .update(cx, |_, window, _| window.activate_window())
8588 .ok();
8589 return Some(workspace_window);
8590 }
8591 }
8592 None
8593 })
8594}
8595
8596pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
8597 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
8598}
8599
8600pub fn workspace_windows_for_location(
8601 serialized_location: &SerializedWorkspaceLocation,
8602 cx: &App,
8603) -> Vec<WindowHandle<MultiWorkspace>> {
8604 cx.windows()
8605 .into_iter()
8606 .filter_map(|window| window.downcast::<MultiWorkspace>())
8607 .filter(|multi_workspace| {
8608 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
8609 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
8610 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
8611 }
8612 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
8613 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
8614 a.distro_name == b.distro_name
8615 }
8616 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
8617 a.container_id == b.container_id
8618 }
8619 #[cfg(any(test, feature = "test-support"))]
8620 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
8621 a.id == b.id
8622 }
8623 _ => false,
8624 };
8625
8626 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
8627 multi_workspace.workspaces().iter().any(|workspace| {
8628 match workspace.read(cx).workspace_location(cx) {
8629 WorkspaceLocation::Location(location, _) => {
8630 match (&location, serialized_location) {
8631 (
8632 SerializedWorkspaceLocation::Local,
8633 SerializedWorkspaceLocation::Local,
8634 ) => true,
8635 (
8636 SerializedWorkspaceLocation::Remote(a),
8637 SerializedWorkspaceLocation::Remote(b),
8638 ) => same_host(a, b),
8639 _ => false,
8640 }
8641 }
8642 _ => false,
8643 }
8644 })
8645 })
8646 })
8647 .collect()
8648}
8649
8650pub async fn find_existing_workspace(
8651 abs_paths: &[PathBuf],
8652 open_options: &OpenOptions,
8653 location: &SerializedWorkspaceLocation,
8654 cx: &mut AsyncApp,
8655) -> (
8656 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
8657 OpenVisible,
8658) {
8659 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
8660 let mut open_visible = OpenVisible::All;
8661 let mut best_match = None;
8662
8663 if open_options.open_new_workspace != Some(true) {
8664 cx.update(|cx| {
8665 for window in workspace_windows_for_location(location, cx) {
8666 if let Ok(multi_workspace) = window.read(cx) {
8667 for workspace in multi_workspace.workspaces() {
8668 let project = workspace.read(cx).project.read(cx);
8669 let m = project.visibility_for_paths(
8670 abs_paths,
8671 open_options.open_new_workspace == None,
8672 cx,
8673 );
8674 if m > best_match {
8675 existing = Some((window, workspace.clone()));
8676 best_match = m;
8677 } else if best_match.is_none()
8678 && open_options.open_new_workspace == Some(false)
8679 {
8680 existing = Some((window, workspace.clone()))
8681 }
8682 }
8683 }
8684 }
8685 });
8686
8687 let all_paths_are_files = existing
8688 .as_ref()
8689 .and_then(|(_, target_workspace)| {
8690 cx.update(|cx| {
8691 let workspace = target_workspace.read(cx);
8692 let project = workspace.project.read(cx);
8693 let path_style = workspace.path_style(cx);
8694 Some(!abs_paths.iter().any(|path| {
8695 let path = util::paths::SanitizedPath::new(path);
8696 project.worktrees(cx).any(|worktree| {
8697 let worktree = worktree.read(cx);
8698 let abs_path = worktree.abs_path();
8699 path_style
8700 .strip_prefix(path.as_ref(), abs_path.as_ref())
8701 .and_then(|rel| worktree.entry_for_path(&rel))
8702 .is_some_and(|e| e.is_dir())
8703 })
8704 }))
8705 })
8706 })
8707 .unwrap_or(false);
8708
8709 if open_options.open_new_workspace.is_none()
8710 && existing.is_some()
8711 && open_options.wait
8712 && all_paths_are_files
8713 {
8714 cx.update(|cx| {
8715 let windows = workspace_windows_for_location(location, cx);
8716 let window = cx
8717 .active_window()
8718 .and_then(|window| window.downcast::<MultiWorkspace>())
8719 .filter(|window| windows.contains(window))
8720 .or_else(|| windows.into_iter().next());
8721 if let Some(window) = window {
8722 if let Ok(multi_workspace) = window.read(cx) {
8723 let active_workspace = multi_workspace.workspace().clone();
8724 existing = Some((window, active_workspace));
8725 open_visible = OpenVisible::None;
8726 }
8727 }
8728 });
8729 }
8730 }
8731 (existing, open_visible)
8732}
8733
8734#[derive(Default, Clone)]
8735pub struct OpenOptions {
8736 pub visible: Option<OpenVisible>,
8737 pub focus: Option<bool>,
8738 pub open_new_workspace: Option<bool>,
8739 pub wait: bool,
8740 pub replace_window: Option<WindowHandle<MultiWorkspace>>,
8741 pub env: Option<HashMap<String, String>>,
8742}
8743
8744/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
8745pub fn open_workspace_by_id(
8746 workspace_id: WorkspaceId,
8747 app_state: Arc<AppState>,
8748 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8749 cx: &mut App,
8750) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
8751 let project_handle = Project::local(
8752 app_state.client.clone(),
8753 app_state.node_runtime.clone(),
8754 app_state.user_store.clone(),
8755 app_state.languages.clone(),
8756 app_state.fs.clone(),
8757 None,
8758 project::LocalProjectFlags {
8759 init_worktree_trust: true,
8760 ..project::LocalProjectFlags::default()
8761 },
8762 cx,
8763 );
8764
8765 cx.spawn(async move |cx| {
8766 let serialized_workspace = persistence::DB
8767 .workspace_for_id(workspace_id)
8768 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
8769
8770 let centered_layout = serialized_workspace.centered_layout;
8771
8772 let (window, workspace) = if let Some(window) = requesting_window {
8773 let workspace = window.update(cx, |multi_workspace, window, cx| {
8774 let workspace = cx.new(|cx| {
8775 let mut workspace = Workspace::new(
8776 Some(workspace_id),
8777 project_handle.clone(),
8778 app_state.clone(),
8779 window,
8780 cx,
8781 );
8782 workspace.centered_layout = centered_layout;
8783 workspace
8784 });
8785 multi_workspace.add_workspace(workspace.clone(), cx);
8786 workspace
8787 })?;
8788 (window, workspace)
8789 } else {
8790 let window_bounds_override = window_bounds_env_override();
8791
8792 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
8793 (Some(WindowBounds::Windowed(bounds)), None)
8794 } else if let Some(display) = serialized_workspace.display
8795 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
8796 {
8797 (Some(bounds.0), Some(display))
8798 } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
8799 (Some(bounds), Some(display))
8800 } else {
8801 (None, None)
8802 };
8803
8804 let options = cx.update(|cx| {
8805 let mut options = (app_state.build_window_options)(display, cx);
8806 options.window_bounds = window_bounds;
8807 options
8808 });
8809
8810 let window = cx.open_window(options, {
8811 let app_state = app_state.clone();
8812 let project_handle = project_handle.clone();
8813 move |window, cx| {
8814 let workspace = cx.new(|cx| {
8815 let mut workspace = Workspace::new(
8816 Some(workspace_id),
8817 project_handle,
8818 app_state,
8819 window,
8820 cx,
8821 );
8822 workspace.centered_layout = centered_layout;
8823 workspace
8824 });
8825 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
8826 }
8827 })?;
8828
8829 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
8830 multi_workspace.workspace().clone()
8831 })?;
8832
8833 (window, workspace)
8834 };
8835
8836 notify_if_database_failed(window, cx);
8837
8838 // Restore items from the serialized workspace
8839 window
8840 .update(cx, |_, window, cx| {
8841 workspace.update(cx, |_workspace, cx| {
8842 open_items(Some(serialized_workspace), vec![], window, cx)
8843 })
8844 })?
8845 .await?;
8846
8847 window.update(cx, |_, window, cx| {
8848 workspace.update(cx, |workspace, cx| {
8849 workspace.serialize_workspace(window, cx);
8850 });
8851 })?;
8852
8853 Ok(window)
8854 })
8855}
8856
8857#[allow(clippy::type_complexity)]
8858pub fn open_paths(
8859 abs_paths: &[PathBuf],
8860 app_state: Arc<AppState>,
8861 open_options: OpenOptions,
8862 cx: &mut App,
8863) -> Task<
8864 anyhow::Result<(
8865 WindowHandle<MultiWorkspace>,
8866 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
8867 )>,
8868> {
8869 let abs_paths = abs_paths.to_vec();
8870 #[cfg(target_os = "windows")]
8871 let wsl_path = abs_paths
8872 .iter()
8873 .find_map(|p| util::paths::WslPath::from_path(p));
8874
8875 cx.spawn(async move |cx| {
8876 let (mut existing, mut open_visible) = find_existing_workspace(
8877 &abs_paths,
8878 &open_options,
8879 &SerializedWorkspaceLocation::Local,
8880 cx,
8881 )
8882 .await;
8883
8884 // Fallback: if no workspace contains the paths and all paths are files,
8885 // prefer an existing local workspace window (active window first).
8886 if open_options.open_new_workspace.is_none() && existing.is_none() {
8887 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
8888 let all_metadatas = futures::future::join_all(all_paths)
8889 .await
8890 .into_iter()
8891 .filter_map(|result| result.ok().flatten())
8892 .collect::<Vec<_>>();
8893
8894 if all_metadatas.iter().all(|file| !file.is_dir) {
8895 cx.update(|cx| {
8896 let windows = workspace_windows_for_location(
8897 &SerializedWorkspaceLocation::Local,
8898 cx,
8899 );
8900 let window = cx
8901 .active_window()
8902 .and_then(|window| window.downcast::<MultiWorkspace>())
8903 .filter(|window| windows.contains(window))
8904 .or_else(|| windows.into_iter().next());
8905 if let Some(window) = window {
8906 if let Ok(multi_workspace) = window.read(cx) {
8907 let active_workspace = multi_workspace.workspace().clone();
8908 existing = Some((window, active_workspace));
8909 open_visible = OpenVisible::None;
8910 }
8911 }
8912 });
8913 }
8914 }
8915
8916 let result = if let Some((existing, target_workspace)) = existing {
8917 let open_task = existing
8918 .update(cx, |multi_workspace, window, cx| {
8919 window.activate_window();
8920 multi_workspace.activate(target_workspace.clone(), cx);
8921 target_workspace.update(cx, |workspace, cx| {
8922 workspace.open_paths(
8923 abs_paths,
8924 OpenOptions {
8925 visible: Some(open_visible),
8926 ..Default::default()
8927 },
8928 None,
8929 window,
8930 cx,
8931 )
8932 })
8933 })?
8934 .await;
8935
8936 _ = existing.update(cx, |multi_workspace, _, cx| {
8937 let workspace = multi_workspace.workspace().clone();
8938 workspace.update(cx, |workspace, cx| {
8939 for item in open_task.iter().flatten() {
8940 if let Err(e) = item {
8941 workspace.show_error(&e, cx);
8942 }
8943 }
8944 });
8945 });
8946
8947 Ok((existing, open_task))
8948 } else {
8949 let result = cx
8950 .update(move |cx| {
8951 Workspace::new_local(
8952 abs_paths,
8953 app_state.clone(),
8954 open_options.replace_window,
8955 open_options.env,
8956 None,
8957 true,
8958 cx,
8959 )
8960 })
8961 .await;
8962
8963 if let Ok((ref window_handle, _)) = result {
8964 window_handle
8965 .update(cx, |_, window, _cx| {
8966 window.activate_window();
8967 })
8968 .log_err();
8969 }
8970
8971 result
8972 };
8973
8974 #[cfg(target_os = "windows")]
8975 if let Some(util::paths::WslPath{distro, path}) = wsl_path
8976 && let Ok((multi_workspace_window, _)) = &result
8977 {
8978 multi_workspace_window
8979 .update(cx, move |multi_workspace, _window, cx| {
8980 struct OpenInWsl;
8981 let workspace = multi_workspace.workspace().clone();
8982 workspace.update(cx, |workspace, cx| {
8983 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
8984 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
8985 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
8986 cx.new(move |cx| {
8987 MessageNotification::new(msg, cx)
8988 .primary_message("Open in WSL")
8989 .primary_icon(IconName::FolderOpen)
8990 .primary_on_click(move |window, cx| {
8991 window.dispatch_action(Box::new(remote::OpenWslPath {
8992 distro: remote::WslConnectionOptions {
8993 distro_name: distro.clone(),
8994 user: None,
8995 },
8996 paths: vec![path.clone().into()],
8997 }), cx)
8998 })
8999 })
9000 });
9001 });
9002 })
9003 .unwrap();
9004 };
9005 result
9006 })
9007}
9008
9009pub fn open_new(
9010 open_options: OpenOptions,
9011 app_state: Arc<AppState>,
9012 cx: &mut App,
9013 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9014) -> Task<anyhow::Result<()>> {
9015 let task = Workspace::new_local(
9016 Vec::new(),
9017 app_state,
9018 open_options.replace_window,
9019 open_options.env,
9020 Some(Box::new(init)),
9021 true,
9022 cx,
9023 );
9024 cx.spawn(async move |cx| {
9025 let (window, _opened_paths) = task.await?;
9026 window
9027 .update(cx, |_, window, _cx| {
9028 window.activate_window();
9029 })
9030 .ok();
9031 Ok(())
9032 })
9033}
9034
9035pub fn create_and_open_local_file(
9036 path: &'static Path,
9037 window: &mut Window,
9038 cx: &mut Context<Workspace>,
9039 default_content: impl 'static + Send + FnOnce() -> Rope,
9040) -> Task<Result<Box<dyn ItemHandle>>> {
9041 cx.spawn_in(window, async move |workspace, cx| {
9042 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9043 if !fs.is_file(path).await {
9044 fs.create_file(path, Default::default()).await?;
9045 fs.save(path, &default_content(), Default::default())
9046 .await?;
9047 }
9048
9049 workspace
9050 .update_in(cx, |workspace, window, cx| {
9051 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9052 let path = workspace
9053 .project
9054 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9055 cx.spawn_in(window, async move |workspace, cx| {
9056 let path = path.await?;
9057 let mut items = workspace
9058 .update_in(cx, |workspace, window, cx| {
9059 workspace.open_paths(
9060 vec![path.to_path_buf()],
9061 OpenOptions {
9062 visible: Some(OpenVisible::None),
9063 ..Default::default()
9064 },
9065 None,
9066 window,
9067 cx,
9068 )
9069 })?
9070 .await;
9071 let item = items.pop().flatten();
9072 item.with_context(|| format!("path {path:?} is not a file"))?
9073 })
9074 })
9075 })?
9076 .await?
9077 .await
9078 })
9079}
9080
9081pub fn open_remote_project_with_new_connection(
9082 window: WindowHandle<MultiWorkspace>,
9083 remote_connection: Arc<dyn RemoteConnection>,
9084 cancel_rx: oneshot::Receiver<()>,
9085 delegate: Arc<dyn RemoteClientDelegate>,
9086 app_state: Arc<AppState>,
9087 paths: Vec<PathBuf>,
9088 cx: &mut App,
9089) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9090 cx.spawn(async move |cx| {
9091 let (workspace_id, serialized_workspace) =
9092 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9093 .await?;
9094
9095 let session = match cx
9096 .update(|cx| {
9097 remote::RemoteClient::new(
9098 ConnectionIdentifier::Workspace(workspace_id.0),
9099 remote_connection,
9100 cancel_rx,
9101 delegate,
9102 cx,
9103 )
9104 })
9105 .await?
9106 {
9107 Some(result) => result,
9108 None => return Ok(Vec::new()),
9109 };
9110
9111 let project = cx.update(|cx| {
9112 project::Project::remote(
9113 session,
9114 app_state.client.clone(),
9115 app_state.node_runtime.clone(),
9116 app_state.user_store.clone(),
9117 app_state.languages.clone(),
9118 app_state.fs.clone(),
9119 true,
9120 cx,
9121 )
9122 });
9123
9124 open_remote_project_inner(
9125 project,
9126 paths,
9127 workspace_id,
9128 serialized_workspace,
9129 app_state,
9130 window,
9131 cx,
9132 )
9133 .await
9134 })
9135}
9136
9137pub fn open_remote_project_with_existing_connection(
9138 connection_options: RemoteConnectionOptions,
9139 project: Entity<Project>,
9140 paths: Vec<PathBuf>,
9141 app_state: Arc<AppState>,
9142 window: WindowHandle<MultiWorkspace>,
9143 cx: &mut AsyncApp,
9144) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9145 cx.spawn(async move |cx| {
9146 let (workspace_id, serialized_workspace) =
9147 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9148
9149 open_remote_project_inner(
9150 project,
9151 paths,
9152 workspace_id,
9153 serialized_workspace,
9154 app_state,
9155 window,
9156 cx,
9157 )
9158 .await
9159 })
9160}
9161
9162async fn open_remote_project_inner(
9163 project: Entity<Project>,
9164 paths: Vec<PathBuf>,
9165 workspace_id: WorkspaceId,
9166 serialized_workspace: Option<SerializedWorkspace>,
9167 app_state: Arc<AppState>,
9168 window: WindowHandle<MultiWorkspace>,
9169 cx: &mut AsyncApp,
9170) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9171 let toolchains = DB.toolchains(workspace_id).await?;
9172 for (toolchain, worktree_path, path) in toolchains {
9173 project
9174 .update(cx, |this, cx| {
9175 let Some(worktree_id) =
9176 this.find_worktree(&worktree_path, cx)
9177 .and_then(|(worktree, rel_path)| {
9178 if rel_path.is_empty() {
9179 Some(worktree.read(cx).id())
9180 } else {
9181 None
9182 }
9183 })
9184 else {
9185 return Task::ready(None);
9186 };
9187
9188 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9189 })
9190 .await;
9191 }
9192 let mut project_paths_to_open = vec![];
9193 let mut project_path_errors = vec![];
9194
9195 for path in paths {
9196 let result = cx
9197 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9198 .await;
9199 match result {
9200 Ok((_, project_path)) => {
9201 project_paths_to_open.push((path.clone(), Some(project_path)));
9202 }
9203 Err(error) => {
9204 project_path_errors.push(error);
9205 }
9206 };
9207 }
9208
9209 if project_paths_to_open.is_empty() {
9210 return Err(project_path_errors.pop().context("no paths given")?);
9211 }
9212
9213 let workspace = window.update(cx, |multi_workspace, window, cx| {
9214 telemetry::event!("SSH Project Opened");
9215
9216 let new_workspace = cx.new(|cx| {
9217 let mut workspace =
9218 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9219 workspace.update_history(cx);
9220
9221 if let Some(ref serialized) = serialized_workspace {
9222 workspace.centered_layout = serialized.centered_layout;
9223 }
9224
9225 workspace
9226 });
9227
9228 multi_workspace.activate(new_workspace.clone(), cx);
9229 new_workspace
9230 })?;
9231
9232 let items = window
9233 .update(cx, |_, window, cx| {
9234 window.activate_window();
9235 workspace.update(cx, |_workspace, cx| {
9236 open_items(serialized_workspace, project_paths_to_open, window, cx)
9237 })
9238 })?
9239 .await?;
9240
9241 workspace.update(cx, |workspace, cx| {
9242 for error in project_path_errors {
9243 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9244 if let Some(path) = error.error_tag("path") {
9245 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9246 }
9247 } else {
9248 workspace.show_error(&error, cx)
9249 }
9250 }
9251 });
9252
9253 Ok(items.into_iter().map(|item| item?.ok()).collect())
9254}
9255
9256fn deserialize_remote_project(
9257 connection_options: RemoteConnectionOptions,
9258 paths: Vec<PathBuf>,
9259 cx: &AsyncApp,
9260) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9261 cx.background_spawn(async move {
9262 let remote_connection_id = persistence::DB
9263 .get_or_create_remote_connection(connection_options)
9264 .await?;
9265
9266 let serialized_workspace =
9267 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
9268
9269 let workspace_id = if let Some(workspace_id) =
9270 serialized_workspace.as_ref().map(|workspace| workspace.id)
9271 {
9272 workspace_id
9273 } else {
9274 persistence::DB.next_id().await?
9275 };
9276
9277 Ok((workspace_id, serialized_workspace))
9278 })
9279}
9280
9281pub fn join_in_room_project(
9282 project_id: u64,
9283 follow_user_id: u64,
9284 app_state: Arc<AppState>,
9285 cx: &mut App,
9286) -> Task<Result<()>> {
9287 let windows = cx.windows();
9288 cx.spawn(async move |cx| {
9289 let existing_window_and_workspace: Option<(
9290 WindowHandle<MultiWorkspace>,
9291 Entity<Workspace>,
9292 )> = windows.into_iter().find_map(|window_handle| {
9293 window_handle
9294 .downcast::<MultiWorkspace>()
9295 .and_then(|window_handle| {
9296 window_handle
9297 .update(cx, |multi_workspace, _window, cx| {
9298 for workspace in multi_workspace.workspaces() {
9299 if workspace.read(cx).project().read(cx).remote_id()
9300 == Some(project_id)
9301 {
9302 return Some((window_handle, workspace.clone()));
9303 }
9304 }
9305 None
9306 })
9307 .unwrap_or(None)
9308 })
9309 });
9310
9311 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9312 existing_window_and_workspace
9313 {
9314 existing_window
9315 .update(cx, |multi_workspace, _, cx| {
9316 multi_workspace.activate(target_workspace, cx);
9317 })
9318 .ok();
9319 existing_window
9320 } else {
9321 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9322 let project = cx
9323 .update(|cx| {
9324 active_call.0.join_project(
9325 project_id,
9326 app_state.languages.clone(),
9327 app_state.fs.clone(),
9328 cx,
9329 )
9330 })
9331 .await?;
9332
9333 let window_bounds_override = window_bounds_env_override();
9334 cx.update(|cx| {
9335 let mut options = (app_state.build_window_options)(None, cx);
9336 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9337 cx.open_window(options, |window, cx| {
9338 let workspace = cx.new(|cx| {
9339 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9340 });
9341 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9342 })
9343 })?
9344 };
9345
9346 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9347 cx.activate(true);
9348 window.activate_window();
9349
9350 // We set the active workspace above, so this is the correct workspace.
9351 let workspace = multi_workspace.workspace().clone();
9352 workspace.update(cx, |workspace, cx| {
9353 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9354 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9355 .or_else(|| {
9356 // If we couldn't follow the given user, follow the host instead.
9357 let collaborator = workspace
9358 .project()
9359 .read(cx)
9360 .collaborators()
9361 .values()
9362 .find(|collaborator| collaborator.is_host)?;
9363 Some(collaborator.peer_id)
9364 });
9365
9366 if let Some(follow_peer_id) = follow_peer_id {
9367 workspace.follow(follow_peer_id, window, cx);
9368 }
9369 });
9370 })?;
9371
9372 anyhow::Ok(())
9373 })
9374}
9375
9376pub fn reload(cx: &mut App) {
9377 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9378 let mut workspace_windows = cx
9379 .windows()
9380 .into_iter()
9381 .filter_map(|window| window.downcast::<MultiWorkspace>())
9382 .collect::<Vec<_>>();
9383
9384 // If multiple windows have unsaved changes, and need a save prompt,
9385 // prompt in the active window before switching to a different window.
9386 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9387
9388 let mut prompt = None;
9389 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9390 prompt = window
9391 .update(cx, |_, window, cx| {
9392 window.prompt(
9393 PromptLevel::Info,
9394 "Are you sure you want to restart?",
9395 None,
9396 &["Restart", "Cancel"],
9397 cx,
9398 )
9399 })
9400 .ok();
9401 }
9402
9403 cx.spawn(async move |cx| {
9404 if let Some(prompt) = prompt {
9405 let answer = prompt.await?;
9406 if answer != 0 {
9407 return anyhow::Ok(());
9408 }
9409 }
9410
9411 // If the user cancels any save prompt, then keep the app open.
9412 for window in workspace_windows {
9413 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9414 let workspace = multi_workspace.workspace().clone();
9415 workspace.update(cx, |workspace, cx| {
9416 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9417 })
9418 }) && !should_close.await?
9419 {
9420 return anyhow::Ok(());
9421 }
9422 }
9423 cx.update(|cx| cx.restart());
9424 anyhow::Ok(())
9425 })
9426 .detach_and_log_err(cx);
9427}
9428
9429fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9430 let mut parts = value.split(',');
9431 let x: usize = parts.next()?.parse().ok()?;
9432 let y: usize = parts.next()?.parse().ok()?;
9433 Some(point(px(x as f32), px(y as f32)))
9434}
9435
9436fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9437 let mut parts = value.split(',');
9438 let width: usize = parts.next()?.parse().ok()?;
9439 let height: usize = parts.next()?.parse().ok()?;
9440 Some(size(px(width as f32), px(height as f32)))
9441}
9442
9443/// Add client-side decorations (rounded corners, shadows, resize handling) when
9444/// appropriate.
9445///
9446/// The `border_radius_tiling` parameter allows overriding which corners get
9447/// rounded, independently of the actual window tiling state. This is used
9448/// specifically for the workspace switcher sidebar: when the sidebar is open,
9449/// we want square corners on the left (so the sidebar appears flush with the
9450/// window edge) but we still need the shadow padding for proper visual
9451/// appearance. Unlike actual window tiling, this only affects border radius -
9452/// not padding or shadows.
9453pub fn client_side_decorations(
9454 element: impl IntoElement,
9455 window: &mut Window,
9456 cx: &mut App,
9457 border_radius_tiling: Tiling,
9458) -> Stateful<Div> {
9459 const BORDER_SIZE: Pixels = px(1.0);
9460 let decorations = window.window_decorations();
9461 let tiling = match decorations {
9462 Decorations::Server => Tiling::default(),
9463 Decorations::Client { tiling } => tiling,
9464 };
9465
9466 match decorations {
9467 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9468 Decorations::Server => window.set_client_inset(px(0.0)),
9469 }
9470
9471 struct GlobalResizeEdge(ResizeEdge);
9472 impl Global for GlobalResizeEdge {}
9473
9474 div()
9475 .id("window-backdrop")
9476 .bg(transparent_black())
9477 .map(|div| match decorations {
9478 Decorations::Server => div,
9479 Decorations::Client { .. } => div
9480 .when(
9481 !(tiling.top
9482 || tiling.right
9483 || border_radius_tiling.top
9484 || border_radius_tiling.right),
9485 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9486 )
9487 .when(
9488 !(tiling.top
9489 || tiling.left
9490 || border_radius_tiling.top
9491 || border_radius_tiling.left),
9492 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9493 )
9494 .when(
9495 !(tiling.bottom
9496 || tiling.right
9497 || border_radius_tiling.bottom
9498 || border_radius_tiling.right),
9499 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9500 )
9501 .when(
9502 !(tiling.bottom
9503 || tiling.left
9504 || border_radius_tiling.bottom
9505 || border_radius_tiling.left),
9506 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9507 )
9508 .when(!tiling.top, |div| {
9509 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9510 })
9511 .when(!tiling.bottom, |div| {
9512 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9513 })
9514 .when(!tiling.left, |div| {
9515 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9516 })
9517 .when(!tiling.right, |div| {
9518 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9519 })
9520 .on_mouse_move(move |e, window, cx| {
9521 let size = window.window_bounds().get_bounds().size;
9522 let pos = e.position;
9523
9524 let new_edge =
9525 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9526
9527 let edge = cx.try_global::<GlobalResizeEdge>();
9528 if new_edge != edge.map(|edge| edge.0) {
9529 window
9530 .window_handle()
9531 .update(cx, |workspace, _, cx| {
9532 cx.notify(workspace.entity_id());
9533 })
9534 .ok();
9535 }
9536 })
9537 .on_mouse_down(MouseButton::Left, move |e, window, _| {
9538 let size = window.window_bounds().get_bounds().size;
9539 let pos = e.position;
9540
9541 let edge = match resize_edge(
9542 pos,
9543 theme::CLIENT_SIDE_DECORATION_SHADOW,
9544 size,
9545 tiling,
9546 ) {
9547 Some(value) => value,
9548 None => return,
9549 };
9550
9551 window.start_window_resize(edge);
9552 }),
9553 })
9554 .size_full()
9555 .child(
9556 div()
9557 .cursor(CursorStyle::Arrow)
9558 .map(|div| match decorations {
9559 Decorations::Server => div,
9560 Decorations::Client { .. } => div
9561 .border_color(cx.theme().colors().border)
9562 .when(
9563 !(tiling.top
9564 || tiling.right
9565 || border_radius_tiling.top
9566 || border_radius_tiling.right),
9567 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9568 )
9569 .when(
9570 !(tiling.top
9571 || tiling.left
9572 || border_radius_tiling.top
9573 || border_radius_tiling.left),
9574 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9575 )
9576 .when(
9577 !(tiling.bottom
9578 || tiling.right
9579 || border_radius_tiling.bottom
9580 || border_radius_tiling.right),
9581 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9582 )
9583 .when(
9584 !(tiling.bottom
9585 || tiling.left
9586 || border_radius_tiling.bottom
9587 || border_radius_tiling.left),
9588 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9589 )
9590 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
9591 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
9592 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
9593 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
9594 .when(!tiling.is_tiled(), |div| {
9595 div.shadow(vec![gpui::BoxShadow {
9596 color: Hsla {
9597 h: 0.,
9598 s: 0.,
9599 l: 0.,
9600 a: 0.4,
9601 },
9602 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
9603 spread_radius: px(0.),
9604 offset: point(px(0.0), px(0.0)),
9605 }])
9606 }),
9607 })
9608 .on_mouse_move(|_e, _, cx| {
9609 cx.stop_propagation();
9610 })
9611 .size_full()
9612 .child(element),
9613 )
9614 .map(|div| match decorations {
9615 Decorations::Server => div,
9616 Decorations::Client { tiling, .. } => div.child(
9617 canvas(
9618 |_bounds, window, _| {
9619 window.insert_hitbox(
9620 Bounds::new(
9621 point(px(0.0), px(0.0)),
9622 window.window_bounds().get_bounds().size,
9623 ),
9624 HitboxBehavior::Normal,
9625 )
9626 },
9627 move |_bounds, hitbox, window, cx| {
9628 let mouse = window.mouse_position();
9629 let size = window.window_bounds().get_bounds().size;
9630 let Some(edge) =
9631 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
9632 else {
9633 return;
9634 };
9635 cx.set_global(GlobalResizeEdge(edge));
9636 window.set_cursor_style(
9637 match edge {
9638 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
9639 ResizeEdge::Left | ResizeEdge::Right => {
9640 CursorStyle::ResizeLeftRight
9641 }
9642 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
9643 CursorStyle::ResizeUpLeftDownRight
9644 }
9645 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
9646 CursorStyle::ResizeUpRightDownLeft
9647 }
9648 },
9649 &hitbox,
9650 );
9651 },
9652 )
9653 .size_full()
9654 .absolute(),
9655 ),
9656 })
9657}
9658
9659fn resize_edge(
9660 pos: Point<Pixels>,
9661 shadow_size: Pixels,
9662 window_size: Size<Pixels>,
9663 tiling: Tiling,
9664) -> Option<ResizeEdge> {
9665 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
9666 if bounds.contains(&pos) {
9667 return None;
9668 }
9669
9670 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
9671 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
9672 if !tiling.top && top_left_bounds.contains(&pos) {
9673 return Some(ResizeEdge::TopLeft);
9674 }
9675
9676 let top_right_bounds = Bounds::new(
9677 Point::new(window_size.width - corner_size.width, px(0.)),
9678 corner_size,
9679 );
9680 if !tiling.top && top_right_bounds.contains(&pos) {
9681 return Some(ResizeEdge::TopRight);
9682 }
9683
9684 let bottom_left_bounds = Bounds::new(
9685 Point::new(px(0.), window_size.height - corner_size.height),
9686 corner_size,
9687 );
9688 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
9689 return Some(ResizeEdge::BottomLeft);
9690 }
9691
9692 let bottom_right_bounds = Bounds::new(
9693 Point::new(
9694 window_size.width - corner_size.width,
9695 window_size.height - corner_size.height,
9696 ),
9697 corner_size,
9698 );
9699 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
9700 return Some(ResizeEdge::BottomRight);
9701 }
9702
9703 if !tiling.top && pos.y < shadow_size {
9704 Some(ResizeEdge::Top)
9705 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
9706 Some(ResizeEdge::Bottom)
9707 } else if !tiling.left && pos.x < shadow_size {
9708 Some(ResizeEdge::Left)
9709 } else if !tiling.right && pos.x > window_size.width - shadow_size {
9710 Some(ResizeEdge::Right)
9711 } else {
9712 None
9713 }
9714}
9715
9716fn join_pane_into_active(
9717 active_pane: &Entity<Pane>,
9718 pane: &Entity<Pane>,
9719 window: &mut Window,
9720 cx: &mut App,
9721) {
9722 if pane == active_pane {
9723 } else if pane.read(cx).items_len() == 0 {
9724 pane.update(cx, |_, cx| {
9725 cx.emit(pane::Event::Remove {
9726 focus_on_pane: None,
9727 });
9728 })
9729 } else {
9730 move_all_items(pane, active_pane, window, cx);
9731 }
9732}
9733
9734fn move_all_items(
9735 from_pane: &Entity<Pane>,
9736 to_pane: &Entity<Pane>,
9737 window: &mut Window,
9738 cx: &mut App,
9739) {
9740 let destination_is_different = from_pane != to_pane;
9741 let mut moved_items = 0;
9742 for (item_ix, item_handle) in from_pane
9743 .read(cx)
9744 .items()
9745 .enumerate()
9746 .map(|(ix, item)| (ix, item.clone()))
9747 .collect::<Vec<_>>()
9748 {
9749 let ix = item_ix - moved_items;
9750 if destination_is_different {
9751 // Close item from previous pane
9752 from_pane.update(cx, |source, cx| {
9753 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
9754 });
9755 moved_items += 1;
9756 }
9757
9758 // This automatically removes duplicate items in the pane
9759 to_pane.update(cx, |destination, cx| {
9760 destination.add_item(item_handle, true, true, None, window, cx);
9761 window.focus(&destination.focus_handle(cx), cx)
9762 });
9763 }
9764}
9765
9766pub fn move_item(
9767 source: &Entity<Pane>,
9768 destination: &Entity<Pane>,
9769 item_id_to_move: EntityId,
9770 destination_index: usize,
9771 activate: bool,
9772 window: &mut Window,
9773 cx: &mut App,
9774) {
9775 let Some((item_ix, item_handle)) = source
9776 .read(cx)
9777 .items()
9778 .enumerate()
9779 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
9780 .map(|(ix, item)| (ix, item.clone()))
9781 else {
9782 // Tab was closed during drag
9783 return;
9784 };
9785
9786 if source != destination {
9787 // Close item from previous pane
9788 source.update(cx, |source, cx| {
9789 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
9790 });
9791 }
9792
9793 // This automatically removes duplicate items in the pane
9794 destination.update(cx, |destination, cx| {
9795 destination.add_item_inner(
9796 item_handle,
9797 activate,
9798 activate,
9799 activate,
9800 Some(destination_index),
9801 window,
9802 cx,
9803 );
9804 if activate {
9805 window.focus(&destination.focus_handle(cx), cx)
9806 }
9807 });
9808}
9809
9810pub fn move_active_item(
9811 source: &Entity<Pane>,
9812 destination: &Entity<Pane>,
9813 focus_destination: bool,
9814 close_if_empty: bool,
9815 window: &mut Window,
9816 cx: &mut App,
9817) {
9818 if source == destination {
9819 return;
9820 }
9821 let Some(active_item) = source.read(cx).active_item() else {
9822 return;
9823 };
9824 source.update(cx, |source_pane, cx| {
9825 let item_id = active_item.item_id();
9826 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
9827 destination.update(cx, |target_pane, cx| {
9828 target_pane.add_item(
9829 active_item,
9830 focus_destination,
9831 focus_destination,
9832 Some(target_pane.items_len()),
9833 window,
9834 cx,
9835 );
9836 });
9837 });
9838}
9839
9840pub fn clone_active_item(
9841 workspace_id: Option<WorkspaceId>,
9842 source: &Entity<Pane>,
9843 destination: &Entity<Pane>,
9844 focus_destination: bool,
9845 window: &mut Window,
9846 cx: &mut App,
9847) {
9848 if source == destination {
9849 return;
9850 }
9851 let Some(active_item) = source.read(cx).active_item() else {
9852 return;
9853 };
9854 if !active_item.can_split(cx) {
9855 return;
9856 }
9857 let destination = destination.downgrade();
9858 let task = active_item.clone_on_split(workspace_id, window, cx);
9859 window
9860 .spawn(cx, async move |cx| {
9861 let Some(clone) = task.await else {
9862 return;
9863 };
9864 destination
9865 .update_in(cx, |target_pane, window, cx| {
9866 target_pane.add_item(
9867 clone,
9868 focus_destination,
9869 focus_destination,
9870 Some(target_pane.items_len()),
9871 window,
9872 cx,
9873 );
9874 })
9875 .log_err();
9876 })
9877 .detach();
9878}
9879
9880#[derive(Debug)]
9881pub struct WorkspacePosition {
9882 pub window_bounds: Option<WindowBounds>,
9883 pub display: Option<Uuid>,
9884 pub centered_layout: bool,
9885}
9886
9887pub fn remote_workspace_position_from_db(
9888 connection_options: RemoteConnectionOptions,
9889 paths_to_open: &[PathBuf],
9890 cx: &App,
9891) -> Task<Result<WorkspacePosition>> {
9892 let paths = paths_to_open.to_vec();
9893
9894 cx.background_spawn(async move {
9895 let remote_connection_id = persistence::DB
9896 .get_or_create_remote_connection(connection_options)
9897 .await
9898 .context("fetching serialized ssh project")?;
9899 let serialized_workspace =
9900 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
9901
9902 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
9903 (Some(WindowBounds::Windowed(bounds)), None)
9904 } else {
9905 let restorable_bounds = serialized_workspace
9906 .as_ref()
9907 .and_then(|workspace| {
9908 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
9909 })
9910 .or_else(|| persistence::read_default_window_bounds());
9911
9912 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
9913 (Some(serialized_bounds), Some(serialized_display))
9914 } else {
9915 (None, None)
9916 }
9917 };
9918
9919 let centered_layout = serialized_workspace
9920 .as_ref()
9921 .map(|w| w.centered_layout)
9922 .unwrap_or(false);
9923
9924 Ok(WorkspacePosition {
9925 window_bounds,
9926 display,
9927 centered_layout,
9928 })
9929 })
9930}
9931
9932pub fn with_active_or_new_workspace(
9933 cx: &mut App,
9934 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
9935) {
9936 match cx
9937 .active_window()
9938 .and_then(|w| w.downcast::<MultiWorkspace>())
9939 {
9940 Some(multi_workspace) => {
9941 cx.defer(move |cx| {
9942 multi_workspace
9943 .update(cx, |multi_workspace, window, cx| {
9944 let workspace = multi_workspace.workspace().clone();
9945 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
9946 })
9947 .log_err();
9948 });
9949 }
9950 None => {
9951 let app_state = AppState::global(cx);
9952 if let Some(app_state) = app_state.upgrade() {
9953 open_new(
9954 OpenOptions::default(),
9955 app_state,
9956 cx,
9957 move |workspace, window, cx| f(workspace, window, cx),
9958 )
9959 .detach_and_log_err(cx);
9960 }
9961 }
9962 }
9963}
9964
9965#[cfg(test)]
9966mod tests {
9967 use std::{cell::RefCell, rc::Rc};
9968
9969 use super::*;
9970 use crate::{
9971 dock::{PanelEvent, test::TestPanel},
9972 item::{
9973 ItemBufferKind, ItemEvent,
9974 test::{TestItem, TestProjectItem},
9975 },
9976 };
9977 use fs::FakeFs;
9978 use gpui::{
9979 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
9980 UpdateGlobal, VisualTestContext, px,
9981 };
9982 use project::{Project, ProjectEntryId};
9983 use serde_json::json;
9984 use settings::SettingsStore;
9985 use util::rel_path::rel_path;
9986
9987 #[gpui::test]
9988 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
9989 init_test(cx);
9990
9991 let fs = FakeFs::new(cx.executor());
9992 let project = Project::test(fs, [], cx).await;
9993 let (workspace, cx) =
9994 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9995
9996 // Adding an item with no ambiguity renders the tab without detail.
9997 let item1 = cx.new(|cx| {
9998 let mut item = TestItem::new(cx);
9999 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10000 item
10001 });
10002 workspace.update_in(cx, |workspace, window, cx| {
10003 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10004 });
10005 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10006
10007 // Adding an item that creates ambiguity increases the level of detail on
10008 // both tabs.
10009 let item2 = cx.new_window_entity(|_window, cx| {
10010 let mut item = TestItem::new(cx);
10011 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10012 item
10013 });
10014 workspace.update_in(cx, |workspace, window, cx| {
10015 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10016 });
10017 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10018 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10019
10020 // Adding an item that creates ambiguity increases the level of detail only
10021 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10022 // we stop at the highest detail available.
10023 let item3 = cx.new(|cx| {
10024 let mut item = TestItem::new(cx);
10025 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10026 item
10027 });
10028 workspace.update_in(cx, |workspace, window, cx| {
10029 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10030 });
10031 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10032 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10033 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10034 }
10035
10036 #[gpui::test]
10037 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10038 init_test(cx);
10039
10040 let fs = FakeFs::new(cx.executor());
10041 fs.insert_tree(
10042 "/root1",
10043 json!({
10044 "one.txt": "",
10045 "two.txt": "",
10046 }),
10047 )
10048 .await;
10049 fs.insert_tree(
10050 "/root2",
10051 json!({
10052 "three.txt": "",
10053 }),
10054 )
10055 .await;
10056
10057 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10058 let (workspace, cx) =
10059 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10060 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10061 let worktree_id = project.update(cx, |project, cx| {
10062 project.worktrees(cx).next().unwrap().read(cx).id()
10063 });
10064
10065 let item1 = cx.new(|cx| {
10066 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10067 });
10068 let item2 = cx.new(|cx| {
10069 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10070 });
10071
10072 // Add an item to an empty pane
10073 workspace.update_in(cx, |workspace, window, cx| {
10074 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10075 });
10076 project.update(cx, |project, cx| {
10077 assert_eq!(
10078 project.active_entry(),
10079 project
10080 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10081 .map(|e| e.id)
10082 );
10083 });
10084 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10085
10086 // Add a second item to a non-empty pane
10087 workspace.update_in(cx, |workspace, window, cx| {
10088 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10089 });
10090 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10091 project.update(cx, |project, cx| {
10092 assert_eq!(
10093 project.active_entry(),
10094 project
10095 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10096 .map(|e| e.id)
10097 );
10098 });
10099
10100 // Close the active item
10101 pane.update_in(cx, |pane, window, cx| {
10102 pane.close_active_item(&Default::default(), window, cx)
10103 })
10104 .await
10105 .unwrap();
10106 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10107 project.update(cx, |project, cx| {
10108 assert_eq!(
10109 project.active_entry(),
10110 project
10111 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10112 .map(|e| e.id)
10113 );
10114 });
10115
10116 // Add a project folder
10117 project
10118 .update(cx, |project, cx| {
10119 project.find_or_create_worktree("root2", true, cx)
10120 })
10121 .await
10122 .unwrap();
10123 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10124
10125 // Remove a project folder
10126 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10127 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10128 }
10129
10130 #[gpui::test]
10131 async fn test_close_window(cx: &mut TestAppContext) {
10132 init_test(cx);
10133
10134 let fs = FakeFs::new(cx.executor());
10135 fs.insert_tree("/root", json!({ "one": "" })).await;
10136
10137 let project = Project::test(fs, ["root".as_ref()], cx).await;
10138 let (workspace, cx) =
10139 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10140
10141 // When there are no dirty items, there's nothing to do.
10142 let item1 = cx.new(TestItem::new);
10143 workspace.update_in(cx, |w, window, cx| {
10144 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10145 });
10146 let task = workspace.update_in(cx, |w, window, cx| {
10147 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10148 });
10149 assert!(task.await.unwrap());
10150
10151 // When there are dirty untitled items, prompt to save each one. If the user
10152 // cancels any prompt, then abort.
10153 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10154 let item3 = cx.new(|cx| {
10155 TestItem::new(cx)
10156 .with_dirty(true)
10157 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10158 });
10159 workspace.update_in(cx, |w, window, cx| {
10160 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10161 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10162 });
10163 let task = workspace.update_in(cx, |w, window, cx| {
10164 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10165 });
10166 cx.executor().run_until_parked();
10167 cx.simulate_prompt_answer("Cancel"); // cancel save all
10168 cx.executor().run_until_parked();
10169 assert!(!cx.has_pending_prompt());
10170 assert!(!task.await.unwrap());
10171 }
10172
10173 #[gpui::test]
10174 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10175 init_test(cx);
10176
10177 let fs = FakeFs::new(cx.executor());
10178 fs.insert_tree("/root", json!({ "one": "" })).await;
10179
10180 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10181 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10182 let multi_workspace_handle =
10183 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10184 cx.run_until_parked();
10185
10186 let workspace_a = multi_workspace_handle
10187 .read_with(cx, |mw, _| mw.workspace().clone())
10188 .unwrap();
10189
10190 let workspace_b = multi_workspace_handle
10191 .update(cx, |mw, window, cx| {
10192 mw.test_add_workspace(project_b, window, cx)
10193 })
10194 .unwrap();
10195
10196 // Activate workspace A
10197 multi_workspace_handle
10198 .update(cx, |mw, window, cx| {
10199 mw.activate_index(0, window, cx);
10200 })
10201 .unwrap();
10202
10203 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10204
10205 // Workspace A has a clean item
10206 let item_a = cx.new(TestItem::new);
10207 workspace_a.update_in(cx, |w, window, cx| {
10208 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10209 });
10210
10211 // Workspace B has a dirty item
10212 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10213 workspace_b.update_in(cx, |w, window, cx| {
10214 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10215 });
10216
10217 // Verify workspace A is active
10218 multi_workspace_handle
10219 .read_with(cx, |mw, _| {
10220 assert_eq!(mw.active_workspace_index(), 0);
10221 })
10222 .unwrap();
10223
10224 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10225 multi_workspace_handle
10226 .update(cx, |mw, window, cx| {
10227 mw.close_window(&CloseWindow, window, cx);
10228 })
10229 .unwrap();
10230 cx.run_until_parked();
10231
10232 // Workspace B should now be active since it has dirty items that need attention
10233 multi_workspace_handle
10234 .read_with(cx, |mw, _| {
10235 assert_eq!(
10236 mw.active_workspace_index(),
10237 1,
10238 "workspace B should be activated when it prompts"
10239 );
10240 })
10241 .unwrap();
10242
10243 // User cancels the save prompt from workspace B
10244 cx.simulate_prompt_answer("Cancel");
10245 cx.run_until_parked();
10246
10247 // Window should still exist because workspace B's close was cancelled
10248 assert!(
10249 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10250 "window should still exist after cancelling one workspace's close"
10251 );
10252 }
10253
10254 #[gpui::test]
10255 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10256 init_test(cx);
10257
10258 // Register TestItem as a serializable item
10259 cx.update(|cx| {
10260 register_serializable_item::<TestItem>(cx);
10261 });
10262
10263 let fs = FakeFs::new(cx.executor());
10264 fs.insert_tree("/root", json!({ "one": "" })).await;
10265
10266 let project = Project::test(fs, ["root".as_ref()], cx).await;
10267 let (workspace, cx) =
10268 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10269
10270 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10271 let item1 = cx.new(|cx| {
10272 TestItem::new(cx)
10273 .with_dirty(true)
10274 .with_serialize(|| Some(Task::ready(Ok(()))))
10275 });
10276 let item2 = cx.new(|cx| {
10277 TestItem::new(cx)
10278 .with_dirty(true)
10279 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10280 .with_serialize(|| Some(Task::ready(Ok(()))))
10281 });
10282 workspace.update_in(cx, |w, window, cx| {
10283 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10284 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10285 });
10286 let task = workspace.update_in(cx, |w, window, cx| {
10287 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10288 });
10289 assert!(task.await.unwrap());
10290 }
10291
10292 #[gpui::test]
10293 async fn test_close_pane_items(cx: &mut TestAppContext) {
10294 init_test(cx);
10295
10296 let fs = FakeFs::new(cx.executor());
10297
10298 let project = Project::test(fs, None, cx).await;
10299 let (workspace, cx) =
10300 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10301
10302 let item1 = cx.new(|cx| {
10303 TestItem::new(cx)
10304 .with_dirty(true)
10305 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10306 });
10307 let item2 = cx.new(|cx| {
10308 TestItem::new(cx)
10309 .with_dirty(true)
10310 .with_conflict(true)
10311 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10312 });
10313 let item3 = cx.new(|cx| {
10314 TestItem::new(cx)
10315 .with_dirty(true)
10316 .with_conflict(true)
10317 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10318 });
10319 let item4 = cx.new(|cx| {
10320 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10321 let project_item = TestProjectItem::new_untitled(cx);
10322 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10323 project_item
10324 }])
10325 });
10326 let pane = workspace.update_in(cx, |workspace, window, cx| {
10327 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10328 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10329 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10330 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10331 workspace.active_pane().clone()
10332 });
10333
10334 let close_items = pane.update_in(cx, |pane, window, cx| {
10335 pane.activate_item(1, true, true, window, cx);
10336 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10337 let item1_id = item1.item_id();
10338 let item3_id = item3.item_id();
10339 let item4_id = item4.item_id();
10340 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10341 [item1_id, item3_id, item4_id].contains(&id)
10342 })
10343 });
10344 cx.executor().run_until_parked();
10345
10346 assert!(cx.has_pending_prompt());
10347 cx.simulate_prompt_answer("Save all");
10348
10349 cx.executor().run_until_parked();
10350
10351 // Item 1 is saved. There's a prompt to save item 3.
10352 pane.update(cx, |pane, cx| {
10353 assert_eq!(item1.read(cx).save_count, 1);
10354 assert_eq!(item1.read(cx).save_as_count, 0);
10355 assert_eq!(item1.read(cx).reload_count, 0);
10356 assert_eq!(pane.items_len(), 3);
10357 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10358 });
10359 assert!(cx.has_pending_prompt());
10360
10361 // Cancel saving item 3.
10362 cx.simulate_prompt_answer("Discard");
10363 cx.executor().run_until_parked();
10364
10365 // Item 3 is reloaded. There's a prompt to save item 4.
10366 pane.update(cx, |pane, cx| {
10367 assert_eq!(item3.read(cx).save_count, 0);
10368 assert_eq!(item3.read(cx).save_as_count, 0);
10369 assert_eq!(item3.read(cx).reload_count, 1);
10370 assert_eq!(pane.items_len(), 2);
10371 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10372 });
10373
10374 // There's a prompt for a path for item 4.
10375 cx.simulate_new_path_selection(|_| Some(Default::default()));
10376 close_items.await.unwrap();
10377
10378 // The requested items are closed.
10379 pane.update(cx, |pane, cx| {
10380 assert_eq!(item4.read(cx).save_count, 0);
10381 assert_eq!(item4.read(cx).save_as_count, 1);
10382 assert_eq!(item4.read(cx).reload_count, 0);
10383 assert_eq!(pane.items_len(), 1);
10384 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10385 });
10386 }
10387
10388 #[gpui::test]
10389 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10390 init_test(cx);
10391
10392 let fs = FakeFs::new(cx.executor());
10393 let project = Project::test(fs, [], cx).await;
10394 let (workspace, cx) =
10395 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10396
10397 // Create several workspace items with single project entries, and two
10398 // workspace items with multiple project entries.
10399 let single_entry_items = (0..=4)
10400 .map(|project_entry_id| {
10401 cx.new(|cx| {
10402 TestItem::new(cx)
10403 .with_dirty(true)
10404 .with_project_items(&[dirty_project_item(
10405 project_entry_id,
10406 &format!("{project_entry_id}.txt"),
10407 cx,
10408 )])
10409 })
10410 })
10411 .collect::<Vec<_>>();
10412 let item_2_3 = cx.new(|cx| {
10413 TestItem::new(cx)
10414 .with_dirty(true)
10415 .with_buffer_kind(ItemBufferKind::Multibuffer)
10416 .with_project_items(&[
10417 single_entry_items[2].read(cx).project_items[0].clone(),
10418 single_entry_items[3].read(cx).project_items[0].clone(),
10419 ])
10420 });
10421 let item_3_4 = cx.new(|cx| {
10422 TestItem::new(cx)
10423 .with_dirty(true)
10424 .with_buffer_kind(ItemBufferKind::Multibuffer)
10425 .with_project_items(&[
10426 single_entry_items[3].read(cx).project_items[0].clone(),
10427 single_entry_items[4].read(cx).project_items[0].clone(),
10428 ])
10429 });
10430
10431 // Create two panes that contain the following project entries:
10432 // left pane:
10433 // multi-entry items: (2, 3)
10434 // single-entry items: 0, 2, 3, 4
10435 // right pane:
10436 // single-entry items: 4, 1
10437 // multi-entry items: (3, 4)
10438 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10439 let left_pane = workspace.active_pane().clone();
10440 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10441 workspace.add_item_to_active_pane(
10442 single_entry_items[0].boxed_clone(),
10443 None,
10444 true,
10445 window,
10446 cx,
10447 );
10448 workspace.add_item_to_active_pane(
10449 single_entry_items[2].boxed_clone(),
10450 None,
10451 true,
10452 window,
10453 cx,
10454 );
10455 workspace.add_item_to_active_pane(
10456 single_entry_items[3].boxed_clone(),
10457 None,
10458 true,
10459 window,
10460 cx,
10461 );
10462 workspace.add_item_to_active_pane(
10463 single_entry_items[4].boxed_clone(),
10464 None,
10465 true,
10466 window,
10467 cx,
10468 );
10469
10470 let right_pane =
10471 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10472
10473 let boxed_clone = single_entry_items[1].boxed_clone();
10474 let right_pane = window.spawn(cx, async move |cx| {
10475 right_pane.await.inspect(|right_pane| {
10476 right_pane
10477 .update_in(cx, |pane, window, cx| {
10478 pane.add_item(boxed_clone, true, true, None, window, cx);
10479 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10480 })
10481 .unwrap();
10482 })
10483 });
10484
10485 (left_pane, right_pane)
10486 });
10487 let right_pane = right_pane.await.unwrap();
10488 cx.focus(&right_pane);
10489
10490 let close = right_pane.update_in(cx, |pane, window, cx| {
10491 pane.close_all_items(&CloseAllItems::default(), window, cx)
10492 .unwrap()
10493 });
10494 cx.executor().run_until_parked();
10495
10496 let msg = cx.pending_prompt().unwrap().0;
10497 assert!(msg.contains("1.txt"));
10498 assert!(!msg.contains("2.txt"));
10499 assert!(!msg.contains("3.txt"));
10500 assert!(!msg.contains("4.txt"));
10501
10502 // With best-effort close, cancelling item 1 keeps it open but items 4
10503 // and (3,4) still close since their entries exist in left pane.
10504 cx.simulate_prompt_answer("Cancel");
10505 close.await;
10506
10507 right_pane.read_with(cx, |pane, _| {
10508 assert_eq!(pane.items_len(), 1);
10509 });
10510
10511 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10512 left_pane
10513 .update_in(cx, |left_pane, window, cx| {
10514 left_pane.close_item_by_id(
10515 single_entry_items[3].entity_id(),
10516 SaveIntent::Skip,
10517 window,
10518 cx,
10519 )
10520 })
10521 .await
10522 .unwrap();
10523
10524 let close = left_pane.update_in(cx, |pane, window, cx| {
10525 pane.close_all_items(&CloseAllItems::default(), window, cx)
10526 .unwrap()
10527 });
10528 cx.executor().run_until_parked();
10529
10530 let details = cx.pending_prompt().unwrap().1;
10531 assert!(details.contains("0.txt"));
10532 assert!(details.contains("3.txt"));
10533 assert!(details.contains("4.txt"));
10534 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10535 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10536 // assert!(!details.contains("2.txt"));
10537
10538 cx.simulate_prompt_answer("Save all");
10539 cx.executor().run_until_parked();
10540 close.await;
10541
10542 left_pane.read_with(cx, |pane, _| {
10543 assert_eq!(pane.items_len(), 0);
10544 });
10545 }
10546
10547 #[gpui::test]
10548 async fn test_autosave(cx: &mut gpui::TestAppContext) {
10549 init_test(cx);
10550
10551 let fs = FakeFs::new(cx.executor());
10552 let project = Project::test(fs, [], cx).await;
10553 let (workspace, cx) =
10554 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10555 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10556
10557 let item = cx.new(|cx| {
10558 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10559 });
10560 let item_id = item.entity_id();
10561 workspace.update_in(cx, |workspace, window, cx| {
10562 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10563 });
10564
10565 // Autosave on window change.
10566 item.update(cx, |item, cx| {
10567 SettingsStore::update_global(cx, |settings, cx| {
10568 settings.update_user_settings(cx, |settings| {
10569 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10570 })
10571 });
10572 item.is_dirty = true;
10573 });
10574
10575 // Deactivating the window saves the file.
10576 cx.deactivate_window();
10577 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10578
10579 // Re-activating the window doesn't save the file.
10580 cx.update(|window, _| window.activate_window());
10581 cx.executor().run_until_parked();
10582 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10583
10584 // Autosave on focus change.
10585 item.update_in(cx, |item, window, cx| {
10586 cx.focus_self(window);
10587 SettingsStore::update_global(cx, |settings, cx| {
10588 settings.update_user_settings(cx, |settings| {
10589 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10590 })
10591 });
10592 item.is_dirty = true;
10593 });
10594 // Blurring the item saves the file.
10595 item.update_in(cx, |_, window, _| window.blur());
10596 cx.executor().run_until_parked();
10597 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10598
10599 // Deactivating the window still saves the file.
10600 item.update_in(cx, |item, window, cx| {
10601 cx.focus_self(window);
10602 item.is_dirty = true;
10603 });
10604 cx.deactivate_window();
10605 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10606
10607 // Autosave after delay.
10608 item.update(cx, |item, cx| {
10609 SettingsStore::update_global(cx, |settings, cx| {
10610 settings.update_user_settings(cx, |settings| {
10611 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10612 milliseconds: 500.into(),
10613 });
10614 })
10615 });
10616 item.is_dirty = true;
10617 cx.emit(ItemEvent::Edit);
10618 });
10619
10620 // Delay hasn't fully expired, so the file is still dirty and unsaved.
10621 cx.executor().advance_clock(Duration::from_millis(250));
10622 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10623
10624 // After delay expires, the file is saved.
10625 cx.executor().advance_clock(Duration::from_millis(250));
10626 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10627
10628 // Autosave after delay, should save earlier than delay if tab is closed
10629 item.update(cx, |item, cx| {
10630 item.is_dirty = true;
10631 cx.emit(ItemEvent::Edit);
10632 });
10633 cx.executor().advance_clock(Duration::from_millis(250));
10634 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10635
10636 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10637 pane.update_in(cx, |pane, window, cx| {
10638 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10639 })
10640 .await
10641 .unwrap();
10642 assert!(!cx.has_pending_prompt());
10643 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10644
10645 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10646 workspace.update_in(cx, |workspace, window, cx| {
10647 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10648 });
10649 item.update_in(cx, |item, _window, cx| {
10650 item.is_dirty = true;
10651 for project_item in &mut item.project_items {
10652 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10653 }
10654 });
10655 cx.run_until_parked();
10656 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10657
10658 // Autosave on focus change, ensuring closing the tab counts as such.
10659 item.update(cx, |item, cx| {
10660 SettingsStore::update_global(cx, |settings, cx| {
10661 settings.update_user_settings(cx, |settings| {
10662 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10663 })
10664 });
10665 item.is_dirty = true;
10666 for project_item in &mut item.project_items {
10667 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10668 }
10669 });
10670
10671 pane.update_in(cx, |pane, window, cx| {
10672 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10673 })
10674 .await
10675 .unwrap();
10676 assert!(!cx.has_pending_prompt());
10677 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10678
10679 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10680 workspace.update_in(cx, |workspace, window, cx| {
10681 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10682 });
10683 item.update_in(cx, |item, window, cx| {
10684 item.project_items[0].update(cx, |item, _| {
10685 item.entry_id = None;
10686 });
10687 item.is_dirty = true;
10688 window.blur();
10689 });
10690 cx.run_until_parked();
10691 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10692
10693 // Ensure autosave is prevented for deleted files also when closing the buffer.
10694 let _close_items = pane.update_in(cx, |pane, window, cx| {
10695 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10696 });
10697 cx.run_until_parked();
10698 assert!(cx.has_pending_prompt());
10699 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10700 }
10701
10702 #[gpui::test]
10703 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
10704 init_test(cx);
10705
10706 let fs = FakeFs::new(cx.executor());
10707 let project = Project::test(fs, [], cx).await;
10708 let (workspace, cx) =
10709 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10710
10711 // Create a multibuffer-like item with two child focus handles,
10712 // simulating individual buffer editors within a multibuffer.
10713 let item = cx.new(|cx| {
10714 TestItem::new(cx)
10715 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10716 .with_child_focus_handles(2, cx)
10717 });
10718 workspace.update_in(cx, |workspace, window, cx| {
10719 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10720 });
10721
10722 // Set autosave to OnFocusChange and focus the first child handle,
10723 // simulating the user's cursor being inside one of the multibuffer's excerpts.
10724 item.update_in(cx, |item, window, cx| {
10725 SettingsStore::update_global(cx, |settings, cx| {
10726 settings.update_user_settings(cx, |settings| {
10727 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10728 })
10729 });
10730 item.is_dirty = true;
10731 window.focus(&item.child_focus_handles[0], cx);
10732 });
10733 cx.executor().run_until_parked();
10734 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
10735
10736 // Moving focus from one child to another within the same item should
10737 // NOT trigger autosave — focus is still within the item's focus hierarchy.
10738 item.update_in(cx, |item, window, cx| {
10739 window.focus(&item.child_focus_handles[1], cx);
10740 });
10741 cx.executor().run_until_parked();
10742 item.read_with(cx, |item, _| {
10743 assert_eq!(
10744 item.save_count, 0,
10745 "Switching focus between children within the same item should not autosave"
10746 );
10747 });
10748
10749 // Blurring the item saves the file. This is the core regression scenario:
10750 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
10751 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
10752 // the leaf is always a child focus handle, so `on_blur` never detected
10753 // focus leaving the item.
10754 item.update_in(cx, |_, window, _| window.blur());
10755 cx.executor().run_until_parked();
10756 item.read_with(cx, |item, _| {
10757 assert_eq!(
10758 item.save_count, 1,
10759 "Blurring should trigger autosave when focus was on a child of the item"
10760 );
10761 });
10762
10763 // Deactivating the window should also trigger autosave when a child of
10764 // the multibuffer item currently owns focus.
10765 item.update_in(cx, |item, window, cx| {
10766 item.is_dirty = true;
10767 window.focus(&item.child_focus_handles[0], cx);
10768 });
10769 cx.executor().run_until_parked();
10770 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10771
10772 cx.deactivate_window();
10773 item.read_with(cx, |item, _| {
10774 assert_eq!(
10775 item.save_count, 2,
10776 "Deactivating window should trigger autosave when focus was on a child"
10777 );
10778 });
10779 }
10780
10781 #[gpui::test]
10782 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10783 init_test(cx);
10784
10785 let fs = FakeFs::new(cx.executor());
10786
10787 let project = Project::test(fs, [], cx).await;
10788 let (workspace, cx) =
10789 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10790
10791 let item = cx.new(|cx| {
10792 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10793 });
10794 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10795 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10796 let toolbar_notify_count = Rc::new(RefCell::new(0));
10797
10798 workspace.update_in(cx, |workspace, window, cx| {
10799 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10800 let toolbar_notification_count = toolbar_notify_count.clone();
10801 cx.observe_in(&toolbar, window, move |_, _, _, _| {
10802 *toolbar_notification_count.borrow_mut() += 1
10803 })
10804 .detach();
10805 });
10806
10807 pane.read_with(cx, |pane, _| {
10808 assert!(!pane.can_navigate_backward());
10809 assert!(!pane.can_navigate_forward());
10810 });
10811
10812 item.update_in(cx, |item, _, cx| {
10813 item.set_state("one".to_string(), cx);
10814 });
10815
10816 // Toolbar must be notified to re-render the navigation buttons
10817 assert_eq!(*toolbar_notify_count.borrow(), 1);
10818
10819 pane.read_with(cx, |pane, _| {
10820 assert!(pane.can_navigate_backward());
10821 assert!(!pane.can_navigate_forward());
10822 });
10823
10824 workspace
10825 .update_in(cx, |workspace, window, cx| {
10826 workspace.go_back(pane.downgrade(), window, cx)
10827 })
10828 .await
10829 .unwrap();
10830
10831 assert_eq!(*toolbar_notify_count.borrow(), 2);
10832 pane.read_with(cx, |pane, _| {
10833 assert!(!pane.can_navigate_backward());
10834 assert!(pane.can_navigate_forward());
10835 });
10836 }
10837
10838 #[gpui::test]
10839 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
10840 init_test(cx);
10841 let fs = FakeFs::new(cx.executor());
10842 let project = Project::test(fs, [], cx).await;
10843 let (multi_workspace, cx) =
10844 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
10845 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
10846
10847 workspace.update_in(cx, |workspace, window, cx| {
10848 let first_item = cx.new(|cx| {
10849 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10850 });
10851 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
10852 workspace.split_pane(
10853 workspace.active_pane().clone(),
10854 SplitDirection::Right,
10855 window,
10856 cx,
10857 );
10858 workspace.split_pane(
10859 workspace.active_pane().clone(),
10860 SplitDirection::Right,
10861 window,
10862 cx,
10863 );
10864 });
10865
10866 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
10867 let panes = workspace.center.panes();
10868 assert!(panes.len() >= 2);
10869 (
10870 panes.first().expect("at least one pane").entity_id(),
10871 panes.last().expect("at least one pane").entity_id(),
10872 )
10873 });
10874
10875 workspace.update_in(cx, |workspace, window, cx| {
10876 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
10877 });
10878 workspace.update(cx, |workspace, _| {
10879 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
10880 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
10881 });
10882
10883 cx.dispatch_action(ActivateLastPane);
10884
10885 workspace.update(cx, |workspace, _| {
10886 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
10887 });
10888 }
10889
10890 #[gpui::test]
10891 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
10892 init_test(cx);
10893 let fs = FakeFs::new(cx.executor());
10894
10895 let project = Project::test(fs, [], cx).await;
10896 let (workspace, cx) =
10897 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10898
10899 let panel = workspace.update_in(cx, |workspace, window, cx| {
10900 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10901 workspace.add_panel(panel.clone(), window, cx);
10902
10903 workspace
10904 .right_dock()
10905 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10906
10907 panel
10908 });
10909
10910 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10911 pane.update_in(cx, |pane, window, cx| {
10912 let item = cx.new(TestItem::new);
10913 pane.add_item(Box::new(item), true, true, None, window, cx);
10914 });
10915
10916 // Transfer focus from center to panel
10917 workspace.update_in(cx, |workspace, window, cx| {
10918 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10919 });
10920
10921 workspace.update_in(cx, |workspace, window, cx| {
10922 assert!(workspace.right_dock().read(cx).is_open());
10923 assert!(!panel.is_zoomed(window, cx));
10924 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10925 });
10926
10927 // Transfer focus from panel to center
10928 workspace.update_in(cx, |workspace, window, cx| {
10929 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10930 });
10931
10932 workspace.update_in(cx, |workspace, window, cx| {
10933 assert!(workspace.right_dock().read(cx).is_open());
10934 assert!(!panel.is_zoomed(window, cx));
10935 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10936 });
10937
10938 // Close the dock
10939 workspace.update_in(cx, |workspace, window, cx| {
10940 workspace.toggle_dock(DockPosition::Right, window, cx);
10941 });
10942
10943 workspace.update_in(cx, |workspace, window, cx| {
10944 assert!(!workspace.right_dock().read(cx).is_open());
10945 assert!(!panel.is_zoomed(window, cx));
10946 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10947 });
10948
10949 // Open the dock
10950 workspace.update_in(cx, |workspace, window, cx| {
10951 workspace.toggle_dock(DockPosition::Right, window, cx);
10952 });
10953
10954 workspace.update_in(cx, |workspace, window, cx| {
10955 assert!(workspace.right_dock().read(cx).is_open());
10956 assert!(!panel.is_zoomed(window, cx));
10957 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10958 });
10959
10960 // Focus and zoom panel
10961 panel.update_in(cx, |panel, window, cx| {
10962 cx.focus_self(window);
10963 panel.set_zoomed(true, window, cx)
10964 });
10965
10966 workspace.update_in(cx, |workspace, window, cx| {
10967 assert!(workspace.right_dock().read(cx).is_open());
10968 assert!(panel.is_zoomed(window, cx));
10969 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10970 });
10971
10972 // Transfer focus to the center closes the dock
10973 workspace.update_in(cx, |workspace, window, cx| {
10974 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10975 });
10976
10977 workspace.update_in(cx, |workspace, window, cx| {
10978 assert!(!workspace.right_dock().read(cx).is_open());
10979 assert!(panel.is_zoomed(window, cx));
10980 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10981 });
10982
10983 // Transferring focus back to the panel keeps it zoomed
10984 workspace.update_in(cx, |workspace, window, cx| {
10985 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10986 });
10987
10988 workspace.update_in(cx, |workspace, window, cx| {
10989 assert!(workspace.right_dock().read(cx).is_open());
10990 assert!(panel.is_zoomed(window, cx));
10991 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10992 });
10993
10994 // Close the dock while it is zoomed
10995 workspace.update_in(cx, |workspace, window, cx| {
10996 workspace.toggle_dock(DockPosition::Right, window, cx)
10997 });
10998
10999 workspace.update_in(cx, |workspace, window, cx| {
11000 assert!(!workspace.right_dock().read(cx).is_open());
11001 assert!(panel.is_zoomed(window, cx));
11002 assert!(workspace.zoomed.is_none());
11003 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11004 });
11005
11006 // Opening the dock, when it's zoomed, retains focus
11007 workspace.update_in(cx, |workspace, window, cx| {
11008 workspace.toggle_dock(DockPosition::Right, window, cx)
11009 });
11010
11011 workspace.update_in(cx, |workspace, window, cx| {
11012 assert!(workspace.right_dock().read(cx).is_open());
11013 assert!(panel.is_zoomed(window, cx));
11014 assert!(workspace.zoomed.is_some());
11015 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11016 });
11017
11018 // Unzoom and close the panel, zoom the active pane.
11019 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11020 workspace.update_in(cx, |workspace, window, cx| {
11021 workspace.toggle_dock(DockPosition::Right, window, cx)
11022 });
11023 pane.update_in(cx, |pane, window, cx| {
11024 pane.toggle_zoom(&Default::default(), window, cx)
11025 });
11026
11027 // Opening a dock unzooms the pane.
11028 workspace.update_in(cx, |workspace, window, cx| {
11029 workspace.toggle_dock(DockPosition::Right, window, cx)
11030 });
11031 workspace.update_in(cx, |workspace, window, cx| {
11032 let pane = pane.read(cx);
11033 assert!(!pane.is_zoomed());
11034 assert!(!pane.focus_handle(cx).is_focused(window));
11035 assert!(workspace.right_dock().read(cx).is_open());
11036 assert!(workspace.zoomed.is_none());
11037 });
11038 }
11039
11040 #[gpui::test]
11041 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11042 init_test(cx);
11043 let fs = FakeFs::new(cx.executor());
11044
11045 let project = Project::test(fs, [], cx).await;
11046 let (workspace, cx) =
11047 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11048
11049 let panel = workspace.update_in(cx, |workspace, window, cx| {
11050 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11051 workspace.add_panel(panel.clone(), window, cx);
11052 panel
11053 });
11054
11055 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11056 pane.update_in(cx, |pane, window, cx| {
11057 let item = cx.new(TestItem::new);
11058 pane.add_item(Box::new(item), true, true, None, window, cx);
11059 });
11060
11061 // Enable close_panel_on_toggle
11062 cx.update_global(|store: &mut SettingsStore, cx| {
11063 store.update_user_settings(cx, |settings| {
11064 settings.workspace.close_panel_on_toggle = Some(true);
11065 });
11066 });
11067
11068 // Panel starts closed. Toggling should open and focus it.
11069 workspace.update_in(cx, |workspace, window, cx| {
11070 assert!(!workspace.right_dock().read(cx).is_open());
11071 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11072 });
11073
11074 workspace.update_in(cx, |workspace, window, cx| {
11075 assert!(
11076 workspace.right_dock().read(cx).is_open(),
11077 "Dock should be open after toggling from center"
11078 );
11079 assert!(
11080 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11081 "Panel should be focused after toggling from center"
11082 );
11083 });
11084
11085 // Panel is open and focused. Toggling should close the panel and
11086 // return focus to the center.
11087 workspace.update_in(cx, |workspace, window, cx| {
11088 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11089 });
11090
11091 workspace.update_in(cx, |workspace, window, cx| {
11092 assert!(
11093 !workspace.right_dock().read(cx).is_open(),
11094 "Dock should be closed after toggling from focused panel"
11095 );
11096 assert!(
11097 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11098 "Panel should not be focused after toggling from focused panel"
11099 );
11100 });
11101
11102 // Open the dock and focus something else so the panel is open but not
11103 // focused. Toggling should focus the panel (not close it).
11104 workspace.update_in(cx, |workspace, window, cx| {
11105 workspace
11106 .right_dock()
11107 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11108 window.focus(&pane.read(cx).focus_handle(cx), cx);
11109 });
11110
11111 workspace.update_in(cx, |workspace, window, cx| {
11112 assert!(workspace.right_dock().read(cx).is_open());
11113 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11114 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11115 });
11116
11117 workspace.update_in(cx, |workspace, window, cx| {
11118 assert!(
11119 workspace.right_dock().read(cx).is_open(),
11120 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11121 );
11122 assert!(
11123 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11124 "Panel should be focused after toggling an open-but-unfocused panel"
11125 );
11126 });
11127
11128 // Now disable the setting and verify the original behavior: toggling
11129 // from a focused panel moves focus to center but leaves the dock open.
11130 cx.update_global(|store: &mut SettingsStore, cx| {
11131 store.update_user_settings(cx, |settings| {
11132 settings.workspace.close_panel_on_toggle = Some(false);
11133 });
11134 });
11135
11136 workspace.update_in(cx, |workspace, window, cx| {
11137 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11138 });
11139
11140 workspace.update_in(cx, |workspace, window, cx| {
11141 assert!(
11142 workspace.right_dock().read(cx).is_open(),
11143 "Dock should remain open when setting is disabled"
11144 );
11145 assert!(
11146 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11147 "Panel should not be focused after toggling with setting disabled"
11148 );
11149 });
11150 }
11151
11152 #[gpui::test]
11153 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11154 init_test(cx);
11155 let fs = FakeFs::new(cx.executor());
11156
11157 let project = Project::test(fs, [], cx).await;
11158 let (workspace, cx) =
11159 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11160
11161 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11162 workspace.active_pane().clone()
11163 });
11164
11165 // Add an item to the pane so it can be zoomed
11166 workspace.update_in(cx, |workspace, window, cx| {
11167 let item = cx.new(TestItem::new);
11168 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11169 });
11170
11171 // Initially not zoomed
11172 workspace.update_in(cx, |workspace, _window, cx| {
11173 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11174 assert!(
11175 workspace.zoomed.is_none(),
11176 "Workspace should track no zoomed pane"
11177 );
11178 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11179 });
11180
11181 // Zoom In
11182 pane.update_in(cx, |pane, window, cx| {
11183 pane.zoom_in(&crate::ZoomIn, window, cx);
11184 });
11185
11186 workspace.update_in(cx, |workspace, window, cx| {
11187 assert!(
11188 pane.read(cx).is_zoomed(),
11189 "Pane should be zoomed after ZoomIn"
11190 );
11191 assert!(
11192 workspace.zoomed.is_some(),
11193 "Workspace should track the zoomed pane"
11194 );
11195 assert!(
11196 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11197 "ZoomIn should focus the pane"
11198 );
11199 });
11200
11201 // Zoom In again is a no-op
11202 pane.update_in(cx, |pane, window, cx| {
11203 pane.zoom_in(&crate::ZoomIn, window, cx);
11204 });
11205
11206 workspace.update_in(cx, |workspace, window, cx| {
11207 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11208 assert!(
11209 workspace.zoomed.is_some(),
11210 "Workspace still tracks zoomed pane"
11211 );
11212 assert!(
11213 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11214 "Pane remains focused after repeated ZoomIn"
11215 );
11216 });
11217
11218 // Zoom Out
11219 pane.update_in(cx, |pane, window, cx| {
11220 pane.zoom_out(&crate::ZoomOut, window, cx);
11221 });
11222
11223 workspace.update_in(cx, |workspace, _window, cx| {
11224 assert!(
11225 !pane.read(cx).is_zoomed(),
11226 "Pane should unzoom after ZoomOut"
11227 );
11228 assert!(
11229 workspace.zoomed.is_none(),
11230 "Workspace clears zoom tracking after ZoomOut"
11231 );
11232 });
11233
11234 // Zoom Out again is a no-op
11235 pane.update_in(cx, |pane, window, cx| {
11236 pane.zoom_out(&crate::ZoomOut, window, cx);
11237 });
11238
11239 workspace.update_in(cx, |workspace, _window, cx| {
11240 assert!(
11241 !pane.read(cx).is_zoomed(),
11242 "Second ZoomOut keeps pane unzoomed"
11243 );
11244 assert!(
11245 workspace.zoomed.is_none(),
11246 "Workspace remains without zoomed pane"
11247 );
11248 });
11249 }
11250
11251 #[gpui::test]
11252 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11253 init_test(cx);
11254 let fs = FakeFs::new(cx.executor());
11255
11256 let project = Project::test(fs, [], cx).await;
11257 let (workspace, cx) =
11258 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11259 workspace.update_in(cx, |workspace, window, cx| {
11260 // Open two docks
11261 let left_dock = workspace.dock_at_position(DockPosition::Left);
11262 let right_dock = workspace.dock_at_position(DockPosition::Right);
11263
11264 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11265 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11266
11267 assert!(left_dock.read(cx).is_open());
11268 assert!(right_dock.read(cx).is_open());
11269 });
11270
11271 workspace.update_in(cx, |workspace, window, cx| {
11272 // Toggle all docks - should close both
11273 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11274
11275 let left_dock = workspace.dock_at_position(DockPosition::Left);
11276 let right_dock = workspace.dock_at_position(DockPosition::Right);
11277 assert!(!left_dock.read(cx).is_open());
11278 assert!(!right_dock.read(cx).is_open());
11279 });
11280
11281 workspace.update_in(cx, |workspace, window, cx| {
11282 // Toggle again - should reopen both
11283 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11284
11285 let left_dock = workspace.dock_at_position(DockPosition::Left);
11286 let right_dock = workspace.dock_at_position(DockPosition::Right);
11287 assert!(left_dock.read(cx).is_open());
11288 assert!(right_dock.read(cx).is_open());
11289 });
11290 }
11291
11292 #[gpui::test]
11293 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11294 init_test(cx);
11295 let fs = FakeFs::new(cx.executor());
11296
11297 let project = Project::test(fs, [], cx).await;
11298 let (workspace, cx) =
11299 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11300 workspace.update_in(cx, |workspace, window, cx| {
11301 // Open two docks
11302 let left_dock = workspace.dock_at_position(DockPosition::Left);
11303 let right_dock = workspace.dock_at_position(DockPosition::Right);
11304
11305 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11306 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11307
11308 assert!(left_dock.read(cx).is_open());
11309 assert!(right_dock.read(cx).is_open());
11310 });
11311
11312 workspace.update_in(cx, |workspace, window, cx| {
11313 // Close them manually
11314 workspace.toggle_dock(DockPosition::Left, window, cx);
11315 workspace.toggle_dock(DockPosition::Right, window, cx);
11316
11317 let left_dock = workspace.dock_at_position(DockPosition::Left);
11318 let right_dock = workspace.dock_at_position(DockPosition::Right);
11319 assert!(!left_dock.read(cx).is_open());
11320 assert!(!right_dock.read(cx).is_open());
11321 });
11322
11323 workspace.update_in(cx, |workspace, window, cx| {
11324 // Toggle all docks - only last closed (right dock) should reopen
11325 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11326
11327 let left_dock = workspace.dock_at_position(DockPosition::Left);
11328 let right_dock = workspace.dock_at_position(DockPosition::Right);
11329 assert!(!left_dock.read(cx).is_open());
11330 assert!(right_dock.read(cx).is_open());
11331 });
11332 }
11333
11334 #[gpui::test]
11335 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11336 init_test(cx);
11337 let fs = FakeFs::new(cx.executor());
11338 let project = Project::test(fs, [], cx).await;
11339 let (multi_workspace, cx) =
11340 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11341 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11342
11343 // Open two docks (left and right) with one panel each
11344 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11345 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11346 workspace.add_panel(left_panel.clone(), window, cx);
11347
11348 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11349 workspace.add_panel(right_panel.clone(), window, cx);
11350
11351 workspace.toggle_dock(DockPosition::Left, window, cx);
11352 workspace.toggle_dock(DockPosition::Right, window, cx);
11353
11354 // Verify initial state
11355 assert!(
11356 workspace.left_dock().read(cx).is_open(),
11357 "Left dock should be open"
11358 );
11359 assert_eq!(
11360 workspace
11361 .left_dock()
11362 .read(cx)
11363 .visible_panel()
11364 .unwrap()
11365 .panel_id(),
11366 left_panel.panel_id(),
11367 "Left panel should be visible in left dock"
11368 );
11369 assert!(
11370 workspace.right_dock().read(cx).is_open(),
11371 "Right dock should be open"
11372 );
11373 assert_eq!(
11374 workspace
11375 .right_dock()
11376 .read(cx)
11377 .visible_panel()
11378 .unwrap()
11379 .panel_id(),
11380 right_panel.panel_id(),
11381 "Right panel should be visible in right dock"
11382 );
11383 assert!(
11384 !workspace.bottom_dock().read(cx).is_open(),
11385 "Bottom dock should be closed"
11386 );
11387
11388 (left_panel, right_panel)
11389 });
11390
11391 // Focus the left panel and move it to the next position (bottom dock)
11392 workspace.update_in(cx, |workspace, window, cx| {
11393 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11394 assert!(
11395 left_panel.read(cx).focus_handle(cx).is_focused(window),
11396 "Left panel should be focused"
11397 );
11398 });
11399
11400 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11401
11402 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11403 workspace.update(cx, |workspace, cx| {
11404 assert!(
11405 !workspace.left_dock().read(cx).is_open(),
11406 "Left dock should be closed"
11407 );
11408 assert!(
11409 workspace.bottom_dock().read(cx).is_open(),
11410 "Bottom dock should now be open"
11411 );
11412 assert_eq!(
11413 left_panel.read(cx).position,
11414 DockPosition::Bottom,
11415 "Left panel should now be in the bottom dock"
11416 );
11417 assert_eq!(
11418 workspace
11419 .bottom_dock()
11420 .read(cx)
11421 .visible_panel()
11422 .unwrap()
11423 .panel_id(),
11424 left_panel.panel_id(),
11425 "Left panel should be the visible panel in the bottom dock"
11426 );
11427 });
11428
11429 // Toggle all docks off
11430 workspace.update_in(cx, |workspace, window, cx| {
11431 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11432 assert!(
11433 !workspace.left_dock().read(cx).is_open(),
11434 "Left dock should be closed"
11435 );
11436 assert!(
11437 !workspace.right_dock().read(cx).is_open(),
11438 "Right dock should be closed"
11439 );
11440 assert!(
11441 !workspace.bottom_dock().read(cx).is_open(),
11442 "Bottom dock should be closed"
11443 );
11444 });
11445
11446 // Toggle all docks back on and verify positions are restored
11447 workspace.update_in(cx, |workspace, window, cx| {
11448 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11449 assert!(
11450 !workspace.left_dock().read(cx).is_open(),
11451 "Left dock should remain closed"
11452 );
11453 assert!(
11454 workspace.right_dock().read(cx).is_open(),
11455 "Right dock should remain open"
11456 );
11457 assert!(
11458 workspace.bottom_dock().read(cx).is_open(),
11459 "Bottom dock should remain open"
11460 );
11461 assert_eq!(
11462 left_panel.read(cx).position,
11463 DockPosition::Bottom,
11464 "Left panel should remain in the bottom dock"
11465 );
11466 assert_eq!(
11467 right_panel.read(cx).position,
11468 DockPosition::Right,
11469 "Right panel should remain in the right dock"
11470 );
11471 assert_eq!(
11472 workspace
11473 .bottom_dock()
11474 .read(cx)
11475 .visible_panel()
11476 .unwrap()
11477 .panel_id(),
11478 left_panel.panel_id(),
11479 "Left panel should be the visible panel in the right dock"
11480 );
11481 });
11482 }
11483
11484 #[gpui::test]
11485 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11486 init_test(cx);
11487
11488 let fs = FakeFs::new(cx.executor());
11489
11490 let project = Project::test(fs, None, cx).await;
11491 let (workspace, cx) =
11492 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11493
11494 // Let's arrange the panes like this:
11495 //
11496 // +-----------------------+
11497 // | top |
11498 // +------+--------+-------+
11499 // | left | center | right |
11500 // +------+--------+-------+
11501 // | bottom |
11502 // +-----------------------+
11503
11504 let top_item = cx.new(|cx| {
11505 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11506 });
11507 let bottom_item = cx.new(|cx| {
11508 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11509 });
11510 let left_item = cx.new(|cx| {
11511 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11512 });
11513 let right_item = cx.new(|cx| {
11514 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11515 });
11516 let center_item = cx.new(|cx| {
11517 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11518 });
11519
11520 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11521 let top_pane_id = workspace.active_pane().entity_id();
11522 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11523 workspace.split_pane(
11524 workspace.active_pane().clone(),
11525 SplitDirection::Down,
11526 window,
11527 cx,
11528 );
11529 top_pane_id
11530 });
11531 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11532 let bottom_pane_id = workspace.active_pane().entity_id();
11533 workspace.add_item_to_active_pane(
11534 Box::new(bottom_item.clone()),
11535 None,
11536 false,
11537 window,
11538 cx,
11539 );
11540 workspace.split_pane(
11541 workspace.active_pane().clone(),
11542 SplitDirection::Up,
11543 window,
11544 cx,
11545 );
11546 bottom_pane_id
11547 });
11548 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11549 let left_pane_id = workspace.active_pane().entity_id();
11550 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11551 workspace.split_pane(
11552 workspace.active_pane().clone(),
11553 SplitDirection::Right,
11554 window,
11555 cx,
11556 );
11557 left_pane_id
11558 });
11559 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11560 let right_pane_id = workspace.active_pane().entity_id();
11561 workspace.add_item_to_active_pane(
11562 Box::new(right_item.clone()),
11563 None,
11564 false,
11565 window,
11566 cx,
11567 );
11568 workspace.split_pane(
11569 workspace.active_pane().clone(),
11570 SplitDirection::Left,
11571 window,
11572 cx,
11573 );
11574 right_pane_id
11575 });
11576 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11577 let center_pane_id = workspace.active_pane().entity_id();
11578 workspace.add_item_to_active_pane(
11579 Box::new(center_item.clone()),
11580 None,
11581 false,
11582 window,
11583 cx,
11584 );
11585 center_pane_id
11586 });
11587 cx.executor().run_until_parked();
11588
11589 workspace.update_in(cx, |workspace, window, cx| {
11590 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11591
11592 // Join into next from center pane into right
11593 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11594 });
11595
11596 workspace.update_in(cx, |workspace, window, cx| {
11597 let active_pane = workspace.active_pane();
11598 assert_eq!(right_pane_id, active_pane.entity_id());
11599 assert_eq!(2, active_pane.read(cx).items_len());
11600 let item_ids_in_pane =
11601 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11602 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11603 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11604
11605 // Join into next from right pane into bottom
11606 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11607 });
11608
11609 workspace.update_in(cx, |workspace, window, cx| {
11610 let active_pane = workspace.active_pane();
11611 assert_eq!(bottom_pane_id, active_pane.entity_id());
11612 assert_eq!(3, active_pane.read(cx).items_len());
11613 let item_ids_in_pane =
11614 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11615 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11616 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11617 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11618
11619 // Join into next from bottom pane into left
11620 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11621 });
11622
11623 workspace.update_in(cx, |workspace, window, cx| {
11624 let active_pane = workspace.active_pane();
11625 assert_eq!(left_pane_id, active_pane.entity_id());
11626 assert_eq!(4, active_pane.read(cx).items_len());
11627 let item_ids_in_pane =
11628 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11629 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11630 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11631 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11632 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11633
11634 // Join into next from left pane into top
11635 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11636 });
11637
11638 workspace.update_in(cx, |workspace, window, cx| {
11639 let active_pane = workspace.active_pane();
11640 assert_eq!(top_pane_id, active_pane.entity_id());
11641 assert_eq!(5, active_pane.read(cx).items_len());
11642 let item_ids_in_pane =
11643 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11644 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11645 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11646 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11647 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11648 assert!(item_ids_in_pane.contains(&top_item.item_id()));
11649
11650 // Single pane left: no-op
11651 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11652 });
11653
11654 workspace.update(cx, |workspace, _cx| {
11655 let active_pane = workspace.active_pane();
11656 assert_eq!(top_pane_id, active_pane.entity_id());
11657 });
11658 }
11659
11660 fn add_an_item_to_active_pane(
11661 cx: &mut VisualTestContext,
11662 workspace: &Entity<Workspace>,
11663 item_id: u64,
11664 ) -> Entity<TestItem> {
11665 let item = cx.new(|cx| {
11666 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11667 item_id,
11668 "item{item_id}.txt",
11669 cx,
11670 )])
11671 });
11672 workspace.update_in(cx, |workspace, window, cx| {
11673 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11674 });
11675 item
11676 }
11677
11678 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11679 workspace.update_in(cx, |workspace, window, cx| {
11680 workspace.split_pane(
11681 workspace.active_pane().clone(),
11682 SplitDirection::Right,
11683 window,
11684 cx,
11685 )
11686 })
11687 }
11688
11689 #[gpui::test]
11690 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11691 init_test(cx);
11692 let fs = FakeFs::new(cx.executor());
11693 let project = Project::test(fs, None, cx).await;
11694 let (workspace, cx) =
11695 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11696
11697 add_an_item_to_active_pane(cx, &workspace, 1);
11698 split_pane(cx, &workspace);
11699 add_an_item_to_active_pane(cx, &workspace, 2);
11700 split_pane(cx, &workspace); // empty pane
11701 split_pane(cx, &workspace);
11702 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11703
11704 cx.executor().run_until_parked();
11705
11706 workspace.update(cx, |workspace, cx| {
11707 let num_panes = workspace.panes().len();
11708 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11709 let active_item = workspace
11710 .active_pane()
11711 .read(cx)
11712 .active_item()
11713 .expect("item is in focus");
11714
11715 assert_eq!(num_panes, 4);
11716 assert_eq!(num_items_in_current_pane, 1);
11717 assert_eq!(active_item.item_id(), last_item.item_id());
11718 });
11719
11720 workspace.update_in(cx, |workspace, window, cx| {
11721 workspace.join_all_panes(window, cx);
11722 });
11723
11724 workspace.update(cx, |workspace, cx| {
11725 let num_panes = workspace.panes().len();
11726 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11727 let active_item = workspace
11728 .active_pane()
11729 .read(cx)
11730 .active_item()
11731 .expect("item is in focus");
11732
11733 assert_eq!(num_panes, 1);
11734 assert_eq!(num_items_in_current_pane, 3);
11735 assert_eq!(active_item.item_id(), last_item.item_id());
11736 });
11737 }
11738 struct TestModal(FocusHandle);
11739
11740 impl TestModal {
11741 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11742 Self(cx.focus_handle())
11743 }
11744 }
11745
11746 impl EventEmitter<DismissEvent> for TestModal {}
11747
11748 impl Focusable for TestModal {
11749 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11750 self.0.clone()
11751 }
11752 }
11753
11754 impl ModalView for TestModal {}
11755
11756 impl Render for TestModal {
11757 fn render(
11758 &mut self,
11759 _window: &mut Window,
11760 _cx: &mut Context<TestModal>,
11761 ) -> impl IntoElement {
11762 div().track_focus(&self.0)
11763 }
11764 }
11765
11766 #[gpui::test]
11767 async fn test_panels(cx: &mut gpui::TestAppContext) {
11768 init_test(cx);
11769 let fs = FakeFs::new(cx.executor());
11770
11771 let project = Project::test(fs, [], cx).await;
11772 let (multi_workspace, cx) =
11773 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11774 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11775
11776 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11777 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11778 workspace.add_panel(panel_1.clone(), window, cx);
11779 workspace.toggle_dock(DockPosition::Left, window, cx);
11780 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11781 workspace.add_panel(panel_2.clone(), window, cx);
11782 workspace.toggle_dock(DockPosition::Right, window, cx);
11783
11784 let left_dock = workspace.left_dock();
11785 assert_eq!(
11786 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11787 panel_1.panel_id()
11788 );
11789 assert_eq!(
11790 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11791 panel_1.size(window, cx)
11792 );
11793
11794 left_dock.update(cx, |left_dock, cx| {
11795 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11796 });
11797 assert_eq!(
11798 workspace
11799 .right_dock()
11800 .read(cx)
11801 .visible_panel()
11802 .unwrap()
11803 .panel_id(),
11804 panel_2.panel_id(),
11805 );
11806
11807 (panel_1, panel_2)
11808 });
11809
11810 // Move panel_1 to the right
11811 panel_1.update_in(cx, |panel_1, window, cx| {
11812 panel_1.set_position(DockPosition::Right, window, cx)
11813 });
11814
11815 workspace.update_in(cx, |workspace, window, cx| {
11816 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11817 // Since it was the only panel on the left, the left dock should now be closed.
11818 assert!(!workspace.left_dock().read(cx).is_open());
11819 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11820 let right_dock = workspace.right_dock();
11821 assert_eq!(
11822 right_dock.read(cx).visible_panel().unwrap().panel_id(),
11823 panel_1.panel_id()
11824 );
11825 assert_eq!(
11826 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11827 px(1337.)
11828 );
11829
11830 // Now we move panel_2 to the left
11831 panel_2.set_position(DockPosition::Left, window, cx);
11832 });
11833
11834 workspace.update(cx, |workspace, cx| {
11835 // Since panel_2 was not visible on the right, we don't open the left dock.
11836 assert!(!workspace.left_dock().read(cx).is_open());
11837 // And the right dock is unaffected in its displaying of panel_1
11838 assert!(workspace.right_dock().read(cx).is_open());
11839 assert_eq!(
11840 workspace
11841 .right_dock()
11842 .read(cx)
11843 .visible_panel()
11844 .unwrap()
11845 .panel_id(),
11846 panel_1.panel_id(),
11847 );
11848 });
11849
11850 // Move panel_1 back to the left
11851 panel_1.update_in(cx, |panel_1, window, cx| {
11852 panel_1.set_position(DockPosition::Left, window, cx)
11853 });
11854
11855 workspace.update_in(cx, |workspace, window, cx| {
11856 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11857 let left_dock = workspace.left_dock();
11858 assert!(left_dock.read(cx).is_open());
11859 assert_eq!(
11860 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11861 panel_1.panel_id()
11862 );
11863 assert_eq!(
11864 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11865 px(1337.)
11866 );
11867 // And the right dock should be closed as it no longer has any panels.
11868 assert!(!workspace.right_dock().read(cx).is_open());
11869
11870 // Now we move panel_1 to the bottom
11871 panel_1.set_position(DockPosition::Bottom, window, cx);
11872 });
11873
11874 workspace.update_in(cx, |workspace, window, cx| {
11875 // Since panel_1 was visible on the left, we close the left dock.
11876 assert!(!workspace.left_dock().read(cx).is_open());
11877 // The bottom dock is sized based on the panel's default size,
11878 // since the panel orientation changed from vertical to horizontal.
11879 let bottom_dock = workspace.bottom_dock();
11880 assert_eq!(
11881 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
11882 panel_1.size(window, cx),
11883 );
11884 // Close bottom dock and move panel_1 back to the left.
11885 bottom_dock.update(cx, |bottom_dock, cx| {
11886 bottom_dock.set_open(false, window, cx)
11887 });
11888 panel_1.set_position(DockPosition::Left, window, cx);
11889 });
11890
11891 // Emit activated event on panel 1
11892 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
11893
11894 // Now the left dock is open and panel_1 is active and focused.
11895 workspace.update_in(cx, |workspace, window, cx| {
11896 let left_dock = workspace.left_dock();
11897 assert!(left_dock.read(cx).is_open());
11898 assert_eq!(
11899 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11900 panel_1.panel_id(),
11901 );
11902 assert!(panel_1.focus_handle(cx).is_focused(window));
11903 });
11904
11905 // Emit closed event on panel 2, which is not active
11906 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11907
11908 // Wo don't close the left dock, because panel_2 wasn't the active panel
11909 workspace.update(cx, |workspace, cx| {
11910 let left_dock = workspace.left_dock();
11911 assert!(left_dock.read(cx).is_open());
11912 assert_eq!(
11913 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11914 panel_1.panel_id(),
11915 );
11916 });
11917
11918 // Emitting a ZoomIn event shows the panel as zoomed.
11919 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
11920 workspace.read_with(cx, |workspace, _| {
11921 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11922 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
11923 });
11924
11925 // Move panel to another dock while it is zoomed
11926 panel_1.update_in(cx, |panel, window, cx| {
11927 panel.set_position(DockPosition::Right, window, cx)
11928 });
11929 workspace.read_with(cx, |workspace, _| {
11930 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11931
11932 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11933 });
11934
11935 // This is a helper for getting a:
11936 // - valid focus on an element,
11937 // - that isn't a part of the panes and panels system of the Workspace,
11938 // - and doesn't trigger the 'on_focus_lost' API.
11939 let focus_other_view = {
11940 let workspace = workspace.clone();
11941 move |cx: &mut VisualTestContext| {
11942 workspace.update_in(cx, |workspace, window, cx| {
11943 if workspace.active_modal::<TestModal>(cx).is_some() {
11944 workspace.toggle_modal(window, cx, TestModal::new);
11945 workspace.toggle_modal(window, cx, TestModal::new);
11946 } else {
11947 workspace.toggle_modal(window, cx, TestModal::new);
11948 }
11949 })
11950 }
11951 };
11952
11953 // If focus is transferred to another view that's not a panel or another pane, we still show
11954 // the panel as zoomed.
11955 focus_other_view(cx);
11956 workspace.read_with(cx, |workspace, _| {
11957 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11958 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11959 });
11960
11961 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
11962 workspace.update_in(cx, |_workspace, window, cx| {
11963 cx.focus_self(window);
11964 });
11965 workspace.read_with(cx, |workspace, _| {
11966 assert_eq!(workspace.zoomed, None);
11967 assert_eq!(workspace.zoomed_position, None);
11968 });
11969
11970 // If focus is transferred again to another view that's not a panel or a pane, we won't
11971 // show the panel as zoomed because it wasn't zoomed before.
11972 focus_other_view(cx);
11973 workspace.read_with(cx, |workspace, _| {
11974 assert_eq!(workspace.zoomed, None);
11975 assert_eq!(workspace.zoomed_position, None);
11976 });
11977
11978 // When the panel is activated, it is zoomed again.
11979 cx.dispatch_action(ToggleRightDock);
11980 workspace.read_with(cx, |workspace, _| {
11981 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11982 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11983 });
11984
11985 // Emitting a ZoomOut event unzooms the panel.
11986 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
11987 workspace.read_with(cx, |workspace, _| {
11988 assert_eq!(workspace.zoomed, None);
11989 assert_eq!(workspace.zoomed_position, None);
11990 });
11991
11992 // Emit closed event on panel 1, which is active
11993 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11994
11995 // Now the left dock is closed, because panel_1 was the active panel
11996 workspace.update(cx, |workspace, cx| {
11997 let right_dock = workspace.right_dock();
11998 assert!(!right_dock.read(cx).is_open());
11999 });
12000 }
12001
12002 #[gpui::test]
12003 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12004 init_test(cx);
12005
12006 let fs = FakeFs::new(cx.background_executor.clone());
12007 let project = Project::test(fs, [], cx).await;
12008 let (workspace, cx) =
12009 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12010 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12011
12012 let dirty_regular_buffer = cx.new(|cx| {
12013 TestItem::new(cx)
12014 .with_dirty(true)
12015 .with_label("1.txt")
12016 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12017 });
12018 let dirty_regular_buffer_2 = cx.new(|cx| {
12019 TestItem::new(cx)
12020 .with_dirty(true)
12021 .with_label("2.txt")
12022 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12023 });
12024 let dirty_multi_buffer_with_both = cx.new(|cx| {
12025 TestItem::new(cx)
12026 .with_dirty(true)
12027 .with_buffer_kind(ItemBufferKind::Multibuffer)
12028 .with_label("Fake Project Search")
12029 .with_project_items(&[
12030 dirty_regular_buffer.read(cx).project_items[0].clone(),
12031 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12032 ])
12033 });
12034 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12035 workspace.update_in(cx, |workspace, window, cx| {
12036 workspace.add_item(
12037 pane.clone(),
12038 Box::new(dirty_regular_buffer.clone()),
12039 None,
12040 false,
12041 false,
12042 window,
12043 cx,
12044 );
12045 workspace.add_item(
12046 pane.clone(),
12047 Box::new(dirty_regular_buffer_2.clone()),
12048 None,
12049 false,
12050 false,
12051 window,
12052 cx,
12053 );
12054 workspace.add_item(
12055 pane.clone(),
12056 Box::new(dirty_multi_buffer_with_both.clone()),
12057 None,
12058 false,
12059 false,
12060 window,
12061 cx,
12062 );
12063 });
12064
12065 pane.update_in(cx, |pane, window, cx| {
12066 pane.activate_item(2, true, true, window, cx);
12067 assert_eq!(
12068 pane.active_item().unwrap().item_id(),
12069 multi_buffer_with_both_files_id,
12070 "Should select the multi buffer in the pane"
12071 );
12072 });
12073 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12074 pane.close_other_items(
12075 &CloseOtherItems {
12076 save_intent: Some(SaveIntent::Save),
12077 close_pinned: true,
12078 },
12079 None,
12080 window,
12081 cx,
12082 )
12083 });
12084 cx.background_executor.run_until_parked();
12085 assert!(!cx.has_pending_prompt());
12086 close_all_but_multi_buffer_task
12087 .await
12088 .expect("Closing all buffers but the multi buffer failed");
12089 pane.update(cx, |pane, cx| {
12090 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12091 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12092 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12093 assert_eq!(pane.items_len(), 1);
12094 assert_eq!(
12095 pane.active_item().unwrap().item_id(),
12096 multi_buffer_with_both_files_id,
12097 "Should have only the multi buffer left in the pane"
12098 );
12099 assert!(
12100 dirty_multi_buffer_with_both.read(cx).is_dirty,
12101 "The multi buffer containing the unsaved buffer should still be dirty"
12102 );
12103 });
12104
12105 dirty_regular_buffer.update(cx, |buffer, cx| {
12106 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12107 });
12108
12109 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12110 pane.close_active_item(
12111 &CloseActiveItem {
12112 save_intent: Some(SaveIntent::Close),
12113 close_pinned: false,
12114 },
12115 window,
12116 cx,
12117 )
12118 });
12119 cx.background_executor.run_until_parked();
12120 assert!(
12121 cx.has_pending_prompt(),
12122 "Dirty multi buffer should prompt a save dialog"
12123 );
12124 cx.simulate_prompt_answer("Save");
12125 cx.background_executor.run_until_parked();
12126 close_multi_buffer_task
12127 .await
12128 .expect("Closing the multi buffer failed");
12129 pane.update(cx, |pane, cx| {
12130 assert_eq!(
12131 dirty_multi_buffer_with_both.read(cx).save_count,
12132 1,
12133 "Multi buffer item should get be saved"
12134 );
12135 // Test impl does not save inner items, so we do not assert them
12136 assert_eq!(
12137 pane.items_len(),
12138 0,
12139 "No more items should be left in the pane"
12140 );
12141 assert!(pane.active_item().is_none());
12142 });
12143 }
12144
12145 #[gpui::test]
12146 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
12147 cx: &mut TestAppContext,
12148 ) {
12149 init_test(cx);
12150
12151 let fs = FakeFs::new(cx.background_executor.clone());
12152 let project = Project::test(fs, [], cx).await;
12153 let (workspace, cx) =
12154 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12155 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12156
12157 let dirty_regular_buffer = cx.new(|cx| {
12158 TestItem::new(cx)
12159 .with_dirty(true)
12160 .with_label("1.txt")
12161 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12162 });
12163 let dirty_regular_buffer_2 = cx.new(|cx| {
12164 TestItem::new(cx)
12165 .with_dirty(true)
12166 .with_label("2.txt")
12167 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12168 });
12169 let clear_regular_buffer = cx.new(|cx| {
12170 TestItem::new(cx)
12171 .with_label("3.txt")
12172 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12173 });
12174
12175 let dirty_multi_buffer_with_both = cx.new(|cx| {
12176 TestItem::new(cx)
12177 .with_dirty(true)
12178 .with_buffer_kind(ItemBufferKind::Multibuffer)
12179 .with_label("Fake Project Search")
12180 .with_project_items(&[
12181 dirty_regular_buffer.read(cx).project_items[0].clone(),
12182 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12183 clear_regular_buffer.read(cx).project_items[0].clone(),
12184 ])
12185 });
12186 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12187 workspace.update_in(cx, |workspace, window, cx| {
12188 workspace.add_item(
12189 pane.clone(),
12190 Box::new(dirty_regular_buffer.clone()),
12191 None,
12192 false,
12193 false,
12194 window,
12195 cx,
12196 );
12197 workspace.add_item(
12198 pane.clone(),
12199 Box::new(dirty_multi_buffer_with_both.clone()),
12200 None,
12201 false,
12202 false,
12203 window,
12204 cx,
12205 );
12206 });
12207
12208 pane.update_in(cx, |pane, window, cx| {
12209 pane.activate_item(1, true, true, window, cx);
12210 assert_eq!(
12211 pane.active_item().unwrap().item_id(),
12212 multi_buffer_with_both_files_id,
12213 "Should select the multi buffer in the pane"
12214 );
12215 });
12216 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12217 pane.close_active_item(
12218 &CloseActiveItem {
12219 save_intent: None,
12220 close_pinned: false,
12221 },
12222 window,
12223 cx,
12224 )
12225 });
12226 cx.background_executor.run_until_parked();
12227 assert!(
12228 cx.has_pending_prompt(),
12229 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
12230 );
12231 }
12232
12233 /// Tests that when `close_on_file_delete` is enabled, files are automatically
12234 /// closed when they are deleted from disk.
12235 #[gpui::test]
12236 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
12237 init_test(cx);
12238
12239 // Enable the close_on_disk_deletion setting
12240 cx.update_global(|store: &mut SettingsStore, cx| {
12241 store.update_user_settings(cx, |settings| {
12242 settings.workspace.close_on_file_delete = Some(true);
12243 });
12244 });
12245
12246 let fs = FakeFs::new(cx.background_executor.clone());
12247 let project = Project::test(fs, [], cx).await;
12248 let (workspace, cx) =
12249 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12250 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12251
12252 // Create a test item that simulates a file
12253 let item = cx.new(|cx| {
12254 TestItem::new(cx)
12255 .with_label("test.txt")
12256 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12257 });
12258
12259 // Add item to workspace
12260 workspace.update_in(cx, |workspace, window, cx| {
12261 workspace.add_item(
12262 pane.clone(),
12263 Box::new(item.clone()),
12264 None,
12265 false,
12266 false,
12267 window,
12268 cx,
12269 );
12270 });
12271
12272 // Verify the item is in the pane
12273 pane.read_with(cx, |pane, _| {
12274 assert_eq!(pane.items().count(), 1);
12275 });
12276
12277 // Simulate file deletion by setting the item's deleted state
12278 item.update(cx, |item, _| {
12279 item.set_has_deleted_file(true);
12280 });
12281
12282 // Emit UpdateTab event to trigger the close behavior
12283 cx.run_until_parked();
12284 item.update(cx, |_, cx| {
12285 cx.emit(ItemEvent::UpdateTab);
12286 });
12287
12288 // Allow the close operation to complete
12289 cx.run_until_parked();
12290
12291 // Verify the item was automatically closed
12292 pane.read_with(cx, |pane, _| {
12293 assert_eq!(
12294 pane.items().count(),
12295 0,
12296 "Item should be automatically closed when file is deleted"
12297 );
12298 });
12299 }
12300
12301 /// Tests that when `close_on_file_delete` is disabled (default), files remain
12302 /// open with a strikethrough when they are deleted from disk.
12303 #[gpui::test]
12304 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12305 init_test(cx);
12306
12307 // Ensure close_on_disk_deletion is disabled (default)
12308 cx.update_global(|store: &mut SettingsStore, cx| {
12309 store.update_user_settings(cx, |settings| {
12310 settings.workspace.close_on_file_delete = Some(false);
12311 });
12312 });
12313
12314 let fs = FakeFs::new(cx.background_executor.clone());
12315 let project = Project::test(fs, [], cx).await;
12316 let (workspace, cx) =
12317 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12318 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12319
12320 // Create a test item that simulates a file
12321 let item = cx.new(|cx| {
12322 TestItem::new(cx)
12323 .with_label("test.txt")
12324 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12325 });
12326
12327 // Add item to workspace
12328 workspace.update_in(cx, |workspace, window, cx| {
12329 workspace.add_item(
12330 pane.clone(),
12331 Box::new(item.clone()),
12332 None,
12333 false,
12334 false,
12335 window,
12336 cx,
12337 );
12338 });
12339
12340 // Verify the item is in the pane
12341 pane.read_with(cx, |pane, _| {
12342 assert_eq!(pane.items().count(), 1);
12343 });
12344
12345 // Simulate file deletion
12346 item.update(cx, |item, _| {
12347 item.set_has_deleted_file(true);
12348 });
12349
12350 // Emit UpdateTab event
12351 cx.run_until_parked();
12352 item.update(cx, |_, cx| {
12353 cx.emit(ItemEvent::UpdateTab);
12354 });
12355
12356 // Allow any potential close operation to complete
12357 cx.run_until_parked();
12358
12359 // Verify the item remains open (with strikethrough)
12360 pane.read_with(cx, |pane, _| {
12361 assert_eq!(
12362 pane.items().count(),
12363 1,
12364 "Item should remain open when close_on_disk_deletion is disabled"
12365 );
12366 });
12367
12368 // Verify the item shows as deleted
12369 item.read_with(cx, |item, _| {
12370 assert!(
12371 item.has_deleted_file,
12372 "Item should be marked as having deleted file"
12373 );
12374 });
12375 }
12376
12377 /// Tests that dirty files are not automatically closed when deleted from disk,
12378 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12379 /// unsaved changes without being prompted.
12380 #[gpui::test]
12381 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12382 init_test(cx);
12383
12384 // Enable the close_on_file_delete setting
12385 cx.update_global(|store: &mut SettingsStore, cx| {
12386 store.update_user_settings(cx, |settings| {
12387 settings.workspace.close_on_file_delete = Some(true);
12388 });
12389 });
12390
12391 let fs = FakeFs::new(cx.background_executor.clone());
12392 let project = Project::test(fs, [], cx).await;
12393 let (workspace, cx) =
12394 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12395 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12396
12397 // Create a dirty test item
12398 let item = cx.new(|cx| {
12399 TestItem::new(cx)
12400 .with_dirty(true)
12401 .with_label("test.txt")
12402 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12403 });
12404
12405 // Add item to workspace
12406 workspace.update_in(cx, |workspace, window, cx| {
12407 workspace.add_item(
12408 pane.clone(),
12409 Box::new(item.clone()),
12410 None,
12411 false,
12412 false,
12413 window,
12414 cx,
12415 );
12416 });
12417
12418 // Simulate file deletion
12419 item.update(cx, |item, _| {
12420 item.set_has_deleted_file(true);
12421 });
12422
12423 // Emit UpdateTab event to trigger the close behavior
12424 cx.run_until_parked();
12425 item.update(cx, |_, cx| {
12426 cx.emit(ItemEvent::UpdateTab);
12427 });
12428
12429 // Allow any potential close operation to complete
12430 cx.run_until_parked();
12431
12432 // Verify the item remains open (dirty files are not auto-closed)
12433 pane.read_with(cx, |pane, _| {
12434 assert_eq!(
12435 pane.items().count(),
12436 1,
12437 "Dirty items should not be automatically closed even when file is deleted"
12438 );
12439 });
12440
12441 // Verify the item is marked as deleted and still dirty
12442 item.read_with(cx, |item, _| {
12443 assert!(
12444 item.has_deleted_file,
12445 "Item should be marked as having deleted file"
12446 );
12447 assert!(item.is_dirty, "Item should still be dirty");
12448 });
12449 }
12450
12451 /// Tests that navigation history is cleaned up when files are auto-closed
12452 /// due to deletion from disk.
12453 #[gpui::test]
12454 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12455 init_test(cx);
12456
12457 // Enable the close_on_file_delete setting
12458 cx.update_global(|store: &mut SettingsStore, cx| {
12459 store.update_user_settings(cx, |settings| {
12460 settings.workspace.close_on_file_delete = Some(true);
12461 });
12462 });
12463
12464 let fs = FakeFs::new(cx.background_executor.clone());
12465 let project = Project::test(fs, [], cx).await;
12466 let (workspace, cx) =
12467 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12468 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12469
12470 // Create test items
12471 let item1 = cx.new(|cx| {
12472 TestItem::new(cx)
12473 .with_label("test1.txt")
12474 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12475 });
12476 let item1_id = item1.item_id();
12477
12478 let item2 = cx.new(|cx| {
12479 TestItem::new(cx)
12480 .with_label("test2.txt")
12481 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12482 });
12483
12484 // Add items to workspace
12485 workspace.update_in(cx, |workspace, window, cx| {
12486 workspace.add_item(
12487 pane.clone(),
12488 Box::new(item1.clone()),
12489 None,
12490 false,
12491 false,
12492 window,
12493 cx,
12494 );
12495 workspace.add_item(
12496 pane.clone(),
12497 Box::new(item2.clone()),
12498 None,
12499 false,
12500 false,
12501 window,
12502 cx,
12503 );
12504 });
12505
12506 // Activate item1 to ensure it gets navigation entries
12507 pane.update_in(cx, |pane, window, cx| {
12508 pane.activate_item(0, true, true, window, cx);
12509 });
12510
12511 // Switch to item2 and back to create navigation history
12512 pane.update_in(cx, |pane, window, cx| {
12513 pane.activate_item(1, true, true, window, cx);
12514 });
12515 cx.run_until_parked();
12516
12517 pane.update_in(cx, |pane, window, cx| {
12518 pane.activate_item(0, true, true, window, cx);
12519 });
12520 cx.run_until_parked();
12521
12522 // Simulate file deletion for item1
12523 item1.update(cx, |item, _| {
12524 item.set_has_deleted_file(true);
12525 });
12526
12527 // Emit UpdateTab event to trigger the close behavior
12528 item1.update(cx, |_, cx| {
12529 cx.emit(ItemEvent::UpdateTab);
12530 });
12531 cx.run_until_parked();
12532
12533 // Verify item1 was closed
12534 pane.read_with(cx, |pane, _| {
12535 assert_eq!(
12536 pane.items().count(),
12537 1,
12538 "Should have 1 item remaining after auto-close"
12539 );
12540 });
12541
12542 // Check navigation history after close
12543 let has_item = pane.read_with(cx, |pane, cx| {
12544 let mut has_item = false;
12545 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12546 if entry.item.id() == item1_id {
12547 has_item = true;
12548 }
12549 });
12550 has_item
12551 });
12552
12553 assert!(
12554 !has_item,
12555 "Navigation history should not contain closed item entries"
12556 );
12557 }
12558
12559 #[gpui::test]
12560 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12561 cx: &mut TestAppContext,
12562 ) {
12563 init_test(cx);
12564
12565 let fs = FakeFs::new(cx.background_executor.clone());
12566 let project = Project::test(fs, [], cx).await;
12567 let (workspace, cx) =
12568 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12569 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12570
12571 let dirty_regular_buffer = cx.new(|cx| {
12572 TestItem::new(cx)
12573 .with_dirty(true)
12574 .with_label("1.txt")
12575 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12576 });
12577 let dirty_regular_buffer_2 = cx.new(|cx| {
12578 TestItem::new(cx)
12579 .with_dirty(true)
12580 .with_label("2.txt")
12581 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12582 });
12583 let clear_regular_buffer = cx.new(|cx| {
12584 TestItem::new(cx)
12585 .with_label("3.txt")
12586 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12587 });
12588
12589 let dirty_multi_buffer = cx.new(|cx| {
12590 TestItem::new(cx)
12591 .with_dirty(true)
12592 .with_buffer_kind(ItemBufferKind::Multibuffer)
12593 .with_label("Fake Project Search")
12594 .with_project_items(&[
12595 dirty_regular_buffer.read(cx).project_items[0].clone(),
12596 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12597 clear_regular_buffer.read(cx).project_items[0].clone(),
12598 ])
12599 });
12600 workspace.update_in(cx, |workspace, window, cx| {
12601 workspace.add_item(
12602 pane.clone(),
12603 Box::new(dirty_regular_buffer.clone()),
12604 None,
12605 false,
12606 false,
12607 window,
12608 cx,
12609 );
12610 workspace.add_item(
12611 pane.clone(),
12612 Box::new(dirty_regular_buffer_2.clone()),
12613 None,
12614 false,
12615 false,
12616 window,
12617 cx,
12618 );
12619 workspace.add_item(
12620 pane.clone(),
12621 Box::new(dirty_multi_buffer.clone()),
12622 None,
12623 false,
12624 false,
12625 window,
12626 cx,
12627 );
12628 });
12629
12630 pane.update_in(cx, |pane, window, cx| {
12631 pane.activate_item(2, true, true, window, cx);
12632 assert_eq!(
12633 pane.active_item().unwrap().item_id(),
12634 dirty_multi_buffer.item_id(),
12635 "Should select the multi buffer in the pane"
12636 );
12637 });
12638 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12639 pane.close_active_item(
12640 &CloseActiveItem {
12641 save_intent: None,
12642 close_pinned: false,
12643 },
12644 window,
12645 cx,
12646 )
12647 });
12648 cx.background_executor.run_until_parked();
12649 assert!(
12650 !cx.has_pending_prompt(),
12651 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12652 );
12653 close_multi_buffer_task
12654 .await
12655 .expect("Closing multi buffer failed");
12656 pane.update(cx, |pane, cx| {
12657 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12658 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12659 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12660 assert_eq!(
12661 pane.items()
12662 .map(|item| item.item_id())
12663 .sorted()
12664 .collect::<Vec<_>>(),
12665 vec![
12666 dirty_regular_buffer.item_id(),
12667 dirty_regular_buffer_2.item_id(),
12668 ],
12669 "Should have no multi buffer left in the pane"
12670 );
12671 assert!(dirty_regular_buffer.read(cx).is_dirty);
12672 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12673 });
12674 }
12675
12676 #[gpui::test]
12677 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12678 init_test(cx);
12679 let fs = FakeFs::new(cx.executor());
12680 let project = Project::test(fs, [], cx).await;
12681 let (multi_workspace, cx) =
12682 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12683 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12684
12685 // Add a new panel to the right dock, opening the dock and setting the
12686 // focus to the new panel.
12687 let panel = workspace.update_in(cx, |workspace, window, cx| {
12688 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12689 workspace.add_panel(panel.clone(), window, cx);
12690
12691 workspace
12692 .right_dock()
12693 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12694
12695 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12696
12697 panel
12698 });
12699
12700 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12701 // panel to the next valid position which, in this case, is the left
12702 // dock.
12703 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12704 workspace.update(cx, |workspace, cx| {
12705 assert!(workspace.left_dock().read(cx).is_open());
12706 assert_eq!(panel.read(cx).position, DockPosition::Left);
12707 });
12708
12709 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12710 // panel to the next valid position which, in this case, is the bottom
12711 // dock.
12712 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12713 workspace.update(cx, |workspace, cx| {
12714 assert!(workspace.bottom_dock().read(cx).is_open());
12715 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12716 });
12717
12718 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12719 // around moving the panel to its initial position, the right dock.
12720 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12721 workspace.update(cx, |workspace, cx| {
12722 assert!(workspace.right_dock().read(cx).is_open());
12723 assert_eq!(panel.read(cx).position, DockPosition::Right);
12724 });
12725
12726 // Remove focus from the panel, ensuring that, if the panel is not
12727 // focused, the `MoveFocusedPanelToNextPosition` action does not update
12728 // the panel's position, so the panel is still in the right dock.
12729 workspace.update_in(cx, |workspace, window, cx| {
12730 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12731 });
12732
12733 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12734 workspace.update(cx, |workspace, cx| {
12735 assert!(workspace.right_dock().read(cx).is_open());
12736 assert_eq!(panel.read(cx).position, DockPosition::Right);
12737 });
12738 }
12739
12740 #[gpui::test]
12741 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12742 init_test(cx);
12743
12744 let fs = FakeFs::new(cx.executor());
12745 let project = Project::test(fs, [], cx).await;
12746 let (workspace, cx) =
12747 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12748
12749 let item_1 = cx.new(|cx| {
12750 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12751 });
12752 workspace.update_in(cx, |workspace, window, cx| {
12753 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12754 workspace.move_item_to_pane_in_direction(
12755 &MoveItemToPaneInDirection {
12756 direction: SplitDirection::Right,
12757 focus: true,
12758 clone: false,
12759 },
12760 window,
12761 cx,
12762 );
12763 workspace.move_item_to_pane_at_index(
12764 &MoveItemToPane {
12765 destination: 3,
12766 focus: true,
12767 clone: false,
12768 },
12769 window,
12770 cx,
12771 );
12772
12773 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12774 assert_eq!(
12775 pane_items_paths(&workspace.active_pane, cx),
12776 vec!["first.txt".to_string()],
12777 "Single item was not moved anywhere"
12778 );
12779 });
12780
12781 let item_2 = cx.new(|cx| {
12782 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12783 });
12784 workspace.update_in(cx, |workspace, window, cx| {
12785 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12786 assert_eq!(
12787 pane_items_paths(&workspace.panes[0], cx),
12788 vec!["first.txt".to_string(), "second.txt".to_string()],
12789 );
12790 workspace.move_item_to_pane_in_direction(
12791 &MoveItemToPaneInDirection {
12792 direction: SplitDirection::Right,
12793 focus: true,
12794 clone: false,
12795 },
12796 window,
12797 cx,
12798 );
12799
12800 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12801 assert_eq!(
12802 pane_items_paths(&workspace.panes[0], cx),
12803 vec!["first.txt".to_string()],
12804 "After moving, one item should be left in the original pane"
12805 );
12806 assert_eq!(
12807 pane_items_paths(&workspace.panes[1], cx),
12808 vec!["second.txt".to_string()],
12809 "New item should have been moved to the new pane"
12810 );
12811 });
12812
12813 let item_3 = cx.new(|cx| {
12814 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12815 });
12816 workspace.update_in(cx, |workspace, window, cx| {
12817 let original_pane = workspace.panes[0].clone();
12818 workspace.set_active_pane(&original_pane, window, cx);
12819 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12820 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12821 assert_eq!(
12822 pane_items_paths(&workspace.active_pane, cx),
12823 vec!["first.txt".to_string(), "third.txt".to_string()],
12824 "New pane should be ready to move one item out"
12825 );
12826
12827 workspace.move_item_to_pane_at_index(
12828 &MoveItemToPane {
12829 destination: 3,
12830 focus: true,
12831 clone: false,
12832 },
12833 window,
12834 cx,
12835 );
12836 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12837 assert_eq!(
12838 pane_items_paths(&workspace.active_pane, cx),
12839 vec!["first.txt".to_string()],
12840 "After moving, one item should be left in the original pane"
12841 );
12842 assert_eq!(
12843 pane_items_paths(&workspace.panes[1], cx),
12844 vec!["second.txt".to_string()],
12845 "Previously created pane should be unchanged"
12846 );
12847 assert_eq!(
12848 pane_items_paths(&workspace.panes[2], cx),
12849 vec!["third.txt".to_string()],
12850 "New item should have been moved to the new pane"
12851 );
12852 });
12853 }
12854
12855 #[gpui::test]
12856 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12857 init_test(cx);
12858
12859 let fs = FakeFs::new(cx.executor());
12860 let project = Project::test(fs, [], cx).await;
12861 let (workspace, cx) =
12862 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12863
12864 let item_1 = cx.new(|cx| {
12865 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12866 });
12867 workspace.update_in(cx, |workspace, window, cx| {
12868 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12869 workspace.move_item_to_pane_in_direction(
12870 &MoveItemToPaneInDirection {
12871 direction: SplitDirection::Right,
12872 focus: true,
12873 clone: true,
12874 },
12875 window,
12876 cx,
12877 );
12878 });
12879 cx.run_until_parked();
12880 workspace.update_in(cx, |workspace, window, cx| {
12881 workspace.move_item_to_pane_at_index(
12882 &MoveItemToPane {
12883 destination: 3,
12884 focus: true,
12885 clone: true,
12886 },
12887 window,
12888 cx,
12889 );
12890 });
12891 cx.run_until_parked();
12892
12893 workspace.update(cx, |workspace, cx| {
12894 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
12895 for pane in workspace.panes() {
12896 assert_eq!(
12897 pane_items_paths(pane, cx),
12898 vec!["first.txt".to_string()],
12899 "Single item exists in all panes"
12900 );
12901 }
12902 });
12903
12904 // verify that the active pane has been updated after waiting for the
12905 // pane focus event to fire and resolve
12906 workspace.read_with(cx, |workspace, _app| {
12907 assert_eq!(
12908 workspace.active_pane(),
12909 &workspace.panes[2],
12910 "The third pane should be the active one: {:?}",
12911 workspace.panes
12912 );
12913 })
12914 }
12915
12916 #[gpui::test]
12917 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
12918 init_test(cx);
12919
12920 let fs = FakeFs::new(cx.executor());
12921 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
12922
12923 let project = Project::test(fs, ["root".as_ref()], cx).await;
12924 let (workspace, cx) =
12925 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12926
12927 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12928 // Add item to pane A with project path
12929 let item_a = cx.new(|cx| {
12930 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12931 });
12932 workspace.update_in(cx, |workspace, window, cx| {
12933 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
12934 });
12935
12936 // Split to create pane B
12937 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
12938 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
12939 });
12940
12941 // Add item with SAME project path to pane B, and pin it
12942 let item_b = cx.new(|cx| {
12943 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12944 });
12945 pane_b.update_in(cx, |pane, window, cx| {
12946 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
12947 pane.set_pinned_count(1);
12948 });
12949
12950 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
12951 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
12952
12953 // close_pinned: false should only close the unpinned copy
12954 workspace.update_in(cx, |workspace, window, cx| {
12955 workspace.close_item_in_all_panes(
12956 &CloseItemInAllPanes {
12957 save_intent: Some(SaveIntent::Close),
12958 close_pinned: false,
12959 },
12960 window,
12961 cx,
12962 )
12963 });
12964 cx.executor().run_until_parked();
12965
12966 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
12967 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12968 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
12969 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
12970
12971 // Split again, seeing as closing the previous item also closed its
12972 // pane, so only pane remains, which does not allow us to properly test
12973 // that both items close when `close_pinned: true`.
12974 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
12975 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
12976 });
12977
12978 // Add an item with the same project path to pane C so that
12979 // close_item_in_all_panes can determine what to close across all panes
12980 // (it reads the active item from the active pane, and split_pane
12981 // creates an empty pane).
12982 let item_c = cx.new(|cx| {
12983 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12984 });
12985 pane_c.update_in(cx, |pane, window, cx| {
12986 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
12987 });
12988
12989 // close_pinned: true should close the pinned copy too
12990 workspace.update_in(cx, |workspace, window, cx| {
12991 let panes_count = workspace.panes().len();
12992 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
12993
12994 workspace.close_item_in_all_panes(
12995 &CloseItemInAllPanes {
12996 save_intent: Some(SaveIntent::Close),
12997 close_pinned: true,
12998 },
12999 window,
13000 cx,
13001 )
13002 });
13003 cx.executor().run_until_parked();
13004
13005 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13006 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13007 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13008 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13009 }
13010
13011 mod register_project_item_tests {
13012
13013 use super::*;
13014
13015 // View
13016 struct TestPngItemView {
13017 focus_handle: FocusHandle,
13018 }
13019 // Model
13020 struct TestPngItem {}
13021
13022 impl project::ProjectItem for TestPngItem {
13023 fn try_open(
13024 _project: &Entity<Project>,
13025 path: &ProjectPath,
13026 cx: &mut App,
13027 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13028 if path.path.extension().unwrap() == "png" {
13029 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13030 } else {
13031 None
13032 }
13033 }
13034
13035 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13036 None
13037 }
13038
13039 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13040 None
13041 }
13042
13043 fn is_dirty(&self) -> bool {
13044 false
13045 }
13046 }
13047
13048 impl Item for TestPngItemView {
13049 type Event = ();
13050 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13051 "".into()
13052 }
13053 }
13054 impl EventEmitter<()> for TestPngItemView {}
13055 impl Focusable for TestPngItemView {
13056 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13057 self.focus_handle.clone()
13058 }
13059 }
13060
13061 impl Render for TestPngItemView {
13062 fn render(
13063 &mut self,
13064 _window: &mut Window,
13065 _cx: &mut Context<Self>,
13066 ) -> impl IntoElement {
13067 Empty
13068 }
13069 }
13070
13071 impl ProjectItem for TestPngItemView {
13072 type Item = TestPngItem;
13073
13074 fn for_project_item(
13075 _project: Entity<Project>,
13076 _pane: Option<&Pane>,
13077 _item: Entity<Self::Item>,
13078 _: &mut Window,
13079 cx: &mut Context<Self>,
13080 ) -> Self
13081 where
13082 Self: Sized,
13083 {
13084 Self {
13085 focus_handle: cx.focus_handle(),
13086 }
13087 }
13088 }
13089
13090 // View
13091 struct TestIpynbItemView {
13092 focus_handle: FocusHandle,
13093 }
13094 // Model
13095 struct TestIpynbItem {}
13096
13097 impl project::ProjectItem for TestIpynbItem {
13098 fn try_open(
13099 _project: &Entity<Project>,
13100 path: &ProjectPath,
13101 cx: &mut App,
13102 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13103 if path.path.extension().unwrap() == "ipynb" {
13104 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13105 } else {
13106 None
13107 }
13108 }
13109
13110 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13111 None
13112 }
13113
13114 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13115 None
13116 }
13117
13118 fn is_dirty(&self) -> bool {
13119 false
13120 }
13121 }
13122
13123 impl Item for TestIpynbItemView {
13124 type Event = ();
13125 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13126 "".into()
13127 }
13128 }
13129 impl EventEmitter<()> for TestIpynbItemView {}
13130 impl Focusable for TestIpynbItemView {
13131 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13132 self.focus_handle.clone()
13133 }
13134 }
13135
13136 impl Render for TestIpynbItemView {
13137 fn render(
13138 &mut self,
13139 _window: &mut Window,
13140 _cx: &mut Context<Self>,
13141 ) -> impl IntoElement {
13142 Empty
13143 }
13144 }
13145
13146 impl ProjectItem for TestIpynbItemView {
13147 type Item = TestIpynbItem;
13148
13149 fn for_project_item(
13150 _project: Entity<Project>,
13151 _pane: Option<&Pane>,
13152 _item: Entity<Self::Item>,
13153 _: &mut Window,
13154 cx: &mut Context<Self>,
13155 ) -> Self
13156 where
13157 Self: Sized,
13158 {
13159 Self {
13160 focus_handle: cx.focus_handle(),
13161 }
13162 }
13163 }
13164
13165 struct TestAlternatePngItemView {
13166 focus_handle: FocusHandle,
13167 }
13168
13169 impl Item for TestAlternatePngItemView {
13170 type Event = ();
13171 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13172 "".into()
13173 }
13174 }
13175
13176 impl EventEmitter<()> for TestAlternatePngItemView {}
13177 impl Focusable for TestAlternatePngItemView {
13178 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13179 self.focus_handle.clone()
13180 }
13181 }
13182
13183 impl Render for TestAlternatePngItemView {
13184 fn render(
13185 &mut self,
13186 _window: &mut Window,
13187 _cx: &mut Context<Self>,
13188 ) -> impl IntoElement {
13189 Empty
13190 }
13191 }
13192
13193 impl ProjectItem for TestAlternatePngItemView {
13194 type Item = TestPngItem;
13195
13196 fn for_project_item(
13197 _project: Entity<Project>,
13198 _pane: Option<&Pane>,
13199 _item: Entity<Self::Item>,
13200 _: &mut Window,
13201 cx: &mut Context<Self>,
13202 ) -> Self
13203 where
13204 Self: Sized,
13205 {
13206 Self {
13207 focus_handle: cx.focus_handle(),
13208 }
13209 }
13210 }
13211
13212 #[gpui::test]
13213 async fn test_register_project_item(cx: &mut TestAppContext) {
13214 init_test(cx);
13215
13216 cx.update(|cx| {
13217 register_project_item::<TestPngItemView>(cx);
13218 register_project_item::<TestIpynbItemView>(cx);
13219 });
13220
13221 let fs = FakeFs::new(cx.executor());
13222 fs.insert_tree(
13223 "/root1",
13224 json!({
13225 "one.png": "BINARYDATAHERE",
13226 "two.ipynb": "{ totally a notebook }",
13227 "three.txt": "editing text, sure why not?"
13228 }),
13229 )
13230 .await;
13231
13232 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13233 let (workspace, cx) =
13234 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13235
13236 let worktree_id = project.update(cx, |project, cx| {
13237 project.worktrees(cx).next().unwrap().read(cx).id()
13238 });
13239
13240 let handle = workspace
13241 .update_in(cx, |workspace, window, cx| {
13242 let project_path = (worktree_id, rel_path("one.png"));
13243 workspace.open_path(project_path, None, true, window, cx)
13244 })
13245 .await
13246 .unwrap();
13247
13248 // Now we can check if the handle we got back errored or not
13249 assert_eq!(
13250 handle.to_any_view().entity_type(),
13251 TypeId::of::<TestPngItemView>()
13252 );
13253
13254 let handle = workspace
13255 .update_in(cx, |workspace, window, cx| {
13256 let project_path = (worktree_id, rel_path("two.ipynb"));
13257 workspace.open_path(project_path, None, true, window, cx)
13258 })
13259 .await
13260 .unwrap();
13261
13262 assert_eq!(
13263 handle.to_any_view().entity_type(),
13264 TypeId::of::<TestIpynbItemView>()
13265 );
13266
13267 let handle = workspace
13268 .update_in(cx, |workspace, window, cx| {
13269 let project_path = (worktree_id, rel_path("three.txt"));
13270 workspace.open_path(project_path, None, true, window, cx)
13271 })
13272 .await;
13273 assert!(handle.is_err());
13274 }
13275
13276 #[gpui::test]
13277 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
13278 init_test(cx);
13279
13280 cx.update(|cx| {
13281 register_project_item::<TestPngItemView>(cx);
13282 register_project_item::<TestAlternatePngItemView>(cx);
13283 });
13284
13285 let fs = FakeFs::new(cx.executor());
13286 fs.insert_tree(
13287 "/root1",
13288 json!({
13289 "one.png": "BINARYDATAHERE",
13290 "two.ipynb": "{ totally a notebook }",
13291 "three.txt": "editing text, sure why not?"
13292 }),
13293 )
13294 .await;
13295 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13296 let (workspace, cx) =
13297 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13298 let worktree_id = project.update(cx, |project, cx| {
13299 project.worktrees(cx).next().unwrap().read(cx).id()
13300 });
13301
13302 let handle = workspace
13303 .update_in(cx, |workspace, window, cx| {
13304 let project_path = (worktree_id, rel_path("one.png"));
13305 workspace.open_path(project_path, None, true, window, cx)
13306 })
13307 .await
13308 .unwrap();
13309
13310 // This _must_ be the second item registered
13311 assert_eq!(
13312 handle.to_any_view().entity_type(),
13313 TypeId::of::<TestAlternatePngItemView>()
13314 );
13315
13316 let handle = workspace
13317 .update_in(cx, |workspace, window, cx| {
13318 let project_path = (worktree_id, rel_path("three.txt"));
13319 workspace.open_path(project_path, None, true, window, cx)
13320 })
13321 .await;
13322 assert!(handle.is_err());
13323 }
13324 }
13325
13326 #[gpui::test]
13327 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13328 init_test(cx);
13329
13330 let fs = FakeFs::new(cx.executor());
13331 let project = Project::test(fs, [], cx).await;
13332 let (workspace, _cx) =
13333 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13334
13335 // Test with status bar shown (default)
13336 workspace.read_with(cx, |workspace, cx| {
13337 let visible = workspace.status_bar_visible(cx);
13338 assert!(visible, "Status bar should be visible by default");
13339 });
13340
13341 // Test with status bar hidden
13342 cx.update_global(|store: &mut SettingsStore, cx| {
13343 store.update_user_settings(cx, |settings| {
13344 settings.status_bar.get_or_insert_default().show = Some(false);
13345 });
13346 });
13347
13348 workspace.read_with(cx, |workspace, cx| {
13349 let visible = workspace.status_bar_visible(cx);
13350 assert!(!visible, "Status bar should be hidden when show is false");
13351 });
13352
13353 // Test with status bar shown explicitly
13354 cx.update_global(|store: &mut SettingsStore, cx| {
13355 store.update_user_settings(cx, |settings| {
13356 settings.status_bar.get_or_insert_default().show = Some(true);
13357 });
13358 });
13359
13360 workspace.read_with(cx, |workspace, cx| {
13361 let visible = workspace.status_bar_visible(cx);
13362 assert!(visible, "Status bar should be visible when show is true");
13363 });
13364 }
13365
13366 #[gpui::test]
13367 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13368 init_test(cx);
13369
13370 let fs = FakeFs::new(cx.executor());
13371 let project = Project::test(fs, [], cx).await;
13372 let (multi_workspace, cx) =
13373 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13374 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13375 let panel = workspace.update_in(cx, |workspace, window, cx| {
13376 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13377 workspace.add_panel(panel.clone(), window, cx);
13378
13379 workspace
13380 .right_dock()
13381 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13382
13383 panel
13384 });
13385
13386 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13387 let item_a = cx.new(TestItem::new);
13388 let item_b = cx.new(TestItem::new);
13389 let item_a_id = item_a.entity_id();
13390 let item_b_id = item_b.entity_id();
13391
13392 pane.update_in(cx, |pane, window, cx| {
13393 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13394 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13395 });
13396
13397 pane.read_with(cx, |pane, _| {
13398 assert_eq!(pane.items_len(), 2);
13399 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13400 });
13401
13402 workspace.update_in(cx, |workspace, window, cx| {
13403 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13404 });
13405
13406 workspace.update_in(cx, |_, window, cx| {
13407 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13408 });
13409
13410 // Assert that the `pane::CloseActiveItem` action is handled at the
13411 // workspace level when one of the dock panels is focused and, in that
13412 // case, the center pane's active item is closed but the focus is not
13413 // moved.
13414 cx.dispatch_action(pane::CloseActiveItem::default());
13415 cx.run_until_parked();
13416
13417 pane.read_with(cx, |pane, _| {
13418 assert_eq!(pane.items_len(), 1);
13419 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13420 });
13421
13422 workspace.update_in(cx, |workspace, window, cx| {
13423 assert!(workspace.right_dock().read(cx).is_open());
13424 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13425 });
13426 }
13427
13428 #[gpui::test]
13429 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13430 init_test(cx);
13431 let fs = FakeFs::new(cx.executor());
13432
13433 let project_a = Project::test(fs.clone(), [], cx).await;
13434 let project_b = Project::test(fs, [], cx).await;
13435
13436 let multi_workspace_handle =
13437 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13438 cx.run_until_parked();
13439
13440 let workspace_a = multi_workspace_handle
13441 .read_with(cx, |mw, _| mw.workspace().clone())
13442 .unwrap();
13443
13444 let _workspace_b = multi_workspace_handle
13445 .update(cx, |mw, window, cx| {
13446 mw.test_add_workspace(project_b, window, cx)
13447 })
13448 .unwrap();
13449
13450 // Switch to workspace A
13451 multi_workspace_handle
13452 .update(cx, |mw, window, cx| {
13453 mw.activate_index(0, window, cx);
13454 })
13455 .unwrap();
13456
13457 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13458
13459 // Add a panel to workspace A's right dock and open the dock
13460 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13461 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13462 workspace.add_panel(panel.clone(), window, cx);
13463 workspace
13464 .right_dock()
13465 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13466 panel
13467 });
13468
13469 // Focus the panel through the workspace (matching existing test pattern)
13470 workspace_a.update_in(cx, |workspace, window, cx| {
13471 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13472 });
13473
13474 // Zoom the panel
13475 panel.update_in(cx, |panel, window, cx| {
13476 panel.set_zoomed(true, window, cx);
13477 });
13478
13479 // Verify the panel is zoomed and the dock is open
13480 workspace_a.update_in(cx, |workspace, window, cx| {
13481 assert!(
13482 workspace.right_dock().read(cx).is_open(),
13483 "dock should be open before switch"
13484 );
13485 assert!(
13486 panel.is_zoomed(window, cx),
13487 "panel should be zoomed before switch"
13488 );
13489 assert!(
13490 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13491 "panel should be focused before switch"
13492 );
13493 });
13494
13495 // Switch to workspace B
13496 multi_workspace_handle
13497 .update(cx, |mw, window, cx| {
13498 mw.activate_index(1, window, cx);
13499 })
13500 .unwrap();
13501 cx.run_until_parked();
13502
13503 // Switch back to workspace A
13504 multi_workspace_handle
13505 .update(cx, |mw, window, cx| {
13506 mw.activate_index(0, window, cx);
13507 })
13508 .unwrap();
13509 cx.run_until_parked();
13510
13511 // Verify the panel is still zoomed and the dock is still open
13512 workspace_a.update_in(cx, |workspace, window, cx| {
13513 assert!(
13514 workspace.right_dock().read(cx).is_open(),
13515 "dock should still be open after switching back"
13516 );
13517 assert!(
13518 panel.is_zoomed(window, cx),
13519 "panel should still be zoomed after switching back"
13520 );
13521 });
13522 }
13523
13524 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13525 pane.read(cx)
13526 .items()
13527 .flat_map(|item| {
13528 item.project_paths(cx)
13529 .into_iter()
13530 .map(|path| path.path.display(PathStyle::local()).into_owned())
13531 })
13532 .collect()
13533 }
13534
13535 pub fn init_test(cx: &mut TestAppContext) {
13536 cx.update(|cx| {
13537 let settings_store = SettingsStore::test(cx);
13538 cx.set_global(settings_store);
13539 theme::init(theme::LoadThemes::JustBase, cx);
13540 });
13541 }
13542
13543 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13544 let item = TestProjectItem::new(id, path, cx);
13545 item.update(cx, |item, _| {
13546 item.is_dirty = true;
13547 });
13548 item
13549 }
13550
13551 #[gpui::test]
13552 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13553 cx: &mut gpui::TestAppContext,
13554 ) {
13555 init_test(cx);
13556 let fs = FakeFs::new(cx.executor());
13557
13558 let project = Project::test(fs, [], cx).await;
13559 let (workspace, cx) =
13560 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13561
13562 let panel = workspace.update_in(cx, |workspace, window, cx| {
13563 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13564 workspace.add_panel(panel.clone(), window, cx);
13565 workspace
13566 .right_dock()
13567 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13568 panel
13569 });
13570
13571 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13572 pane.update_in(cx, |pane, window, cx| {
13573 let item = cx.new(TestItem::new);
13574 pane.add_item(Box::new(item), true, true, None, window, cx);
13575 });
13576
13577 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13578 // mirrors the real-world flow and avoids side effects from directly
13579 // focusing the panel while the center pane is active.
13580 workspace.update_in(cx, |workspace, window, cx| {
13581 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13582 });
13583
13584 panel.update_in(cx, |panel, window, cx| {
13585 panel.set_zoomed(true, window, cx);
13586 });
13587
13588 workspace.update_in(cx, |workspace, window, cx| {
13589 assert!(workspace.right_dock().read(cx).is_open());
13590 assert!(panel.is_zoomed(window, cx));
13591 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13592 });
13593
13594 // Simulate a spurious pane::Event::Focus on the center pane while the
13595 // panel still has focus. This mirrors what happens during macOS window
13596 // activation: the center pane fires a focus event even though actual
13597 // focus remains on the dock panel.
13598 pane.update_in(cx, |_, _, cx| {
13599 cx.emit(pane::Event::Focus);
13600 });
13601
13602 // The dock must remain open because the panel had focus at the time the
13603 // event was processed. Before the fix, dock_to_preserve was None for
13604 // panels that don't implement pane(), causing the dock to close.
13605 workspace.update_in(cx, |workspace, window, cx| {
13606 assert!(
13607 workspace.right_dock().read(cx).is_open(),
13608 "Dock should stay open when its zoomed panel (without pane()) still has focus"
13609 );
13610 assert!(panel.is_zoomed(window, cx));
13611 });
13612 }
13613}