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, Sidebar,
31 SidebarHandle, ToggleWorkspaceSidebar,
32};
33pub use path_list::{PathList, SerializedPathList};
34pub use toast_layer::{ToastAction, ToastLayer, ToastView};
35
36use anyhow::{Context as _, Result, anyhow};
37use client::{
38 ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
39 proto::{self, ErrorCode, PanelId, PeerId},
40};
41use collections::{HashMap, HashSet, hash_map};
42use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
43use fs::Fs;
44use futures::{
45 Future, FutureExt, StreamExt,
46 channel::{
47 mpsc::{self, UnboundedReceiver, UnboundedSender},
48 oneshot,
49 },
50 future::{Shared, try_join_all},
51};
52use gpui::{
53 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
54 CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
55 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
56 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
57 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
58 WindowOptions, actions, canvas, point, relative, size, transparent_black,
59};
60pub use history_manager::*;
61pub use item::{
62 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
63 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
64};
65use itertools::Itertools;
66use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
67pub use modal_layer::*;
68use node_runtime::NodeRuntime;
69use notifications::{
70 DetachAndPromptErr, Notifications, dismiss_app_notification,
71 simple_message_notification::MessageNotification,
72};
73pub use pane::*;
74pub use pane_group::{
75 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
76 SplitDirection,
77};
78use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
79pub use persistence::{
80 WorkspaceDb, delete_unloaded_items,
81 model::{
82 DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
83 SessionWorkspace,
84 },
85 read_serialized_multi_workspaces,
86};
87use postage::stream::Stream;
88use project::{
89 DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
90 WorktreeSettings,
91 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
92 project_settings::ProjectSettings,
93 toolchain_store::ToolchainStoreEvent,
94 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
95};
96use remote::{
97 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
98 remote_client::ConnectionIdentifier,
99};
100use schemars::JsonSchema;
101use serde::Deserialize;
102use session::AppSession;
103use settings::{
104 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
105};
106
107use sqlez::{
108 bindable::{Bind, Column, StaticColumnCount},
109 statement::Statement,
110};
111use status_bar::StatusBar;
112pub use status_bar::StatusItemView;
113use std::{
114 any::TypeId,
115 borrow::Cow,
116 cell::RefCell,
117 cmp,
118 collections::VecDeque,
119 env,
120 hash::Hash,
121 path::{Path, PathBuf},
122 process::ExitStatus,
123 rc::Rc,
124 sync::{
125 Arc, LazyLock, Weak,
126 atomic::{AtomicBool, AtomicUsize},
127 },
128 time::Duration,
129};
130use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
131use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
132pub use toolbar::{
133 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
134};
135pub use ui;
136use ui::{Window, prelude::*};
137use util::{
138 ResultExt, TryFutureExt,
139 paths::{PathStyle, SanitizedPath},
140 rel_path::RelPath,
141 serde::default_true,
142};
143use uuid::Uuid;
144pub use workspace_settings::{
145 AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
146 WorkspaceSettings,
147};
148use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
149
150use crate::{item::ItemBufferKind, notifications::NotificationId};
151use crate::{
152 persistence::{
153 SerializedAxis,
154 model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
155 },
156 security_modal::SecurityModal,
157};
158
159pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
160
161static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
162 env::var("ZED_WINDOW_SIZE")
163 .ok()
164 .as_deref()
165 .and_then(parse_pixel_size_env_var)
166});
167
168static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
169 env::var("ZED_WINDOW_POSITION")
170 .ok()
171 .as_deref()
172 .and_then(parse_pixel_position_env_var)
173});
174
175pub trait TerminalProvider {
176 fn spawn(
177 &self,
178 task: SpawnInTerminal,
179 window: &mut Window,
180 cx: &mut App,
181 ) -> Task<Option<Result<ExitStatus>>>;
182}
183
184pub trait DebuggerProvider {
185 // `active_buffer` is used to resolve build task's name against language-specific tasks.
186 fn start_session(
187 &self,
188 definition: DebugScenario,
189 task_context: SharedTaskContext,
190 active_buffer: Option<Entity<Buffer>>,
191 worktree_id: Option<WorktreeId>,
192 window: &mut Window,
193 cx: &mut App,
194 );
195
196 fn spawn_task_or_modal(
197 &self,
198 workspace: &mut Workspace,
199 action: &Spawn,
200 window: &mut Window,
201 cx: &mut Context<Workspace>,
202 );
203
204 fn task_scheduled(&self, cx: &mut App);
205 fn debug_scenario_scheduled(&self, cx: &mut App);
206 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
207
208 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
209}
210
211/// Opens a file or directory.
212#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
213#[action(namespace = workspace)]
214pub struct Open {
215 /// When true, opens in a new window. When false, adds to the current
216 /// window as a new workspace (multi-workspace).
217 #[serde(default = "Open::default_create_new_window")]
218 pub create_new_window: bool,
219}
220
221impl Open {
222 pub const DEFAULT: Self = Self {
223 create_new_window: true,
224 };
225
226 /// Used by `#[serde(default)]` on the `create_new_window` field so that
227 /// the serde default and `Open::DEFAULT` stay in sync.
228 fn default_create_new_window() -> bool {
229 Self::DEFAULT.create_new_window
230 }
231}
232
233impl Default for Open {
234 fn default() -> Self {
235 Self::DEFAULT
236 }
237}
238
239actions!(
240 workspace,
241 [
242 /// Activates the next pane in the workspace.
243 ActivateNextPane,
244 /// Activates the previous pane in the workspace.
245 ActivatePreviousPane,
246 /// Activates the last pane in the workspace.
247 ActivateLastPane,
248 /// Switches to the next window.
249 ActivateNextWindow,
250 /// Switches to the previous window.
251 ActivatePreviousWindow,
252 /// Adds a folder to the current project.
253 AddFolderToProject,
254 /// Clears all notifications.
255 ClearAllNotifications,
256 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
257 ClearNavigationHistory,
258 /// Closes the active dock.
259 CloseActiveDock,
260 /// Closes all docks.
261 CloseAllDocks,
262 /// Toggles all docks.
263 ToggleAllDocks,
264 /// Closes the current window.
265 CloseWindow,
266 /// Closes the current project.
267 CloseProject,
268 /// Opens the feedback dialog.
269 Feedback,
270 /// Follows the next collaborator in the session.
271 FollowNextCollaborator,
272 /// Moves the focused panel to the next position.
273 MoveFocusedPanelToNextPosition,
274 /// Creates a new file.
275 NewFile,
276 /// Creates a new file in a vertical split.
277 NewFileSplitVertical,
278 /// Creates a new file in a horizontal split.
279 NewFileSplitHorizontal,
280 /// Opens a new search.
281 NewSearch,
282 /// Opens a new window.
283 NewWindow,
284 /// Opens multiple files.
285 OpenFiles,
286 /// Opens the current location in terminal.
287 OpenInTerminal,
288 /// Opens the component preview.
289 OpenComponentPreview,
290 /// Reloads the active item.
291 ReloadActiveItem,
292 /// Resets the active dock to its default size.
293 ResetActiveDockSize,
294 /// Resets all open docks to their default sizes.
295 ResetOpenDocksSize,
296 /// Reloads the application
297 Reload,
298 /// Saves the current file with a new name.
299 SaveAs,
300 /// Saves without formatting.
301 SaveWithoutFormat,
302 /// Shuts down all debug adapters.
303 ShutdownDebugAdapters,
304 /// Suppresses the current notification.
305 SuppressNotification,
306 /// Toggles the bottom dock.
307 ToggleBottomDock,
308 /// Toggles centered layout mode.
309 ToggleCenteredLayout,
310 /// Toggles edit prediction feature globally for all files.
311 ToggleEditPrediction,
312 /// Toggles the left dock.
313 ToggleLeftDock,
314 /// Toggles the right dock.
315 ToggleRightDock,
316 /// Toggles zoom on the active pane.
317 ToggleZoom,
318 /// Toggles read-only mode for the active item (if supported by that item).
319 ToggleReadOnlyFile,
320 /// Zooms in on the active pane.
321 ZoomIn,
322 /// Zooms out of the active pane.
323 ZoomOut,
324 /// If any worktrees are in restricted mode, shows a modal with possible actions.
325 /// If the modal is shown already, closes it without trusting any worktree.
326 ToggleWorktreeSecurity,
327 /// Clears all trusted worktrees, placing them in restricted mode on next open.
328 /// Requires restart to take effect on already opened projects.
329 ClearTrustedWorktrees,
330 /// Stops following a collaborator.
331 Unfollow,
332 /// Restores the banner.
333 RestoreBanner,
334 /// Toggles expansion of the selected item.
335 ToggleExpandItem,
336 ]
337);
338
339/// Activates a specific pane by its index.
340#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
341#[action(namespace = workspace)]
342pub struct ActivatePane(pub usize);
343
344/// Moves an item to a specific pane by index.
345#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
346#[action(namespace = workspace)]
347#[serde(deny_unknown_fields)]
348pub struct MoveItemToPane {
349 #[serde(default = "default_1")]
350 pub destination: usize,
351 #[serde(default = "default_true")]
352 pub focus: bool,
353 #[serde(default)]
354 pub clone: bool,
355}
356
357fn default_1() -> usize {
358 1
359}
360
361/// Moves an item to a pane in the specified direction.
362#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
363#[action(namespace = workspace)]
364#[serde(deny_unknown_fields)]
365pub struct MoveItemToPaneInDirection {
366 #[serde(default = "default_right")]
367 pub direction: SplitDirection,
368 #[serde(default = "default_true")]
369 pub focus: bool,
370 #[serde(default)]
371 pub clone: bool,
372}
373
374/// Creates a new file in a split of the desired direction.
375#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
376#[action(namespace = workspace)]
377#[serde(deny_unknown_fields)]
378pub struct NewFileSplit(pub SplitDirection);
379
380fn default_right() -> SplitDirection {
381 SplitDirection::Right
382}
383
384/// Saves all open files in the workspace.
385#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
386#[action(namespace = workspace)]
387#[serde(deny_unknown_fields)]
388pub struct SaveAll {
389 #[serde(default)]
390 pub save_intent: Option<SaveIntent>,
391}
392
393/// Saves the current file with the specified options.
394#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
395#[action(namespace = workspace)]
396#[serde(deny_unknown_fields)]
397pub struct Save {
398 #[serde(default)]
399 pub save_intent: Option<SaveIntent>,
400}
401
402/// Moves Focus to the central panes in the workspace.
403#[derive(Clone, Debug, PartialEq, Eq, Action)]
404#[action(namespace = workspace)]
405pub struct FocusCenterPane;
406
407/// Closes all items and panes in the workspace.
408#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
409#[action(namespace = workspace)]
410#[serde(deny_unknown_fields)]
411pub struct CloseAllItemsAndPanes {
412 #[serde(default)]
413 pub save_intent: Option<SaveIntent>,
414}
415
416/// Closes all inactive tabs and panes in the workspace.
417#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
418#[action(namespace = workspace)]
419#[serde(deny_unknown_fields)]
420pub struct CloseInactiveTabsAndPanes {
421 #[serde(default)]
422 pub save_intent: Option<SaveIntent>,
423}
424
425/// Closes the active item across all panes.
426#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
427#[action(namespace = workspace)]
428#[serde(deny_unknown_fields)]
429pub struct CloseItemInAllPanes {
430 #[serde(default)]
431 pub save_intent: Option<SaveIntent>,
432 #[serde(default)]
433 pub close_pinned: bool,
434}
435
436/// Sends a sequence of keystrokes to the active element.
437#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
438#[action(namespace = workspace)]
439pub struct SendKeystrokes(pub String);
440
441actions!(
442 project_symbols,
443 [
444 /// Toggles the project symbols search.
445 #[action(name = "Toggle")]
446 ToggleProjectSymbols
447 ]
448);
449
450/// Toggles the file finder interface.
451#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
452#[action(namespace = file_finder, name = "Toggle")]
453#[serde(deny_unknown_fields)]
454pub struct ToggleFileFinder {
455 #[serde(default)]
456 pub separate_history: bool,
457}
458
459/// Opens a new terminal in the center.
460#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
461#[action(namespace = workspace)]
462#[serde(deny_unknown_fields)]
463pub struct NewCenterTerminal {
464 /// If true, creates a local terminal even in remote projects.
465 #[serde(default)]
466 pub local: bool,
467}
468
469/// Opens a new terminal.
470#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
471#[action(namespace = workspace)]
472#[serde(deny_unknown_fields)]
473pub struct NewTerminal {
474 /// If true, creates a local terminal even in remote projects.
475 #[serde(default)]
476 pub local: bool,
477}
478
479/// Increases size of a currently focused dock by a given amount of pixels.
480#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
481#[action(namespace = workspace)]
482#[serde(deny_unknown_fields)]
483pub struct IncreaseActiveDockSize {
484 /// For 0px parameter, uses UI font size value.
485 #[serde(default)]
486 pub px: u32,
487}
488
489/// Decreases size of a currently focused dock by a given amount of pixels.
490#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
491#[action(namespace = workspace)]
492#[serde(deny_unknown_fields)]
493pub struct DecreaseActiveDockSize {
494 /// For 0px parameter, uses UI font size value.
495 #[serde(default)]
496 pub px: u32,
497}
498
499/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
500#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
501#[action(namespace = workspace)]
502#[serde(deny_unknown_fields)]
503pub struct IncreaseOpenDocksSize {
504 /// For 0px parameter, uses UI font size value.
505 #[serde(default)]
506 pub px: u32,
507}
508
509/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
510#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
511#[action(namespace = workspace)]
512#[serde(deny_unknown_fields)]
513pub struct DecreaseOpenDocksSize {
514 /// For 0px parameter, uses UI font size value.
515 #[serde(default)]
516 pub px: u32,
517}
518
519actions!(
520 workspace,
521 [
522 /// Activates the pane to the left.
523 ActivatePaneLeft,
524 /// Activates the pane to the right.
525 ActivatePaneRight,
526 /// Activates the pane above.
527 ActivatePaneUp,
528 /// Activates the pane below.
529 ActivatePaneDown,
530 /// Swaps the current pane with the one to the left.
531 SwapPaneLeft,
532 /// Swaps the current pane with the one to the right.
533 SwapPaneRight,
534 /// Swaps the current pane with the one above.
535 SwapPaneUp,
536 /// Swaps the current pane with the one below.
537 SwapPaneDown,
538 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
539 SwapPaneAdjacent,
540 /// Move the current pane to be at the far left.
541 MovePaneLeft,
542 /// Move the current pane to be at the far right.
543 MovePaneRight,
544 /// Move the current pane to be at the very top.
545 MovePaneUp,
546 /// Move the current pane to be at the very bottom.
547 MovePaneDown,
548 ]
549);
550
551#[derive(PartialEq, Eq, Debug)]
552pub enum CloseIntent {
553 /// Quit the program entirely.
554 Quit,
555 /// Close a window.
556 CloseWindow,
557 /// Replace the workspace in an existing window.
558 ReplaceWindow,
559}
560
561#[derive(Clone)]
562pub struct Toast {
563 id: NotificationId,
564 msg: Cow<'static, str>,
565 autohide: bool,
566 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
567}
568
569impl Toast {
570 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
571 Toast {
572 id,
573 msg: msg.into(),
574 on_click: None,
575 autohide: false,
576 }
577 }
578
579 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
580 where
581 M: Into<Cow<'static, str>>,
582 F: Fn(&mut Window, &mut App) + 'static,
583 {
584 self.on_click = Some((message.into(), Arc::new(on_click)));
585 self
586 }
587
588 pub fn autohide(mut self) -> Self {
589 self.autohide = true;
590 self
591 }
592}
593
594impl PartialEq for Toast {
595 fn eq(&self, other: &Self) -> bool {
596 self.id == other.id
597 && self.msg == other.msg
598 && self.on_click.is_some() == other.on_click.is_some()
599 }
600}
601
602/// Opens a new terminal with the specified working directory.
603#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
604#[action(namespace = workspace)]
605#[serde(deny_unknown_fields)]
606pub struct OpenTerminal {
607 pub working_directory: PathBuf,
608 /// If true, creates a local terminal even in remote projects.
609 #[serde(default)]
610 pub local: bool,
611}
612
613#[derive(
614 Clone,
615 Copy,
616 Debug,
617 Default,
618 Hash,
619 PartialEq,
620 Eq,
621 PartialOrd,
622 Ord,
623 serde::Serialize,
624 serde::Deserialize,
625)]
626pub struct WorkspaceId(i64);
627
628impl WorkspaceId {
629 pub fn from_i64(value: i64) -> Self {
630 Self(value)
631 }
632}
633
634impl StaticColumnCount for WorkspaceId {}
635impl Bind for WorkspaceId {
636 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
637 self.0.bind(statement, start_index)
638 }
639}
640impl Column for WorkspaceId {
641 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
642 i64::column(statement, start_index)
643 .map(|(i, next_index)| (Self(i), next_index))
644 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
645 }
646}
647impl From<WorkspaceId> for i64 {
648 fn from(val: WorkspaceId) -> Self {
649 val.0
650 }
651}
652
653fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
654 if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
655 workspace_window
656 .update(cx, |multi_workspace, window, cx| {
657 let workspace = multi_workspace.workspace().clone();
658 workspace.update(cx, |workspace, cx| {
659 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
660 });
661 })
662 .ok();
663 } else {
664 let task = Workspace::new_local(Vec::new(), app_state.clone(), None, None, None, true, cx);
665 cx.spawn(async move |cx| {
666 let OpenResult { window, .. } = task.await?;
667 window.update(cx, |multi_workspace, window, cx| {
668 window.activate_window();
669 let workspace = multi_workspace.workspace().clone();
670 workspace.update(cx, |workspace, cx| {
671 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
672 });
673 })?;
674 anyhow::Ok(())
675 })
676 .detach_and_log_err(cx);
677 }
678}
679
680pub fn prompt_for_open_path_and_open(
681 workspace: &mut Workspace,
682 app_state: Arc<AppState>,
683 options: PathPromptOptions,
684 create_new_window: bool,
685 window: &mut Window,
686 cx: &mut Context<Workspace>,
687) {
688 let paths = workspace.prompt_for_open_path(
689 options,
690 DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
691 window,
692 cx,
693 );
694 let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
695 cx.spawn_in(window, async move |this, cx| {
696 let Some(paths) = paths.await.log_err().flatten() else {
697 return;
698 };
699 if !create_new_window {
700 if let Some(handle) = multi_workspace_handle {
701 if let Some(task) = handle
702 .update(cx, |multi_workspace, window, cx| {
703 multi_workspace.open_project(paths, window, cx)
704 })
705 .log_err()
706 {
707 task.await.log_err();
708 }
709 return;
710 }
711 }
712 if let Some(task) = this
713 .update_in(cx, |this, window, cx| {
714 this.open_workspace_for_paths(false, paths, window, cx)
715 })
716 .log_err()
717 {
718 task.await.log_err();
719 }
720 })
721 .detach();
722}
723
724pub fn init(app_state: Arc<AppState>, cx: &mut App) {
725 component::init();
726 theme_preview::init(cx);
727 toast_layer::init(cx);
728 history_manager::init(app_state.fs.clone(), cx);
729
730 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
731 .on_action(|_: &Reload, cx| reload(cx))
732 .on_action({
733 let app_state = Arc::downgrade(&app_state);
734 move |_: &Open, cx: &mut App| {
735 if let Some(app_state) = app_state.upgrade() {
736 prompt_and_open_paths(
737 app_state,
738 PathPromptOptions {
739 files: true,
740 directories: true,
741 multiple: true,
742 prompt: None,
743 },
744 cx,
745 );
746 }
747 }
748 })
749 .on_action({
750 let app_state = Arc::downgrade(&app_state);
751 move |_: &OpenFiles, cx: &mut App| {
752 let directories = cx.can_select_mixed_files_and_dirs();
753 if let Some(app_state) = app_state.upgrade() {
754 prompt_and_open_paths(
755 app_state,
756 PathPromptOptions {
757 files: true,
758 directories,
759 multiple: true,
760 prompt: None,
761 },
762 cx,
763 );
764 }
765 }
766 });
767}
768
769type BuildProjectItemFn =
770 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
771
772type BuildProjectItemForPathFn =
773 fn(
774 &Entity<Project>,
775 &ProjectPath,
776 &mut Window,
777 &mut App,
778 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
779
780#[derive(Clone, Default)]
781struct ProjectItemRegistry {
782 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
783 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
784}
785
786impl ProjectItemRegistry {
787 fn register<T: ProjectItem>(&mut self) {
788 self.build_project_item_fns_by_type.insert(
789 TypeId::of::<T::Item>(),
790 |item, project, pane, window, cx| {
791 let item = item.downcast().unwrap();
792 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
793 as Box<dyn ItemHandle>
794 },
795 );
796 self.build_project_item_for_path_fns
797 .push(|project, project_path, window, cx| {
798 let project_path = project_path.clone();
799 let is_file = project
800 .read(cx)
801 .entry_for_path(&project_path, cx)
802 .is_some_and(|entry| entry.is_file());
803 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
804 let is_local = project.read(cx).is_local();
805 let project_item =
806 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
807 let project = project.clone();
808 Some(window.spawn(cx, async move |cx| {
809 match project_item.await.with_context(|| {
810 format!(
811 "opening project path {:?}",
812 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
813 )
814 }) {
815 Ok(project_item) => {
816 let project_item = project_item;
817 let project_entry_id: Option<ProjectEntryId> =
818 project_item.read_with(cx, project::ProjectItem::entry_id);
819 let build_workspace_item = Box::new(
820 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
821 Box::new(cx.new(|cx| {
822 T::for_project_item(
823 project,
824 Some(pane),
825 project_item,
826 window,
827 cx,
828 )
829 })) as Box<dyn ItemHandle>
830 },
831 ) as Box<_>;
832 Ok((project_entry_id, build_workspace_item))
833 }
834 Err(e) => {
835 log::warn!("Failed to open a project item: {e:#}");
836 if e.error_code() == ErrorCode::Internal {
837 if let Some(abs_path) =
838 entry_abs_path.as_deref().filter(|_| is_file)
839 {
840 if let Some(broken_project_item_view) =
841 cx.update(|window, cx| {
842 T::for_broken_project_item(
843 abs_path, is_local, &e, window, cx,
844 )
845 })?
846 {
847 let build_workspace_item = Box::new(
848 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
849 cx.new(|_| broken_project_item_view).boxed_clone()
850 },
851 )
852 as Box<_>;
853 return Ok((None, build_workspace_item));
854 }
855 }
856 }
857 Err(e)
858 }
859 }
860 }))
861 });
862 }
863
864 fn open_path(
865 &self,
866 project: &Entity<Project>,
867 path: &ProjectPath,
868 window: &mut Window,
869 cx: &mut App,
870 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
871 let Some(open_project_item) = self
872 .build_project_item_for_path_fns
873 .iter()
874 .rev()
875 .find_map(|open_project_item| open_project_item(project, path, window, cx))
876 else {
877 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
878 };
879 open_project_item
880 }
881
882 fn build_item<T: project::ProjectItem>(
883 &self,
884 item: Entity<T>,
885 project: Entity<Project>,
886 pane: Option<&Pane>,
887 window: &mut Window,
888 cx: &mut App,
889 ) -> Option<Box<dyn ItemHandle>> {
890 let build = self
891 .build_project_item_fns_by_type
892 .get(&TypeId::of::<T>())?;
893 Some(build(item.into_any(), project, pane, window, cx))
894 }
895}
896
897type WorkspaceItemBuilder =
898 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
899
900impl Global for ProjectItemRegistry {}
901
902/// Registers a [ProjectItem] for the app. When opening a file, all the registered
903/// items will get a chance to open the file, starting from the project item that
904/// was added last.
905pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
906 cx.default_global::<ProjectItemRegistry>().register::<I>();
907}
908
909#[derive(Default)]
910pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
911
912struct FollowableViewDescriptor {
913 from_state_proto: fn(
914 Entity<Workspace>,
915 ViewId,
916 &mut Option<proto::view::Variant>,
917 &mut Window,
918 &mut App,
919 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
920 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
921}
922
923impl Global for FollowableViewRegistry {}
924
925impl FollowableViewRegistry {
926 pub fn register<I: FollowableItem>(cx: &mut App) {
927 cx.default_global::<Self>().0.insert(
928 TypeId::of::<I>(),
929 FollowableViewDescriptor {
930 from_state_proto: |workspace, id, state, window, cx| {
931 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
932 cx.foreground_executor()
933 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
934 })
935 },
936 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
937 },
938 );
939 }
940
941 pub fn from_state_proto(
942 workspace: Entity<Workspace>,
943 view_id: ViewId,
944 mut state: Option<proto::view::Variant>,
945 window: &mut Window,
946 cx: &mut App,
947 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
948 cx.update_default_global(|this: &mut Self, cx| {
949 this.0.values().find_map(|descriptor| {
950 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
951 })
952 })
953 }
954
955 pub fn to_followable_view(
956 view: impl Into<AnyView>,
957 cx: &App,
958 ) -> Option<Box<dyn FollowableItemHandle>> {
959 let this = cx.try_global::<Self>()?;
960 let view = view.into();
961 let descriptor = this.0.get(&view.entity_type())?;
962 Some((descriptor.to_followable_view)(&view))
963 }
964}
965
966#[derive(Copy, Clone)]
967struct SerializableItemDescriptor {
968 deserialize: fn(
969 Entity<Project>,
970 WeakEntity<Workspace>,
971 WorkspaceId,
972 ItemId,
973 &mut Window,
974 &mut Context<Pane>,
975 ) -> Task<Result<Box<dyn ItemHandle>>>,
976 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
977 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
978}
979
980#[derive(Default)]
981struct SerializableItemRegistry {
982 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
983 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
984}
985
986impl Global for SerializableItemRegistry {}
987
988impl SerializableItemRegistry {
989 fn deserialize(
990 item_kind: &str,
991 project: Entity<Project>,
992 workspace: WeakEntity<Workspace>,
993 workspace_id: WorkspaceId,
994 item_item: ItemId,
995 window: &mut Window,
996 cx: &mut Context<Pane>,
997 ) -> Task<Result<Box<dyn ItemHandle>>> {
998 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
999 return Task::ready(Err(anyhow!(
1000 "cannot deserialize {}, descriptor not found",
1001 item_kind
1002 )));
1003 };
1004
1005 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
1006 }
1007
1008 fn cleanup(
1009 item_kind: &str,
1010 workspace_id: WorkspaceId,
1011 loaded_items: Vec<ItemId>,
1012 window: &mut Window,
1013 cx: &mut App,
1014 ) -> Task<Result<()>> {
1015 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1016 return Task::ready(Err(anyhow!(
1017 "cannot cleanup {}, descriptor not found",
1018 item_kind
1019 )));
1020 };
1021
1022 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
1023 }
1024
1025 fn view_to_serializable_item_handle(
1026 view: AnyView,
1027 cx: &App,
1028 ) -> Option<Box<dyn SerializableItemHandle>> {
1029 let this = cx.try_global::<Self>()?;
1030 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
1031 Some((descriptor.view_to_serializable_item)(view))
1032 }
1033
1034 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
1035 let this = cx.try_global::<Self>()?;
1036 this.descriptors_by_kind.get(item_kind).copied()
1037 }
1038}
1039
1040pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
1041 let serialized_item_kind = I::serialized_item_kind();
1042
1043 let registry = cx.default_global::<SerializableItemRegistry>();
1044 let descriptor = SerializableItemDescriptor {
1045 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
1046 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
1047 cx.foreground_executor()
1048 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
1049 },
1050 cleanup: |workspace_id, loaded_items, window, cx| {
1051 I::cleanup(workspace_id, loaded_items, window, cx)
1052 },
1053 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
1054 };
1055 registry
1056 .descriptors_by_kind
1057 .insert(Arc::from(serialized_item_kind), descriptor);
1058 registry
1059 .descriptors_by_type
1060 .insert(TypeId::of::<I>(), descriptor);
1061}
1062
1063pub struct AppState {
1064 pub languages: Arc<LanguageRegistry>,
1065 pub client: Arc<Client>,
1066 pub user_store: Entity<UserStore>,
1067 pub workspace_store: Entity<WorkspaceStore>,
1068 pub fs: Arc<dyn fs::Fs>,
1069 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1070 pub node_runtime: NodeRuntime,
1071 pub session: Entity<AppSession>,
1072}
1073
1074struct GlobalAppState(Weak<AppState>);
1075
1076impl Global for GlobalAppState {}
1077
1078pub struct WorkspaceStore {
1079 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1080 client: Arc<Client>,
1081 _subscriptions: Vec<client::Subscription>,
1082}
1083
1084#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1085pub enum CollaboratorId {
1086 PeerId(PeerId),
1087 Agent,
1088}
1089
1090impl From<PeerId> for CollaboratorId {
1091 fn from(peer_id: PeerId) -> Self {
1092 CollaboratorId::PeerId(peer_id)
1093 }
1094}
1095
1096impl From<&PeerId> for CollaboratorId {
1097 fn from(peer_id: &PeerId) -> Self {
1098 CollaboratorId::PeerId(*peer_id)
1099 }
1100}
1101
1102#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1103struct Follower {
1104 project_id: Option<u64>,
1105 peer_id: PeerId,
1106}
1107
1108impl AppState {
1109 #[track_caller]
1110 pub fn global(cx: &App) -> Weak<Self> {
1111 cx.global::<GlobalAppState>().0.clone()
1112 }
1113 pub fn try_global(cx: &App) -> Option<Weak<Self>> {
1114 cx.try_global::<GlobalAppState>()
1115 .map(|state| state.0.clone())
1116 }
1117 pub fn set_global(state: Weak<AppState>, cx: &mut App) {
1118 cx.set_global(GlobalAppState(state));
1119 }
1120
1121 #[cfg(any(test, feature = "test-support"))]
1122 pub fn test(cx: &mut App) -> Arc<Self> {
1123 use fs::Fs;
1124 use node_runtime::NodeRuntime;
1125 use session::Session;
1126 use settings::SettingsStore;
1127
1128 if !cx.has_global::<SettingsStore>() {
1129 let settings_store = SettingsStore::test(cx);
1130 cx.set_global(settings_store);
1131 }
1132
1133 let fs = fs::FakeFs::new(cx.background_executor().clone());
1134 <dyn Fs>::set_global(fs.clone(), cx);
1135 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1136 let clock = Arc::new(clock::FakeSystemClock::new());
1137 let http_client = http_client::FakeHttpClient::with_404_response();
1138 let client = Client::new(clock, http_client, cx);
1139 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1140 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1141 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1142
1143 theme::init(theme::LoadThemes::JustBase, cx);
1144 client::init(&client, cx);
1145
1146 Arc::new(Self {
1147 client,
1148 fs,
1149 languages,
1150 user_store,
1151 workspace_store,
1152 node_runtime: NodeRuntime::unavailable(),
1153 build_window_options: |_, _| Default::default(),
1154 session,
1155 })
1156 }
1157}
1158
1159struct DelayedDebouncedEditAction {
1160 task: Option<Task<()>>,
1161 cancel_channel: Option<oneshot::Sender<()>>,
1162}
1163
1164impl DelayedDebouncedEditAction {
1165 fn new() -> DelayedDebouncedEditAction {
1166 DelayedDebouncedEditAction {
1167 task: None,
1168 cancel_channel: None,
1169 }
1170 }
1171
1172 fn fire_new<F>(
1173 &mut self,
1174 delay: Duration,
1175 window: &mut Window,
1176 cx: &mut Context<Workspace>,
1177 func: F,
1178 ) where
1179 F: 'static
1180 + Send
1181 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1182 {
1183 if let Some(channel) = self.cancel_channel.take() {
1184 _ = channel.send(());
1185 }
1186
1187 let (sender, mut receiver) = oneshot::channel::<()>();
1188 self.cancel_channel = Some(sender);
1189
1190 let previous_task = self.task.take();
1191 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1192 let mut timer = cx.background_executor().timer(delay).fuse();
1193 if let Some(previous_task) = previous_task {
1194 previous_task.await;
1195 }
1196
1197 futures::select_biased! {
1198 _ = receiver => return,
1199 _ = timer => {}
1200 }
1201
1202 if let Some(result) = workspace
1203 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1204 .log_err()
1205 {
1206 result.await.log_err();
1207 }
1208 }));
1209 }
1210}
1211
1212pub enum Event {
1213 PaneAdded(Entity<Pane>),
1214 PaneRemoved,
1215 ItemAdded {
1216 item: Box<dyn ItemHandle>,
1217 },
1218 ActiveItemChanged,
1219 ItemRemoved {
1220 item_id: EntityId,
1221 },
1222 UserSavedItem {
1223 pane: WeakEntity<Pane>,
1224 item: Box<dyn WeakItemHandle>,
1225 save_intent: SaveIntent,
1226 },
1227 ContactRequestedJoin(u64),
1228 WorkspaceCreated(WeakEntity<Workspace>),
1229 OpenBundledFile {
1230 text: Cow<'static, str>,
1231 title: &'static str,
1232 language: &'static str,
1233 },
1234 ZoomChanged,
1235 ModalOpened,
1236 Activate,
1237 PanelAdded(AnyView),
1238}
1239
1240#[derive(Debug, Clone)]
1241pub enum OpenVisible {
1242 All,
1243 None,
1244 OnlyFiles,
1245 OnlyDirectories,
1246}
1247
1248enum WorkspaceLocation {
1249 // Valid local paths or SSH project to serialize
1250 Location(SerializedWorkspaceLocation, PathList),
1251 // No valid location found hence clear session id
1252 DetachFromSession,
1253 // No valid location found to serialize
1254 None,
1255}
1256
1257type PromptForNewPath = Box<
1258 dyn Fn(
1259 &mut Workspace,
1260 DirectoryLister,
1261 Option<String>,
1262 &mut Window,
1263 &mut Context<Workspace>,
1264 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1265>;
1266
1267type PromptForOpenPath = Box<
1268 dyn Fn(
1269 &mut Workspace,
1270 DirectoryLister,
1271 &mut Window,
1272 &mut Context<Workspace>,
1273 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1274>;
1275
1276#[derive(Default)]
1277struct DispatchingKeystrokes {
1278 dispatched: HashSet<Vec<Keystroke>>,
1279 queue: VecDeque<Keystroke>,
1280 task: Option<Shared<Task<()>>>,
1281}
1282
1283/// Collects everything project-related for a certain window opened.
1284/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1285///
1286/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1287/// The `Workspace` owns everybody's state and serves as a default, "global context",
1288/// that can be used to register a global action to be triggered from any place in the window.
1289pub struct Workspace {
1290 weak_self: WeakEntity<Self>,
1291 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1292 zoomed: Option<AnyWeakView>,
1293 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1294 zoomed_position: Option<DockPosition>,
1295 center: PaneGroup,
1296 left_dock: Entity<Dock>,
1297 bottom_dock: Entity<Dock>,
1298 right_dock: Entity<Dock>,
1299 panes: Vec<Entity<Pane>>,
1300 active_worktree_override: Option<WorktreeId>,
1301 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1302 active_pane: Entity<Pane>,
1303 last_active_center_pane: Option<WeakEntity<Pane>>,
1304 last_active_view_id: Option<proto::ViewId>,
1305 status_bar: Entity<StatusBar>,
1306 pub(crate) modal_layer: Entity<ModalLayer>,
1307 toast_layer: Entity<ToastLayer>,
1308 titlebar_item: Option<AnyView>,
1309 notifications: Notifications,
1310 suppressed_notifications: HashSet<NotificationId>,
1311 project: Entity<Project>,
1312 follower_states: HashMap<CollaboratorId, FollowerState>,
1313 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1314 window_edited: bool,
1315 last_window_title: Option<String>,
1316 dirty_items: HashMap<EntityId, Subscription>,
1317 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1318 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1319 database_id: Option<WorkspaceId>,
1320 app_state: Arc<AppState>,
1321 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1322 _subscriptions: Vec<Subscription>,
1323 _apply_leader_updates: Task<Result<()>>,
1324 _observe_current_user: Task<Result<()>>,
1325 _schedule_serialize_workspace: Option<Task<()>>,
1326 _serialize_workspace_task: Option<Task<()>>,
1327 _schedule_serialize_ssh_paths: Option<Task<()>>,
1328 pane_history_timestamp: Arc<AtomicUsize>,
1329 bounds: Bounds<Pixels>,
1330 pub centered_layout: bool,
1331 bounds_save_task_queued: Option<Task<()>>,
1332 on_prompt_for_new_path: Option<PromptForNewPath>,
1333 on_prompt_for_open_path: Option<PromptForOpenPath>,
1334 terminal_provider: Option<Box<dyn TerminalProvider>>,
1335 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1336 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1337 _items_serializer: Task<Result<()>>,
1338 session_id: Option<String>,
1339 scheduled_tasks: Vec<Task<()>>,
1340 last_open_dock_positions: Vec<DockPosition>,
1341 removing: bool,
1342 _panels_task: Option<Task<Result<()>>>,
1343 sidebar_focus_handle: Option<FocusHandle>,
1344}
1345
1346impl EventEmitter<Event> for Workspace {}
1347
1348#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1349pub struct ViewId {
1350 pub creator: CollaboratorId,
1351 pub id: u64,
1352}
1353
1354pub struct FollowerState {
1355 center_pane: Entity<Pane>,
1356 dock_pane: Option<Entity<Pane>>,
1357 active_view_id: Option<ViewId>,
1358 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1359}
1360
1361struct FollowerView {
1362 view: Box<dyn FollowableItemHandle>,
1363 location: Option<proto::PanelId>,
1364}
1365
1366impl Workspace {
1367 pub fn new(
1368 workspace_id: Option<WorkspaceId>,
1369 project: Entity<Project>,
1370 app_state: Arc<AppState>,
1371 window: &mut Window,
1372 cx: &mut Context<Self>,
1373 ) -> Self {
1374 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1375 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1376 if let TrustedWorktreesEvent::Trusted(..) = e {
1377 // Do not persist auto trusted worktrees
1378 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1379 worktrees_store.update(cx, |worktrees_store, cx| {
1380 worktrees_store.schedule_serialization(
1381 cx,
1382 |new_trusted_worktrees, cx| {
1383 let timeout =
1384 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1385 let db = WorkspaceDb::global(cx);
1386 cx.background_spawn(async move {
1387 timeout.await;
1388 db.save_trusted_worktrees(new_trusted_worktrees)
1389 .await
1390 .log_err();
1391 })
1392 },
1393 )
1394 });
1395 }
1396 }
1397 })
1398 .detach();
1399
1400 cx.observe_global::<SettingsStore>(|_, cx| {
1401 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1402 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1403 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1404 trusted_worktrees.auto_trust_all(cx);
1405 })
1406 }
1407 }
1408 })
1409 .detach();
1410 }
1411
1412 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1413 match event {
1414 project::Event::RemoteIdChanged(_) => {
1415 this.update_window_title(window, cx);
1416 }
1417
1418 project::Event::CollaboratorLeft(peer_id) => {
1419 this.collaborator_left(*peer_id, window, cx);
1420 }
1421
1422 &project::Event::WorktreeRemoved(id) | &project::Event::WorktreeAdded(id) => {
1423 this.update_window_title(window, cx);
1424 if this
1425 .project()
1426 .read(cx)
1427 .worktree_for_id(id, cx)
1428 .is_some_and(|wt| wt.read(cx).is_visible())
1429 {
1430 this.serialize_workspace(window, cx);
1431 this.update_history(cx);
1432 }
1433 }
1434 project::Event::WorktreeUpdatedEntries(..) => {
1435 this.update_window_title(window, cx);
1436 this.serialize_workspace(window, cx);
1437 }
1438
1439 project::Event::DisconnectedFromHost => {
1440 this.update_window_edited(window, cx);
1441 let leaders_to_unfollow =
1442 this.follower_states.keys().copied().collect::<Vec<_>>();
1443 for leader_id in leaders_to_unfollow {
1444 this.unfollow(leader_id, window, cx);
1445 }
1446 }
1447
1448 project::Event::DisconnectedFromRemote {
1449 server_not_running: _,
1450 } => {
1451 this.update_window_edited(window, cx);
1452 }
1453
1454 project::Event::Closed => {
1455 window.remove_window();
1456 }
1457
1458 project::Event::DeletedEntry(_, entry_id) => {
1459 for pane in this.panes.iter() {
1460 pane.update(cx, |pane, cx| {
1461 pane.handle_deleted_project_item(*entry_id, window, cx)
1462 });
1463 }
1464 }
1465
1466 project::Event::Toast {
1467 notification_id,
1468 message,
1469 link,
1470 } => this.show_notification(
1471 NotificationId::named(notification_id.clone()),
1472 cx,
1473 |cx| {
1474 let mut notification = MessageNotification::new(message.clone(), cx);
1475 if let Some(link) = link {
1476 notification = notification
1477 .more_info_message(link.label)
1478 .more_info_url(link.url);
1479 }
1480
1481 cx.new(|_| notification)
1482 },
1483 ),
1484
1485 project::Event::HideToast { notification_id } => {
1486 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1487 }
1488
1489 project::Event::LanguageServerPrompt(request) => {
1490 struct LanguageServerPrompt;
1491
1492 this.show_notification(
1493 NotificationId::composite::<LanguageServerPrompt>(request.id),
1494 cx,
1495 |cx| {
1496 cx.new(|cx| {
1497 notifications::LanguageServerPrompt::new(request.clone(), cx)
1498 })
1499 },
1500 );
1501 }
1502
1503 project::Event::AgentLocationChanged => {
1504 this.handle_agent_location_changed(window, cx)
1505 }
1506
1507 _ => {}
1508 }
1509 cx.notify()
1510 })
1511 .detach();
1512
1513 cx.subscribe_in(
1514 &project.read(cx).breakpoint_store(),
1515 window,
1516 |workspace, _, event, window, cx| match event {
1517 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1518 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1519 workspace.serialize_workspace(window, cx);
1520 }
1521 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1522 },
1523 )
1524 .detach();
1525 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1526 cx.subscribe_in(
1527 &toolchain_store,
1528 window,
1529 |workspace, _, event, window, cx| match event {
1530 ToolchainStoreEvent::CustomToolchainsModified => {
1531 workspace.serialize_workspace(window, cx);
1532 }
1533 _ => {}
1534 },
1535 )
1536 .detach();
1537 }
1538
1539 cx.on_focus_lost(window, |this, window, cx| {
1540 let focus_handle = this.focus_handle(cx);
1541 window.focus(&focus_handle, cx);
1542 })
1543 .detach();
1544
1545 let weak_handle = cx.entity().downgrade();
1546 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1547
1548 let center_pane = cx.new(|cx| {
1549 let mut center_pane = Pane::new(
1550 weak_handle.clone(),
1551 project.clone(),
1552 pane_history_timestamp.clone(),
1553 None,
1554 NewFile.boxed_clone(),
1555 true,
1556 window,
1557 cx,
1558 );
1559 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1560 center_pane.set_should_display_welcome_page(true);
1561 center_pane
1562 });
1563 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1564 .detach();
1565
1566 window.focus(¢er_pane.focus_handle(cx), cx);
1567
1568 cx.emit(Event::PaneAdded(center_pane.clone()));
1569
1570 let any_window_handle = window.window_handle();
1571 app_state.workspace_store.update(cx, |store, _| {
1572 store
1573 .workspaces
1574 .insert((any_window_handle, weak_handle.clone()));
1575 });
1576
1577 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1578 let mut connection_status = app_state.client.status();
1579 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1580 current_user.next().await;
1581 connection_status.next().await;
1582 let mut stream =
1583 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1584
1585 while stream.recv().await.is_some() {
1586 this.update(cx, |_, cx| cx.notify())?;
1587 }
1588 anyhow::Ok(())
1589 });
1590
1591 // All leader updates are enqueued and then processed in a single task, so
1592 // that each asynchronous operation can be run in order.
1593 let (leader_updates_tx, mut leader_updates_rx) =
1594 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1595 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1596 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1597 Self::process_leader_update(&this, leader_id, update, cx)
1598 .await
1599 .log_err();
1600 }
1601
1602 Ok(())
1603 });
1604
1605 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1606 let modal_layer = cx.new(|_| ModalLayer::new());
1607 let toast_layer = cx.new(|_| ToastLayer::new());
1608 cx.subscribe(
1609 &modal_layer,
1610 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1611 cx.emit(Event::ModalOpened);
1612 },
1613 )
1614 .detach();
1615
1616 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1617 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1618 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1619 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1620 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1621 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1622 let status_bar = cx.new(|cx| {
1623 let mut status_bar = StatusBar::new(¢er_pane.clone(), window, cx);
1624 status_bar.add_left_item(left_dock_buttons, window, cx);
1625 status_bar.add_right_item(right_dock_buttons, window, cx);
1626 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1627 status_bar
1628 });
1629
1630 let session_id = app_state.session.read(cx).id().to_owned();
1631
1632 let mut active_call = None;
1633 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1634 let subscriptions =
1635 vec![
1636 call.0
1637 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1638 ];
1639 active_call = Some((call, subscriptions));
1640 }
1641
1642 let (serializable_items_tx, serializable_items_rx) =
1643 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1644 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1645 Self::serialize_items(&this, serializable_items_rx, cx).await
1646 });
1647
1648 let subscriptions = vec![
1649 cx.observe_window_activation(window, Self::on_window_activation_changed),
1650 cx.observe_window_bounds(window, move |this, window, cx| {
1651 if this.bounds_save_task_queued.is_some() {
1652 return;
1653 }
1654 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1655 cx.background_executor()
1656 .timer(Duration::from_millis(100))
1657 .await;
1658 this.update_in(cx, |this, window, cx| {
1659 this.save_window_bounds(window, cx).detach();
1660 this.bounds_save_task_queued.take();
1661 })
1662 .ok();
1663 }));
1664 cx.notify();
1665 }),
1666 cx.observe_window_appearance(window, |_, window, cx| {
1667 let window_appearance = window.appearance();
1668
1669 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1670
1671 GlobalTheme::reload_theme(cx);
1672 GlobalTheme::reload_icon_theme(cx);
1673 }),
1674 cx.on_release({
1675 let weak_handle = weak_handle.clone();
1676 move |this, cx| {
1677 this.app_state.workspace_store.update(cx, move |store, _| {
1678 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1679 })
1680 }
1681 }),
1682 ];
1683
1684 cx.defer_in(window, move |this, window, cx| {
1685 this.update_window_title(window, cx);
1686 this.show_initial_notifications(cx);
1687 });
1688
1689 let mut center = PaneGroup::new(center_pane.clone());
1690 center.set_is_center(true);
1691 center.mark_positions(cx);
1692
1693 Workspace {
1694 weak_self: weak_handle.clone(),
1695 zoomed: None,
1696 zoomed_position: None,
1697 previous_dock_drag_coordinates: None,
1698 center,
1699 panes: vec![center_pane.clone()],
1700 panes_by_item: Default::default(),
1701 active_pane: center_pane.clone(),
1702 last_active_center_pane: Some(center_pane.downgrade()),
1703 last_active_view_id: None,
1704 status_bar,
1705 modal_layer,
1706 toast_layer,
1707 titlebar_item: None,
1708 active_worktree_override: None,
1709 notifications: Notifications::default(),
1710 suppressed_notifications: HashSet::default(),
1711 left_dock,
1712 bottom_dock,
1713 right_dock,
1714 _panels_task: None,
1715 project: project.clone(),
1716 follower_states: Default::default(),
1717 last_leaders_by_pane: Default::default(),
1718 dispatching_keystrokes: Default::default(),
1719 window_edited: false,
1720 last_window_title: None,
1721 dirty_items: Default::default(),
1722 active_call,
1723 database_id: workspace_id,
1724 app_state,
1725 _observe_current_user,
1726 _apply_leader_updates,
1727 _schedule_serialize_workspace: None,
1728 _serialize_workspace_task: None,
1729 _schedule_serialize_ssh_paths: None,
1730 leader_updates_tx,
1731 _subscriptions: subscriptions,
1732 pane_history_timestamp,
1733 workspace_actions: Default::default(),
1734 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1735 bounds: Default::default(),
1736 centered_layout: false,
1737 bounds_save_task_queued: None,
1738 on_prompt_for_new_path: None,
1739 on_prompt_for_open_path: None,
1740 terminal_provider: None,
1741 debugger_provider: None,
1742 serializable_items_tx,
1743 _items_serializer,
1744 session_id: Some(session_id),
1745
1746 scheduled_tasks: Vec::new(),
1747 last_open_dock_positions: Vec::new(),
1748 removing: false,
1749 sidebar_focus_handle: None,
1750 }
1751 }
1752
1753 pub fn new_local(
1754 abs_paths: Vec<PathBuf>,
1755 app_state: Arc<AppState>,
1756 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1757 env: Option<HashMap<String, String>>,
1758 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1759 activate: bool,
1760 cx: &mut App,
1761 ) -> Task<anyhow::Result<OpenResult>> {
1762 let project_handle = Project::local(
1763 app_state.client.clone(),
1764 app_state.node_runtime.clone(),
1765 app_state.user_store.clone(),
1766 app_state.languages.clone(),
1767 app_state.fs.clone(),
1768 env,
1769 Default::default(),
1770 cx,
1771 );
1772
1773 let db = WorkspaceDb::global(cx);
1774 let kvp = db::kvp::KeyValueStore::global(cx);
1775 cx.spawn(async move |cx| {
1776 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1777 for path in abs_paths.into_iter() {
1778 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1779 paths_to_open.push(canonical)
1780 } else {
1781 paths_to_open.push(path)
1782 }
1783 }
1784
1785 let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
1786
1787 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1788 paths_to_open = paths.ordered_paths().cloned().collect();
1789 if !paths.is_lexicographically_ordered() {
1790 project_handle.update(cx, |project, cx| {
1791 project.set_worktrees_reordered(true, cx);
1792 });
1793 }
1794 }
1795
1796 // Get project paths for all of the abs_paths
1797 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1798 Vec::with_capacity(paths_to_open.len());
1799
1800 for path in paths_to_open.into_iter() {
1801 if let Some((_, project_entry)) = cx
1802 .update(|cx| {
1803 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1804 })
1805 .await
1806 .log_err()
1807 {
1808 project_paths.push((path, Some(project_entry)));
1809 } else {
1810 project_paths.push((path, None));
1811 }
1812 }
1813
1814 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1815 serialized_workspace.id
1816 } else {
1817 db.next_id().await.unwrap_or_else(|_| Default::default())
1818 };
1819
1820 let toolchains = db.toolchains(workspace_id).await?;
1821
1822 for (toolchain, worktree_path, path) in toolchains {
1823 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1824 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1825 this.find_worktree(&worktree_path, cx)
1826 .and_then(|(worktree, rel_path)| {
1827 if rel_path.is_empty() {
1828 Some(worktree.read(cx).id())
1829 } else {
1830 None
1831 }
1832 })
1833 }) else {
1834 // We did not find a worktree with a given path, but that's whatever.
1835 continue;
1836 };
1837 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1838 continue;
1839 }
1840
1841 project_handle
1842 .update(cx, |this, cx| {
1843 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1844 })
1845 .await;
1846 }
1847 if let Some(workspace) = serialized_workspace.as_ref() {
1848 project_handle.update(cx, |this, cx| {
1849 for (scope, toolchains) in &workspace.user_toolchains {
1850 for toolchain in toolchains {
1851 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1852 }
1853 }
1854 });
1855 }
1856
1857 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1858 if let Some(window) = requesting_window {
1859 let centered_layout = serialized_workspace
1860 .as_ref()
1861 .map(|w| w.centered_layout)
1862 .unwrap_or(false);
1863
1864 let workspace = window.update(cx, |multi_workspace, window, cx| {
1865 let workspace = cx.new(|cx| {
1866 let mut workspace = Workspace::new(
1867 Some(workspace_id),
1868 project_handle.clone(),
1869 app_state.clone(),
1870 window,
1871 cx,
1872 );
1873
1874 workspace.centered_layout = centered_layout;
1875
1876 // Call init callback to add items before window renders
1877 if let Some(init) = init {
1878 init(&mut workspace, window, cx);
1879 }
1880
1881 workspace
1882 });
1883 if activate {
1884 multi_workspace.activate(workspace.clone(), cx);
1885 } else {
1886 multi_workspace.add_workspace(workspace.clone(), cx);
1887 }
1888 workspace
1889 })?;
1890 (window, workspace)
1891 } else {
1892 let window_bounds_override = window_bounds_env_override();
1893
1894 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1895 (Some(WindowBounds::Windowed(bounds)), None)
1896 } else if let Some(workspace) = serialized_workspace.as_ref()
1897 && let Some(display) = workspace.display
1898 && let Some(bounds) = workspace.window_bounds.as_ref()
1899 {
1900 // Reopening an existing workspace - restore its saved bounds
1901 (Some(bounds.0), Some(display))
1902 } else if let Some((display, bounds)) =
1903 persistence::read_default_window_bounds(&kvp)
1904 {
1905 // New or empty workspace - use the last known window bounds
1906 (Some(bounds), Some(display))
1907 } else {
1908 // New window - let GPUI's default_bounds() handle cascading
1909 (None, None)
1910 };
1911
1912 // Use the serialized workspace to construct the new window
1913 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1914 options.window_bounds = window_bounds;
1915 let centered_layout = serialized_workspace
1916 .as_ref()
1917 .map(|w| w.centered_layout)
1918 .unwrap_or(false);
1919 let window = cx.open_window(options, {
1920 let app_state = app_state.clone();
1921 let project_handle = project_handle.clone();
1922 move |window, cx| {
1923 let workspace = cx.new(|cx| {
1924 let mut workspace = Workspace::new(
1925 Some(workspace_id),
1926 project_handle,
1927 app_state,
1928 window,
1929 cx,
1930 );
1931 workspace.centered_layout = centered_layout;
1932
1933 // Call init callback to add items before window renders
1934 if let Some(init) = init {
1935 init(&mut workspace, window, cx);
1936 }
1937
1938 workspace
1939 });
1940 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1941 }
1942 })?;
1943 let workspace =
1944 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
1945 multi_workspace.workspace().clone()
1946 })?;
1947 (window, workspace)
1948 };
1949
1950 notify_if_database_failed(window, cx);
1951 // Check if this is an empty workspace (no paths to open)
1952 // An empty workspace is one where project_paths is empty
1953 let is_empty_workspace = project_paths.is_empty();
1954 // Check if serialized workspace has paths before it's moved
1955 let serialized_workspace_has_paths = serialized_workspace
1956 .as_ref()
1957 .map(|ws| !ws.paths.is_empty())
1958 .unwrap_or(false);
1959
1960 let opened_items = window
1961 .update(cx, |_, window, cx| {
1962 workspace.update(cx, |_workspace: &mut Workspace, cx| {
1963 open_items(serialized_workspace, project_paths, window, cx)
1964 })
1965 })?
1966 .await
1967 .unwrap_or_default();
1968
1969 // Restore default dock state for empty workspaces
1970 // Only restore if:
1971 // 1. This is an empty workspace (no paths), AND
1972 // 2. The serialized workspace either doesn't exist or has no paths
1973 if is_empty_workspace && !serialized_workspace_has_paths {
1974 if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
1975 window
1976 .update(cx, |_, window, cx| {
1977 workspace.update(cx, |workspace, cx| {
1978 for (dock, serialized_dock) in [
1979 (&workspace.right_dock, &default_docks.right),
1980 (&workspace.left_dock, &default_docks.left),
1981 (&workspace.bottom_dock, &default_docks.bottom),
1982 ] {
1983 dock.update(cx, |dock, cx| {
1984 dock.serialized_dock = Some(serialized_dock.clone());
1985 dock.restore_state(window, cx);
1986 });
1987 }
1988 cx.notify();
1989 });
1990 })
1991 .log_err();
1992 }
1993 }
1994
1995 window
1996 .update(cx, |_, _window, cx| {
1997 workspace.update(cx, |this: &mut Workspace, cx| {
1998 this.update_history(cx);
1999 });
2000 })
2001 .log_err();
2002 Ok(OpenResult {
2003 window,
2004 workspace,
2005 opened_items,
2006 })
2007 })
2008 }
2009
2010 pub fn weak_handle(&self) -> WeakEntity<Self> {
2011 self.weak_self.clone()
2012 }
2013
2014 pub fn left_dock(&self) -> &Entity<Dock> {
2015 &self.left_dock
2016 }
2017
2018 pub fn bottom_dock(&self) -> &Entity<Dock> {
2019 &self.bottom_dock
2020 }
2021
2022 pub fn set_bottom_dock_layout(
2023 &mut self,
2024 layout: BottomDockLayout,
2025 window: &mut Window,
2026 cx: &mut Context<Self>,
2027 ) {
2028 let fs = self.project().read(cx).fs();
2029 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2030 content.workspace.bottom_dock_layout = Some(layout);
2031 });
2032
2033 cx.notify();
2034 self.serialize_workspace(window, cx);
2035 }
2036
2037 pub fn right_dock(&self) -> &Entity<Dock> {
2038 &self.right_dock
2039 }
2040
2041 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2042 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2043 }
2044
2045 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2046 let left_dock = self.left_dock.read(cx);
2047 let left_visible = left_dock.is_open();
2048 let left_active_panel = left_dock
2049 .active_panel()
2050 .map(|panel| panel.persistent_name().to_string());
2051 // `zoomed_position` is kept in sync with individual panel zoom state
2052 // by the dock code in `Dock::new` and `Dock::add_panel`.
2053 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2054
2055 let right_dock = self.right_dock.read(cx);
2056 let right_visible = right_dock.is_open();
2057 let right_active_panel = right_dock
2058 .active_panel()
2059 .map(|panel| panel.persistent_name().to_string());
2060 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2061
2062 let bottom_dock = self.bottom_dock.read(cx);
2063 let bottom_visible = bottom_dock.is_open();
2064 let bottom_active_panel = bottom_dock
2065 .active_panel()
2066 .map(|panel| panel.persistent_name().to_string());
2067 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2068
2069 DockStructure {
2070 left: DockData {
2071 visible: left_visible,
2072 active_panel: left_active_panel,
2073 zoom: left_dock_zoom,
2074 },
2075 right: DockData {
2076 visible: right_visible,
2077 active_panel: right_active_panel,
2078 zoom: right_dock_zoom,
2079 },
2080 bottom: DockData {
2081 visible: bottom_visible,
2082 active_panel: bottom_active_panel,
2083 zoom: bottom_dock_zoom,
2084 },
2085 }
2086 }
2087
2088 pub fn set_dock_structure(
2089 &self,
2090 docks: DockStructure,
2091 window: &mut Window,
2092 cx: &mut Context<Self>,
2093 ) {
2094 for (dock, data) in [
2095 (&self.left_dock, docks.left),
2096 (&self.bottom_dock, docks.bottom),
2097 (&self.right_dock, docks.right),
2098 ] {
2099 dock.update(cx, |dock, cx| {
2100 dock.serialized_dock = Some(data);
2101 dock.restore_state(window, cx);
2102 });
2103 }
2104 }
2105
2106 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2107 self.items(cx)
2108 .filter_map(|item| {
2109 let project_path = item.project_path(cx)?;
2110 self.project.read(cx).absolute_path(&project_path, cx)
2111 })
2112 .collect()
2113 }
2114
2115 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2116 match position {
2117 DockPosition::Left => &self.left_dock,
2118 DockPosition::Bottom => &self.bottom_dock,
2119 DockPosition::Right => &self.right_dock,
2120 }
2121 }
2122
2123 pub fn is_edited(&self) -> bool {
2124 self.window_edited
2125 }
2126
2127 pub fn add_panel<T: Panel>(
2128 &mut self,
2129 panel: Entity<T>,
2130 window: &mut Window,
2131 cx: &mut Context<Self>,
2132 ) {
2133 let focus_handle = panel.panel_focus_handle(cx);
2134 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2135 .detach();
2136
2137 let dock_position = panel.position(window, cx);
2138 let dock = self.dock_at_position(dock_position);
2139 let any_panel = panel.to_any();
2140
2141 dock.update(cx, |dock, cx| {
2142 dock.add_panel(panel, self.weak_self.clone(), window, cx)
2143 });
2144
2145 cx.emit(Event::PanelAdded(any_panel));
2146 }
2147
2148 pub fn remove_panel<T: Panel>(
2149 &mut self,
2150 panel: &Entity<T>,
2151 window: &mut Window,
2152 cx: &mut Context<Self>,
2153 ) {
2154 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2155 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2156 }
2157 }
2158
2159 pub fn status_bar(&self) -> &Entity<StatusBar> {
2160 &self.status_bar
2161 }
2162
2163 pub fn set_workspace_sidebar_open(&self, open: bool, cx: &mut App) {
2164 self.status_bar.update(cx, |status_bar, cx| {
2165 status_bar.set_workspace_sidebar_open(open, cx);
2166 });
2167 }
2168
2169 pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
2170 self.sidebar_focus_handle = handle;
2171 }
2172
2173 pub fn status_bar_visible(&self, cx: &App) -> bool {
2174 StatusBarSettings::get_global(cx).show
2175 }
2176
2177 pub fn app_state(&self) -> &Arc<AppState> {
2178 &self.app_state
2179 }
2180
2181 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2182 self._panels_task = Some(task);
2183 }
2184
2185 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2186 self._panels_task.take()
2187 }
2188
2189 pub fn user_store(&self) -> &Entity<UserStore> {
2190 &self.app_state.user_store
2191 }
2192
2193 pub fn project(&self) -> &Entity<Project> {
2194 &self.project
2195 }
2196
2197 pub fn path_style(&self, cx: &App) -> PathStyle {
2198 self.project.read(cx).path_style(cx)
2199 }
2200
2201 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2202 let mut history: HashMap<EntityId, usize> = HashMap::default();
2203
2204 for pane_handle in &self.panes {
2205 let pane = pane_handle.read(cx);
2206
2207 for entry in pane.activation_history() {
2208 history.insert(
2209 entry.entity_id,
2210 history
2211 .get(&entry.entity_id)
2212 .cloned()
2213 .unwrap_or(0)
2214 .max(entry.timestamp),
2215 );
2216 }
2217 }
2218
2219 history
2220 }
2221
2222 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2223 let mut recent_item: Option<Entity<T>> = None;
2224 let mut recent_timestamp = 0;
2225 for pane_handle in &self.panes {
2226 let pane = pane_handle.read(cx);
2227 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2228 pane.items().map(|item| (item.item_id(), item)).collect();
2229 for entry in pane.activation_history() {
2230 if entry.timestamp > recent_timestamp
2231 && let Some(&item) = item_map.get(&entry.entity_id)
2232 && let Some(typed_item) = item.act_as::<T>(cx)
2233 {
2234 recent_timestamp = entry.timestamp;
2235 recent_item = Some(typed_item);
2236 }
2237 }
2238 }
2239 recent_item
2240 }
2241
2242 pub fn recent_navigation_history_iter(
2243 &self,
2244 cx: &App,
2245 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2246 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2247 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2248
2249 for pane in &self.panes {
2250 let pane = pane.read(cx);
2251
2252 pane.nav_history()
2253 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2254 if let Some(fs_path) = &fs_path {
2255 abs_paths_opened
2256 .entry(fs_path.clone())
2257 .or_default()
2258 .insert(project_path.clone());
2259 }
2260 let timestamp = entry.timestamp;
2261 match history.entry(project_path) {
2262 hash_map::Entry::Occupied(mut entry) => {
2263 let (_, old_timestamp) = entry.get();
2264 if ×tamp > old_timestamp {
2265 entry.insert((fs_path, timestamp));
2266 }
2267 }
2268 hash_map::Entry::Vacant(entry) => {
2269 entry.insert((fs_path, timestamp));
2270 }
2271 }
2272 });
2273
2274 if let Some(item) = pane.active_item()
2275 && let Some(project_path) = item.project_path(cx)
2276 {
2277 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2278
2279 if let Some(fs_path) = &fs_path {
2280 abs_paths_opened
2281 .entry(fs_path.clone())
2282 .or_default()
2283 .insert(project_path.clone());
2284 }
2285
2286 history.insert(project_path, (fs_path, std::usize::MAX));
2287 }
2288 }
2289
2290 history
2291 .into_iter()
2292 .sorted_by_key(|(_, (_, order))| *order)
2293 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2294 .rev()
2295 .filter(move |(history_path, abs_path)| {
2296 let latest_project_path_opened = abs_path
2297 .as_ref()
2298 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2299 .and_then(|project_paths| {
2300 project_paths
2301 .iter()
2302 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2303 });
2304
2305 latest_project_path_opened.is_none_or(|path| path == history_path)
2306 })
2307 }
2308
2309 pub fn recent_navigation_history(
2310 &self,
2311 limit: Option<usize>,
2312 cx: &App,
2313 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2314 self.recent_navigation_history_iter(cx)
2315 .take(limit.unwrap_or(usize::MAX))
2316 .collect()
2317 }
2318
2319 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2320 for pane in &self.panes {
2321 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2322 }
2323 }
2324
2325 fn navigate_history(
2326 &mut self,
2327 pane: WeakEntity<Pane>,
2328 mode: NavigationMode,
2329 window: &mut Window,
2330 cx: &mut Context<Workspace>,
2331 ) -> Task<Result<()>> {
2332 self.navigate_history_impl(
2333 pane,
2334 mode,
2335 window,
2336 &mut |history, cx| history.pop(mode, cx),
2337 cx,
2338 )
2339 }
2340
2341 fn navigate_tag_history(
2342 &mut self,
2343 pane: WeakEntity<Pane>,
2344 mode: TagNavigationMode,
2345 window: &mut Window,
2346 cx: &mut Context<Workspace>,
2347 ) -> Task<Result<()>> {
2348 self.navigate_history_impl(
2349 pane,
2350 NavigationMode::Normal,
2351 window,
2352 &mut |history, _cx| history.pop_tag(mode),
2353 cx,
2354 )
2355 }
2356
2357 fn navigate_history_impl(
2358 &mut self,
2359 pane: WeakEntity<Pane>,
2360 mode: NavigationMode,
2361 window: &mut Window,
2362 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2363 cx: &mut Context<Workspace>,
2364 ) -> Task<Result<()>> {
2365 let to_load = if let Some(pane) = pane.upgrade() {
2366 pane.update(cx, |pane, cx| {
2367 window.focus(&pane.focus_handle(cx), cx);
2368 loop {
2369 // Retrieve the weak item handle from the history.
2370 let entry = cb(pane.nav_history_mut(), cx)?;
2371
2372 // If the item is still present in this pane, then activate it.
2373 if let Some(index) = entry
2374 .item
2375 .upgrade()
2376 .and_then(|v| pane.index_for_item(v.as_ref()))
2377 {
2378 let prev_active_item_index = pane.active_item_index();
2379 pane.nav_history_mut().set_mode(mode);
2380 pane.activate_item(index, true, true, window, cx);
2381 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2382
2383 let mut navigated = prev_active_item_index != pane.active_item_index();
2384 if let Some(data) = entry.data {
2385 navigated |= pane.active_item()?.navigate(data, window, cx);
2386 }
2387
2388 if navigated {
2389 break None;
2390 }
2391 } else {
2392 // If the item is no longer present in this pane, then retrieve its
2393 // path info in order to reopen it.
2394 break pane
2395 .nav_history()
2396 .path_for_item(entry.item.id())
2397 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2398 }
2399 }
2400 })
2401 } else {
2402 None
2403 };
2404
2405 if let Some((project_path, abs_path, entry)) = to_load {
2406 // If the item was no longer present, then load it again from its previous path, first try the local path
2407 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2408
2409 cx.spawn_in(window, async move |workspace, cx| {
2410 let open_by_project_path = open_by_project_path.await;
2411 let mut navigated = false;
2412 match open_by_project_path
2413 .with_context(|| format!("Navigating to {project_path:?}"))
2414 {
2415 Ok((project_entry_id, build_item)) => {
2416 let prev_active_item_id = pane.update(cx, |pane, _| {
2417 pane.nav_history_mut().set_mode(mode);
2418 pane.active_item().map(|p| p.item_id())
2419 })?;
2420
2421 pane.update_in(cx, |pane, window, cx| {
2422 let item = pane.open_item(
2423 project_entry_id,
2424 project_path,
2425 true,
2426 entry.is_preview,
2427 true,
2428 None,
2429 window, cx,
2430 build_item,
2431 );
2432 navigated |= Some(item.item_id()) != prev_active_item_id;
2433 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2434 if let Some(data) = entry.data {
2435 navigated |= item.navigate(data, window, cx);
2436 }
2437 })?;
2438 }
2439 Err(open_by_project_path_e) => {
2440 // Fall back to opening by abs path, in case an external file was opened and closed,
2441 // and its worktree is now dropped
2442 if let Some(abs_path) = abs_path {
2443 let prev_active_item_id = pane.update(cx, |pane, _| {
2444 pane.nav_history_mut().set_mode(mode);
2445 pane.active_item().map(|p| p.item_id())
2446 })?;
2447 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2448 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2449 })?;
2450 match open_by_abs_path
2451 .await
2452 .with_context(|| format!("Navigating to {abs_path:?}"))
2453 {
2454 Ok(item) => {
2455 pane.update_in(cx, |pane, window, cx| {
2456 navigated |= Some(item.item_id()) != prev_active_item_id;
2457 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2458 if let Some(data) = entry.data {
2459 navigated |= item.navigate(data, window, cx);
2460 }
2461 })?;
2462 }
2463 Err(open_by_abs_path_e) => {
2464 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2465 }
2466 }
2467 }
2468 }
2469 }
2470
2471 if !navigated {
2472 workspace
2473 .update_in(cx, |workspace, window, cx| {
2474 Self::navigate_history(workspace, pane, mode, window, cx)
2475 })?
2476 .await?;
2477 }
2478
2479 Ok(())
2480 })
2481 } else {
2482 Task::ready(Ok(()))
2483 }
2484 }
2485
2486 pub fn go_back(
2487 &mut self,
2488 pane: WeakEntity<Pane>,
2489 window: &mut Window,
2490 cx: &mut Context<Workspace>,
2491 ) -> Task<Result<()>> {
2492 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2493 }
2494
2495 pub fn go_forward(
2496 &mut self,
2497 pane: WeakEntity<Pane>,
2498 window: &mut Window,
2499 cx: &mut Context<Workspace>,
2500 ) -> Task<Result<()>> {
2501 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2502 }
2503
2504 pub fn reopen_closed_item(
2505 &mut self,
2506 window: &mut Window,
2507 cx: &mut Context<Workspace>,
2508 ) -> Task<Result<()>> {
2509 self.navigate_history(
2510 self.active_pane().downgrade(),
2511 NavigationMode::ReopeningClosedItem,
2512 window,
2513 cx,
2514 )
2515 }
2516
2517 pub fn client(&self) -> &Arc<Client> {
2518 &self.app_state.client
2519 }
2520
2521 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2522 self.titlebar_item = Some(item);
2523 cx.notify();
2524 }
2525
2526 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2527 self.on_prompt_for_new_path = Some(prompt)
2528 }
2529
2530 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2531 self.on_prompt_for_open_path = Some(prompt)
2532 }
2533
2534 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2535 self.terminal_provider = Some(Box::new(provider));
2536 }
2537
2538 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2539 self.debugger_provider = Some(Arc::new(provider));
2540 }
2541
2542 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2543 self.debugger_provider.clone()
2544 }
2545
2546 pub fn prompt_for_open_path(
2547 &mut self,
2548 path_prompt_options: PathPromptOptions,
2549 lister: DirectoryLister,
2550 window: &mut Window,
2551 cx: &mut Context<Self>,
2552 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2553 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2554 let prompt = self.on_prompt_for_open_path.take().unwrap();
2555 let rx = prompt(self, lister, window, cx);
2556 self.on_prompt_for_open_path = Some(prompt);
2557 rx
2558 } else {
2559 let (tx, rx) = oneshot::channel();
2560 let abs_path = cx.prompt_for_paths(path_prompt_options);
2561
2562 cx.spawn_in(window, async move |workspace, cx| {
2563 let Ok(result) = abs_path.await else {
2564 return Ok(());
2565 };
2566
2567 match result {
2568 Ok(result) => {
2569 tx.send(result).ok();
2570 }
2571 Err(err) => {
2572 let rx = workspace.update_in(cx, |workspace, window, cx| {
2573 workspace.show_portal_error(err.to_string(), cx);
2574 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2575 let rx = prompt(workspace, lister, window, cx);
2576 workspace.on_prompt_for_open_path = Some(prompt);
2577 rx
2578 })?;
2579 if let Ok(path) = rx.await {
2580 tx.send(path).ok();
2581 }
2582 }
2583 };
2584 anyhow::Ok(())
2585 })
2586 .detach();
2587
2588 rx
2589 }
2590 }
2591
2592 pub fn prompt_for_new_path(
2593 &mut self,
2594 lister: DirectoryLister,
2595 suggested_name: Option<String>,
2596 window: &mut Window,
2597 cx: &mut Context<Self>,
2598 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2599 if self.project.read(cx).is_via_collab()
2600 || self.project.read(cx).is_via_remote_server()
2601 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2602 {
2603 let prompt = self.on_prompt_for_new_path.take().unwrap();
2604 let rx = prompt(self, lister, suggested_name, window, cx);
2605 self.on_prompt_for_new_path = Some(prompt);
2606 return rx;
2607 }
2608
2609 let (tx, rx) = oneshot::channel();
2610 cx.spawn_in(window, async move |workspace, cx| {
2611 let abs_path = workspace.update(cx, |workspace, cx| {
2612 let relative_to = workspace
2613 .most_recent_active_path(cx)
2614 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2615 .or_else(|| {
2616 let project = workspace.project.read(cx);
2617 project.visible_worktrees(cx).find_map(|worktree| {
2618 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2619 })
2620 })
2621 .or_else(std::env::home_dir)
2622 .unwrap_or_else(|| PathBuf::from(""));
2623 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2624 })?;
2625 let abs_path = match abs_path.await? {
2626 Ok(path) => path,
2627 Err(err) => {
2628 let rx = workspace.update_in(cx, |workspace, window, cx| {
2629 workspace.show_portal_error(err.to_string(), cx);
2630
2631 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2632 let rx = prompt(workspace, lister, suggested_name, window, cx);
2633 workspace.on_prompt_for_new_path = Some(prompt);
2634 rx
2635 })?;
2636 if let Ok(path) = rx.await {
2637 tx.send(path).ok();
2638 }
2639 return anyhow::Ok(());
2640 }
2641 };
2642
2643 tx.send(abs_path.map(|path| vec![path])).ok();
2644 anyhow::Ok(())
2645 })
2646 .detach();
2647
2648 rx
2649 }
2650
2651 pub fn titlebar_item(&self) -> Option<AnyView> {
2652 self.titlebar_item.clone()
2653 }
2654
2655 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2656 /// When set, git-related operations should use this worktree instead of deriving
2657 /// the active worktree from the focused file.
2658 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2659 self.active_worktree_override
2660 }
2661
2662 pub fn set_active_worktree_override(
2663 &mut self,
2664 worktree_id: Option<WorktreeId>,
2665 cx: &mut Context<Self>,
2666 ) {
2667 self.active_worktree_override = worktree_id;
2668 cx.notify();
2669 }
2670
2671 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2672 self.active_worktree_override = None;
2673 cx.notify();
2674 }
2675
2676 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2677 ///
2678 /// If the given workspace has a local project, then it will be passed
2679 /// to the callback. Otherwise, a new empty window will be created.
2680 pub fn with_local_workspace<T, F>(
2681 &mut self,
2682 window: &mut Window,
2683 cx: &mut Context<Self>,
2684 callback: F,
2685 ) -> Task<Result<T>>
2686 where
2687 T: 'static,
2688 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2689 {
2690 if self.project.read(cx).is_local() {
2691 Task::ready(Ok(callback(self, window, cx)))
2692 } else {
2693 let env = self.project.read(cx).cli_environment(cx);
2694 let task = Self::new_local(
2695 Vec::new(),
2696 self.app_state.clone(),
2697 None,
2698 env,
2699 None,
2700 true,
2701 cx,
2702 );
2703 cx.spawn_in(window, async move |_vh, cx| {
2704 let OpenResult {
2705 window: multi_workspace_window,
2706 ..
2707 } = task.await?;
2708 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2709 let workspace = multi_workspace.workspace().clone();
2710 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2711 })
2712 })
2713 }
2714 }
2715
2716 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2717 ///
2718 /// If the given workspace has a local project, then it will be passed
2719 /// to the callback. Otherwise, a new empty window will be created.
2720 pub fn with_local_or_wsl_workspace<T, F>(
2721 &mut self,
2722 window: &mut Window,
2723 cx: &mut Context<Self>,
2724 callback: F,
2725 ) -> Task<Result<T>>
2726 where
2727 T: 'static,
2728 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2729 {
2730 let project = self.project.read(cx);
2731 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
2732 Task::ready(Ok(callback(self, window, cx)))
2733 } else {
2734 let env = self.project.read(cx).cli_environment(cx);
2735 let task = Self::new_local(
2736 Vec::new(),
2737 self.app_state.clone(),
2738 None,
2739 env,
2740 None,
2741 true,
2742 cx,
2743 );
2744 cx.spawn_in(window, async move |_vh, cx| {
2745 let OpenResult {
2746 window: multi_workspace_window,
2747 ..
2748 } = task.await?;
2749 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2750 let workspace = multi_workspace.workspace().clone();
2751 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2752 })
2753 })
2754 }
2755 }
2756
2757 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2758 self.project.read(cx).worktrees(cx)
2759 }
2760
2761 pub fn visible_worktrees<'a>(
2762 &self,
2763 cx: &'a App,
2764 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2765 self.project.read(cx).visible_worktrees(cx)
2766 }
2767
2768 #[cfg(any(test, feature = "test-support"))]
2769 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
2770 let futures = self
2771 .worktrees(cx)
2772 .filter_map(|worktree| worktree.read(cx).as_local())
2773 .map(|worktree| worktree.scan_complete())
2774 .collect::<Vec<_>>();
2775 async move {
2776 for future in futures {
2777 future.await;
2778 }
2779 }
2780 }
2781
2782 pub fn close_global(cx: &mut App) {
2783 cx.defer(|cx| {
2784 cx.windows().iter().find(|window| {
2785 window
2786 .update(cx, |_, window, _| {
2787 if window.is_window_active() {
2788 //This can only get called when the window's project connection has been lost
2789 //so we don't need to prompt the user for anything and instead just close the window
2790 window.remove_window();
2791 true
2792 } else {
2793 false
2794 }
2795 })
2796 .unwrap_or(false)
2797 });
2798 });
2799 }
2800
2801 pub fn move_focused_panel_to_next_position(
2802 &mut self,
2803 _: &MoveFocusedPanelToNextPosition,
2804 window: &mut Window,
2805 cx: &mut Context<Self>,
2806 ) {
2807 let docks = self.all_docks();
2808 let active_dock = docks
2809 .into_iter()
2810 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
2811
2812 if let Some(dock) = active_dock {
2813 dock.update(cx, |dock, cx| {
2814 let active_panel = dock
2815 .active_panel()
2816 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
2817
2818 if let Some(panel) = active_panel {
2819 panel.move_to_next_position(window, cx);
2820 }
2821 })
2822 }
2823 }
2824
2825 pub fn prepare_to_close(
2826 &mut self,
2827 close_intent: CloseIntent,
2828 window: &mut Window,
2829 cx: &mut Context<Self>,
2830 ) -> Task<Result<bool>> {
2831 let active_call = self.active_global_call();
2832
2833 cx.spawn_in(window, async move |this, cx| {
2834 this.update(cx, |this, _| {
2835 if close_intent == CloseIntent::CloseWindow {
2836 this.removing = true;
2837 }
2838 })?;
2839
2840 let workspace_count = cx.update(|_window, cx| {
2841 cx.windows()
2842 .iter()
2843 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
2844 .count()
2845 })?;
2846
2847 #[cfg(target_os = "macos")]
2848 let save_last_workspace = false;
2849
2850 // On Linux and Windows, closing the last window should restore the last workspace.
2851 #[cfg(not(target_os = "macos"))]
2852 let save_last_workspace = {
2853 let remaining_workspaces = cx.update(|_window, cx| {
2854 cx.windows()
2855 .iter()
2856 .filter_map(|window| window.downcast::<MultiWorkspace>())
2857 .filter_map(|multi_workspace| {
2858 multi_workspace
2859 .update(cx, |multi_workspace, _, cx| {
2860 multi_workspace.workspace().read(cx).removing
2861 })
2862 .ok()
2863 })
2864 .filter(|removing| !removing)
2865 .count()
2866 })?;
2867
2868 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
2869 };
2870
2871 if let Some(active_call) = active_call
2872 && workspace_count == 1
2873 && cx
2874 .update(|_window, cx| active_call.0.is_in_room(cx))
2875 .unwrap_or(false)
2876 {
2877 if close_intent == CloseIntent::CloseWindow {
2878 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
2879 let answer = cx.update(|window, cx| {
2880 window.prompt(
2881 PromptLevel::Warning,
2882 "Do you want to leave the current call?",
2883 None,
2884 &["Close window and hang up", "Cancel"],
2885 cx,
2886 )
2887 })?;
2888
2889 if answer.await.log_err() == Some(1) {
2890 return anyhow::Ok(false);
2891 } else {
2892 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
2893 task.await.log_err();
2894 }
2895 }
2896 }
2897 if close_intent == CloseIntent::ReplaceWindow {
2898 _ = cx.update(|_window, cx| {
2899 let multi_workspace = cx
2900 .windows()
2901 .iter()
2902 .filter_map(|window| window.downcast::<MultiWorkspace>())
2903 .next()
2904 .unwrap();
2905 let project = multi_workspace
2906 .read(cx)?
2907 .workspace()
2908 .read(cx)
2909 .project
2910 .clone();
2911 if project.read(cx).is_shared() {
2912 active_call.0.unshare_project(project, cx)?;
2913 }
2914 Ok::<_, anyhow::Error>(())
2915 });
2916 }
2917 }
2918
2919 let save_result = this
2920 .update_in(cx, |this, window, cx| {
2921 this.save_all_internal(SaveIntent::Close, window, cx)
2922 })?
2923 .await;
2924
2925 // If we're not quitting, but closing, we remove the workspace from
2926 // the current session.
2927 if close_intent != CloseIntent::Quit
2928 && !save_last_workspace
2929 && save_result.as_ref().is_ok_and(|&res| res)
2930 {
2931 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
2932 .await;
2933 }
2934
2935 save_result
2936 })
2937 }
2938
2939 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
2940 self.save_all_internal(
2941 action.save_intent.unwrap_or(SaveIntent::SaveAll),
2942 window,
2943 cx,
2944 )
2945 .detach_and_log_err(cx);
2946 }
2947
2948 fn send_keystrokes(
2949 &mut self,
2950 action: &SendKeystrokes,
2951 window: &mut Window,
2952 cx: &mut Context<Self>,
2953 ) {
2954 let keystrokes: Vec<Keystroke> = action
2955 .0
2956 .split(' ')
2957 .flat_map(|k| Keystroke::parse(k).log_err())
2958 .map(|k| {
2959 cx.keyboard_mapper()
2960 .map_key_equivalent(k, false)
2961 .inner()
2962 .clone()
2963 })
2964 .collect();
2965 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
2966 }
2967
2968 pub fn send_keystrokes_impl(
2969 &mut self,
2970 keystrokes: Vec<Keystroke>,
2971 window: &mut Window,
2972 cx: &mut Context<Self>,
2973 ) -> Shared<Task<()>> {
2974 let mut state = self.dispatching_keystrokes.borrow_mut();
2975 if !state.dispatched.insert(keystrokes.clone()) {
2976 cx.propagate();
2977 return state.task.clone().unwrap();
2978 }
2979
2980 state.queue.extend(keystrokes);
2981
2982 let keystrokes = self.dispatching_keystrokes.clone();
2983 if state.task.is_none() {
2984 state.task = Some(
2985 window
2986 .spawn(cx, async move |cx| {
2987 // limit to 100 keystrokes to avoid infinite recursion.
2988 for _ in 0..100 {
2989 let keystroke = {
2990 let mut state = keystrokes.borrow_mut();
2991 let Some(keystroke) = state.queue.pop_front() else {
2992 state.dispatched.clear();
2993 state.task.take();
2994 return;
2995 };
2996 keystroke
2997 };
2998 cx.update(|window, cx| {
2999 let focused = window.focused(cx);
3000 window.dispatch_keystroke(keystroke.clone(), cx);
3001 if window.focused(cx) != focused {
3002 // dispatch_keystroke may cause the focus to change.
3003 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
3004 // And we need that to happen before the next keystroke to keep vim mode happy...
3005 // (Note that the tests always do this implicitly, so you must manually test with something like:
3006 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
3007 // )
3008 window.draw(cx).clear();
3009 }
3010 })
3011 .ok();
3012
3013 // Yield between synthetic keystrokes so deferred focus and
3014 // other effects can settle before dispatching the next key.
3015 yield_now().await;
3016 }
3017
3018 *keystrokes.borrow_mut() = Default::default();
3019 log::error!("over 100 keystrokes passed to send_keystrokes");
3020 })
3021 .shared(),
3022 );
3023 }
3024 state.task.clone().unwrap()
3025 }
3026
3027 fn save_all_internal(
3028 &mut self,
3029 mut save_intent: SaveIntent,
3030 window: &mut Window,
3031 cx: &mut Context<Self>,
3032 ) -> Task<Result<bool>> {
3033 if self.project.read(cx).is_disconnected(cx) {
3034 return Task::ready(Ok(true));
3035 }
3036 let dirty_items = self
3037 .panes
3038 .iter()
3039 .flat_map(|pane| {
3040 pane.read(cx).items().filter_map(|item| {
3041 if item.is_dirty(cx) {
3042 item.tab_content_text(0, cx);
3043 Some((pane.downgrade(), item.boxed_clone()))
3044 } else {
3045 None
3046 }
3047 })
3048 })
3049 .collect::<Vec<_>>();
3050
3051 let project = self.project.clone();
3052 cx.spawn_in(window, async move |workspace, cx| {
3053 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3054 let (serialize_tasks, remaining_dirty_items) =
3055 workspace.update_in(cx, |workspace, window, cx| {
3056 let mut remaining_dirty_items = Vec::new();
3057 let mut serialize_tasks = Vec::new();
3058 for (pane, item) in dirty_items {
3059 if let Some(task) = item
3060 .to_serializable_item_handle(cx)
3061 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3062 {
3063 serialize_tasks.push(task);
3064 } else {
3065 remaining_dirty_items.push((pane, item));
3066 }
3067 }
3068 (serialize_tasks, remaining_dirty_items)
3069 })?;
3070
3071 futures::future::try_join_all(serialize_tasks).await?;
3072
3073 if !remaining_dirty_items.is_empty() {
3074 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3075 }
3076
3077 if remaining_dirty_items.len() > 1 {
3078 let answer = workspace.update_in(cx, |_, window, cx| {
3079 let detail = Pane::file_names_for_prompt(
3080 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3081 cx,
3082 );
3083 window.prompt(
3084 PromptLevel::Warning,
3085 "Do you want to save all changes in the following files?",
3086 Some(&detail),
3087 &["Save all", "Discard all", "Cancel"],
3088 cx,
3089 )
3090 })?;
3091 match answer.await.log_err() {
3092 Some(0) => save_intent = SaveIntent::SaveAll,
3093 Some(1) => save_intent = SaveIntent::Skip,
3094 Some(2) => return Ok(false),
3095 _ => {}
3096 }
3097 }
3098
3099 remaining_dirty_items
3100 } else {
3101 dirty_items
3102 };
3103
3104 for (pane, item) in dirty_items {
3105 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3106 (
3107 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3108 item.project_entry_ids(cx),
3109 )
3110 })?;
3111 if (singleton || !project_entry_ids.is_empty())
3112 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3113 {
3114 return Ok(false);
3115 }
3116 }
3117 Ok(true)
3118 })
3119 }
3120
3121 pub fn open_workspace_for_paths(
3122 &mut self,
3123 replace_current_window: bool,
3124 paths: Vec<PathBuf>,
3125 window: &mut Window,
3126 cx: &mut Context<Self>,
3127 ) -> Task<Result<Entity<Workspace>>> {
3128 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
3129 let is_remote = self.project.read(cx).is_via_collab();
3130 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3131 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3132
3133 let window_to_replace = if replace_current_window {
3134 window_handle
3135 } else if is_remote || has_worktree || has_dirty_items {
3136 None
3137 } else {
3138 window_handle
3139 };
3140 let app_state = self.app_state.clone();
3141
3142 cx.spawn(async move |_, cx| {
3143 let OpenResult { workspace, .. } = cx
3144 .update(|cx| {
3145 open_paths(
3146 &paths,
3147 app_state,
3148 OpenOptions {
3149 replace_window: window_to_replace,
3150 ..Default::default()
3151 },
3152 cx,
3153 )
3154 })
3155 .await?;
3156 Ok(workspace)
3157 })
3158 }
3159
3160 #[allow(clippy::type_complexity)]
3161 pub fn open_paths(
3162 &mut self,
3163 mut abs_paths: Vec<PathBuf>,
3164 options: OpenOptions,
3165 pane: Option<WeakEntity<Pane>>,
3166 window: &mut Window,
3167 cx: &mut Context<Self>,
3168 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3169 let fs = self.app_state.fs.clone();
3170
3171 let caller_ordered_abs_paths = abs_paths.clone();
3172
3173 // Sort the paths to ensure we add worktrees for parents before their children.
3174 abs_paths.sort_unstable();
3175 cx.spawn_in(window, async move |this, cx| {
3176 let mut tasks = Vec::with_capacity(abs_paths.len());
3177
3178 for abs_path in &abs_paths {
3179 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3180 OpenVisible::All => Some(true),
3181 OpenVisible::None => Some(false),
3182 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3183 Some(Some(metadata)) => Some(!metadata.is_dir),
3184 Some(None) => Some(true),
3185 None => None,
3186 },
3187 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3188 Some(Some(metadata)) => Some(metadata.is_dir),
3189 Some(None) => Some(false),
3190 None => None,
3191 },
3192 };
3193 let project_path = match visible {
3194 Some(visible) => match this
3195 .update(cx, |this, cx| {
3196 Workspace::project_path_for_path(
3197 this.project.clone(),
3198 abs_path,
3199 visible,
3200 cx,
3201 )
3202 })
3203 .log_err()
3204 {
3205 Some(project_path) => project_path.await.log_err(),
3206 None => None,
3207 },
3208 None => None,
3209 };
3210
3211 let this = this.clone();
3212 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3213 let fs = fs.clone();
3214 let pane = pane.clone();
3215 let task = cx.spawn(async move |cx| {
3216 let (_worktree, project_path) = project_path?;
3217 if fs.is_dir(&abs_path).await {
3218 // Opening a directory should not race to update the active entry.
3219 // We'll select/reveal a deterministic final entry after all paths finish opening.
3220 None
3221 } else {
3222 Some(
3223 this.update_in(cx, |this, window, cx| {
3224 this.open_path(
3225 project_path,
3226 pane,
3227 options.focus.unwrap_or(true),
3228 window,
3229 cx,
3230 )
3231 })
3232 .ok()?
3233 .await,
3234 )
3235 }
3236 });
3237 tasks.push(task);
3238 }
3239
3240 let results = futures::future::join_all(tasks).await;
3241
3242 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3243 let mut winner: Option<(PathBuf, bool)> = None;
3244 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3245 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3246 if !metadata.is_dir {
3247 winner = Some((abs_path, false));
3248 break;
3249 }
3250 if winner.is_none() {
3251 winner = Some((abs_path, true));
3252 }
3253 } else if winner.is_none() {
3254 winner = Some((abs_path, false));
3255 }
3256 }
3257
3258 // Compute the winner entry id on the foreground thread and emit once, after all
3259 // paths finish opening. This avoids races between concurrently-opening paths
3260 // (directories in particular) and makes the resulting project panel selection
3261 // deterministic.
3262 if let Some((winner_abs_path, winner_is_dir)) = winner {
3263 'emit_winner: {
3264 let winner_abs_path: Arc<Path> =
3265 SanitizedPath::new(&winner_abs_path).as_path().into();
3266
3267 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3268 OpenVisible::All => true,
3269 OpenVisible::None => false,
3270 OpenVisible::OnlyFiles => !winner_is_dir,
3271 OpenVisible::OnlyDirectories => winner_is_dir,
3272 };
3273
3274 let Some(worktree_task) = this
3275 .update(cx, |workspace, cx| {
3276 workspace.project.update(cx, |project, cx| {
3277 project.find_or_create_worktree(
3278 winner_abs_path.as_ref(),
3279 visible,
3280 cx,
3281 )
3282 })
3283 })
3284 .ok()
3285 else {
3286 break 'emit_winner;
3287 };
3288
3289 let Ok((worktree, _)) = worktree_task.await else {
3290 break 'emit_winner;
3291 };
3292
3293 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3294 let worktree = worktree.read(cx);
3295 let worktree_abs_path = worktree.abs_path();
3296 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3297 worktree.root_entry()
3298 } else {
3299 winner_abs_path
3300 .strip_prefix(worktree_abs_path.as_ref())
3301 .ok()
3302 .and_then(|relative_path| {
3303 let relative_path =
3304 RelPath::new(relative_path, PathStyle::local())
3305 .log_err()?;
3306 worktree.entry_for_path(&relative_path)
3307 })
3308 }?;
3309 Some(entry.id)
3310 }) else {
3311 break 'emit_winner;
3312 };
3313
3314 this.update(cx, |workspace, cx| {
3315 workspace.project.update(cx, |_, cx| {
3316 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3317 });
3318 })
3319 .ok();
3320 }
3321 }
3322
3323 results
3324 })
3325 }
3326
3327 pub fn open_resolved_path(
3328 &mut self,
3329 path: ResolvedPath,
3330 window: &mut Window,
3331 cx: &mut Context<Self>,
3332 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3333 match path {
3334 ResolvedPath::ProjectPath { project_path, .. } => {
3335 self.open_path(project_path, None, true, window, cx)
3336 }
3337 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3338 PathBuf::from(path),
3339 OpenOptions {
3340 visible: Some(OpenVisible::None),
3341 ..Default::default()
3342 },
3343 window,
3344 cx,
3345 ),
3346 }
3347 }
3348
3349 pub fn absolute_path_of_worktree(
3350 &self,
3351 worktree_id: WorktreeId,
3352 cx: &mut Context<Self>,
3353 ) -> Option<PathBuf> {
3354 self.project
3355 .read(cx)
3356 .worktree_for_id(worktree_id, cx)
3357 // TODO: use `abs_path` or `root_dir`
3358 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3359 }
3360
3361 fn add_folder_to_project(
3362 &mut self,
3363 _: &AddFolderToProject,
3364 window: &mut Window,
3365 cx: &mut Context<Self>,
3366 ) {
3367 let project = self.project.read(cx);
3368 if project.is_via_collab() {
3369 self.show_error(
3370 &anyhow!("You cannot add folders to someone else's project"),
3371 cx,
3372 );
3373 return;
3374 }
3375 let paths = self.prompt_for_open_path(
3376 PathPromptOptions {
3377 files: false,
3378 directories: true,
3379 multiple: true,
3380 prompt: None,
3381 },
3382 DirectoryLister::Project(self.project.clone()),
3383 window,
3384 cx,
3385 );
3386 cx.spawn_in(window, async move |this, cx| {
3387 if let Some(paths) = paths.await.log_err().flatten() {
3388 let results = this
3389 .update_in(cx, |this, window, cx| {
3390 this.open_paths(
3391 paths,
3392 OpenOptions {
3393 visible: Some(OpenVisible::All),
3394 ..Default::default()
3395 },
3396 None,
3397 window,
3398 cx,
3399 )
3400 })?
3401 .await;
3402 for result in results.into_iter().flatten() {
3403 result.log_err();
3404 }
3405 }
3406 anyhow::Ok(())
3407 })
3408 .detach_and_log_err(cx);
3409 }
3410
3411 pub fn project_path_for_path(
3412 project: Entity<Project>,
3413 abs_path: &Path,
3414 visible: bool,
3415 cx: &mut App,
3416 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3417 let entry = project.update(cx, |project, cx| {
3418 project.find_or_create_worktree(abs_path, visible, cx)
3419 });
3420 cx.spawn(async move |cx| {
3421 let (worktree, path) = entry.await?;
3422 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3423 Ok((worktree, ProjectPath { worktree_id, path }))
3424 })
3425 }
3426
3427 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3428 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3429 }
3430
3431 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3432 self.items_of_type(cx).max_by_key(|item| item.item_id())
3433 }
3434
3435 pub fn items_of_type<'a, T: Item>(
3436 &'a self,
3437 cx: &'a App,
3438 ) -> impl 'a + Iterator<Item = Entity<T>> {
3439 self.panes
3440 .iter()
3441 .flat_map(|pane| pane.read(cx).items_of_type())
3442 }
3443
3444 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3445 self.active_pane().read(cx).active_item()
3446 }
3447
3448 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3449 let item = self.active_item(cx)?;
3450 item.to_any_view().downcast::<I>().ok()
3451 }
3452
3453 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3454 self.active_item(cx).and_then(|item| item.project_path(cx))
3455 }
3456
3457 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3458 self.recent_navigation_history_iter(cx)
3459 .filter_map(|(path, abs_path)| {
3460 let worktree = self
3461 .project
3462 .read(cx)
3463 .worktree_for_id(path.worktree_id, cx)?;
3464 if worktree.read(cx).is_visible() {
3465 abs_path
3466 } else {
3467 None
3468 }
3469 })
3470 .next()
3471 }
3472
3473 pub fn save_active_item(
3474 &mut self,
3475 save_intent: SaveIntent,
3476 window: &mut Window,
3477 cx: &mut App,
3478 ) -> Task<Result<()>> {
3479 let project = self.project.clone();
3480 let pane = self.active_pane();
3481 let item = pane.read(cx).active_item();
3482 let pane = pane.downgrade();
3483
3484 window.spawn(cx, async move |cx| {
3485 if let Some(item) = item {
3486 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3487 .await
3488 .map(|_| ())
3489 } else {
3490 Ok(())
3491 }
3492 })
3493 }
3494
3495 pub fn close_inactive_items_and_panes(
3496 &mut self,
3497 action: &CloseInactiveTabsAndPanes,
3498 window: &mut Window,
3499 cx: &mut Context<Self>,
3500 ) {
3501 if let Some(task) = self.close_all_internal(
3502 true,
3503 action.save_intent.unwrap_or(SaveIntent::Close),
3504 window,
3505 cx,
3506 ) {
3507 task.detach_and_log_err(cx)
3508 }
3509 }
3510
3511 pub fn close_all_items_and_panes(
3512 &mut self,
3513 action: &CloseAllItemsAndPanes,
3514 window: &mut Window,
3515 cx: &mut Context<Self>,
3516 ) {
3517 if let Some(task) = self.close_all_internal(
3518 false,
3519 action.save_intent.unwrap_or(SaveIntent::Close),
3520 window,
3521 cx,
3522 ) {
3523 task.detach_and_log_err(cx)
3524 }
3525 }
3526
3527 /// Closes the active item across all panes.
3528 pub fn close_item_in_all_panes(
3529 &mut self,
3530 action: &CloseItemInAllPanes,
3531 window: &mut Window,
3532 cx: &mut Context<Self>,
3533 ) {
3534 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3535 return;
3536 };
3537
3538 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3539 let close_pinned = action.close_pinned;
3540
3541 if let Some(project_path) = active_item.project_path(cx) {
3542 self.close_items_with_project_path(
3543 &project_path,
3544 save_intent,
3545 close_pinned,
3546 window,
3547 cx,
3548 );
3549 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3550 let item_id = active_item.item_id();
3551 self.active_pane().update(cx, |pane, cx| {
3552 pane.close_item_by_id(item_id, save_intent, window, cx)
3553 .detach_and_log_err(cx);
3554 });
3555 }
3556 }
3557
3558 /// Closes all items with the given project path across all panes.
3559 pub fn close_items_with_project_path(
3560 &mut self,
3561 project_path: &ProjectPath,
3562 save_intent: SaveIntent,
3563 close_pinned: bool,
3564 window: &mut Window,
3565 cx: &mut Context<Self>,
3566 ) {
3567 let panes = self.panes().to_vec();
3568 for pane in panes {
3569 pane.update(cx, |pane, cx| {
3570 pane.close_items_for_project_path(
3571 project_path,
3572 save_intent,
3573 close_pinned,
3574 window,
3575 cx,
3576 )
3577 .detach_and_log_err(cx);
3578 });
3579 }
3580 }
3581
3582 fn close_all_internal(
3583 &mut self,
3584 retain_active_pane: bool,
3585 save_intent: SaveIntent,
3586 window: &mut Window,
3587 cx: &mut Context<Self>,
3588 ) -> Option<Task<Result<()>>> {
3589 let current_pane = self.active_pane();
3590
3591 let mut tasks = Vec::new();
3592
3593 if retain_active_pane {
3594 let current_pane_close = current_pane.update(cx, |pane, cx| {
3595 pane.close_other_items(
3596 &CloseOtherItems {
3597 save_intent: None,
3598 close_pinned: false,
3599 },
3600 None,
3601 window,
3602 cx,
3603 )
3604 });
3605
3606 tasks.push(current_pane_close);
3607 }
3608
3609 for pane in self.panes() {
3610 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3611 continue;
3612 }
3613
3614 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3615 pane.close_all_items(
3616 &CloseAllItems {
3617 save_intent: Some(save_intent),
3618 close_pinned: false,
3619 },
3620 window,
3621 cx,
3622 )
3623 });
3624
3625 tasks.push(close_pane_items)
3626 }
3627
3628 if tasks.is_empty() {
3629 None
3630 } else {
3631 Some(cx.spawn_in(window, async move |_, _| {
3632 for task in tasks {
3633 task.await?
3634 }
3635 Ok(())
3636 }))
3637 }
3638 }
3639
3640 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3641 self.dock_at_position(position).read(cx).is_open()
3642 }
3643
3644 pub fn toggle_dock(
3645 &mut self,
3646 dock_side: DockPosition,
3647 window: &mut Window,
3648 cx: &mut Context<Self>,
3649 ) {
3650 let mut focus_center = false;
3651 let mut reveal_dock = false;
3652
3653 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3654 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3655
3656 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3657 telemetry::event!(
3658 "Panel Button Clicked",
3659 name = panel.persistent_name(),
3660 toggle_state = !was_visible
3661 );
3662 }
3663 if was_visible {
3664 self.save_open_dock_positions(cx);
3665 }
3666
3667 let dock = self.dock_at_position(dock_side);
3668 dock.update(cx, |dock, cx| {
3669 dock.set_open(!was_visible, window, cx);
3670
3671 if dock.active_panel().is_none() {
3672 let Some(panel_ix) = dock
3673 .first_enabled_panel_idx(cx)
3674 .log_with_level(log::Level::Info)
3675 else {
3676 return;
3677 };
3678 dock.activate_panel(panel_ix, window, cx);
3679 }
3680
3681 if let Some(active_panel) = dock.active_panel() {
3682 if was_visible {
3683 if active_panel
3684 .panel_focus_handle(cx)
3685 .contains_focused(window, cx)
3686 {
3687 focus_center = true;
3688 }
3689 } else {
3690 let focus_handle = &active_panel.panel_focus_handle(cx);
3691 window.focus(focus_handle, cx);
3692 reveal_dock = true;
3693 }
3694 }
3695 });
3696
3697 if reveal_dock {
3698 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3699 }
3700
3701 if focus_center {
3702 self.active_pane
3703 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3704 }
3705
3706 cx.notify();
3707 self.serialize_workspace(window, cx);
3708 }
3709
3710 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3711 self.all_docks().into_iter().find(|&dock| {
3712 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3713 })
3714 }
3715
3716 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3717 if let Some(dock) = self.active_dock(window, cx).cloned() {
3718 self.save_open_dock_positions(cx);
3719 dock.update(cx, |dock, cx| {
3720 dock.set_open(false, window, cx);
3721 });
3722 return true;
3723 }
3724 false
3725 }
3726
3727 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3728 self.save_open_dock_positions(cx);
3729 for dock in self.all_docks() {
3730 dock.update(cx, |dock, cx| {
3731 dock.set_open(false, window, cx);
3732 });
3733 }
3734
3735 cx.focus_self(window);
3736 cx.notify();
3737 self.serialize_workspace(window, cx);
3738 }
3739
3740 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
3741 self.all_docks()
3742 .into_iter()
3743 .filter_map(|dock| {
3744 let dock_ref = dock.read(cx);
3745 if dock_ref.is_open() {
3746 Some(dock_ref.position())
3747 } else {
3748 None
3749 }
3750 })
3751 .collect()
3752 }
3753
3754 /// Saves the positions of currently open docks.
3755 ///
3756 /// Updates `last_open_dock_positions` with positions of all currently open
3757 /// docks, to later be restored by the 'Toggle All Docks' action.
3758 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
3759 let open_dock_positions = self.get_open_dock_positions(cx);
3760 if !open_dock_positions.is_empty() {
3761 self.last_open_dock_positions = open_dock_positions;
3762 }
3763 }
3764
3765 /// Toggles all docks between open and closed states.
3766 ///
3767 /// If any docks are open, closes all and remembers their positions. If all
3768 /// docks are closed, restores the last remembered dock configuration.
3769 fn toggle_all_docks(
3770 &mut self,
3771 _: &ToggleAllDocks,
3772 window: &mut Window,
3773 cx: &mut Context<Self>,
3774 ) {
3775 let open_dock_positions = self.get_open_dock_positions(cx);
3776
3777 if !open_dock_positions.is_empty() {
3778 self.close_all_docks(window, cx);
3779 } else if !self.last_open_dock_positions.is_empty() {
3780 self.restore_last_open_docks(window, cx);
3781 }
3782 }
3783
3784 /// Reopens docks from the most recently remembered configuration.
3785 ///
3786 /// Opens all docks whose positions are stored in `last_open_dock_positions`
3787 /// and clears the stored positions.
3788 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3789 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
3790
3791 for position in positions_to_open {
3792 let dock = self.dock_at_position(position);
3793 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
3794 }
3795
3796 cx.focus_self(window);
3797 cx.notify();
3798 self.serialize_workspace(window, cx);
3799 }
3800
3801 /// Transfer focus to the panel of the given type.
3802 pub fn focus_panel<T: Panel>(
3803 &mut self,
3804 window: &mut Window,
3805 cx: &mut Context<Self>,
3806 ) -> Option<Entity<T>> {
3807 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
3808 panel.to_any().downcast().ok()
3809 }
3810
3811 /// Focus the panel of the given type if it isn't already focused. If it is
3812 /// already focused, then transfer focus back to the workspace center.
3813 /// When the `close_panel_on_toggle` setting is enabled, also closes the
3814 /// panel when transferring focus back to the center.
3815 pub fn toggle_panel_focus<T: Panel>(
3816 &mut self,
3817 window: &mut Window,
3818 cx: &mut Context<Self>,
3819 ) -> bool {
3820 let mut did_focus_panel = false;
3821 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
3822 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
3823 did_focus_panel
3824 });
3825
3826 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
3827 self.close_panel::<T>(window, cx);
3828 }
3829
3830 telemetry::event!(
3831 "Panel Button Clicked",
3832 name = T::persistent_name(),
3833 toggle_state = did_focus_panel
3834 );
3835
3836 did_focus_panel
3837 }
3838
3839 pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3840 if let Some(item) = self.active_item(cx) {
3841 item.item_focus_handle(cx).focus(window, cx);
3842 } else {
3843 log::error!("Could not find a focus target when switching focus to the center panes",);
3844 }
3845 }
3846
3847 pub fn activate_panel_for_proto_id(
3848 &mut self,
3849 panel_id: PanelId,
3850 window: &mut Window,
3851 cx: &mut Context<Self>,
3852 ) -> Option<Arc<dyn PanelHandle>> {
3853 let mut panel = None;
3854 for dock in self.all_docks() {
3855 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
3856 panel = dock.update(cx, |dock, cx| {
3857 dock.activate_panel(panel_index, window, cx);
3858 dock.set_open(true, window, cx);
3859 dock.active_panel().cloned()
3860 });
3861 break;
3862 }
3863 }
3864
3865 if panel.is_some() {
3866 cx.notify();
3867 self.serialize_workspace(window, cx);
3868 }
3869
3870 panel
3871 }
3872
3873 /// Focus or unfocus the given panel type, depending on the given callback.
3874 fn focus_or_unfocus_panel<T: Panel>(
3875 &mut self,
3876 window: &mut Window,
3877 cx: &mut Context<Self>,
3878 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
3879 ) -> Option<Arc<dyn PanelHandle>> {
3880 let mut result_panel = None;
3881 let mut serialize = false;
3882 for dock in self.all_docks() {
3883 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3884 let mut focus_center = false;
3885 let panel = dock.update(cx, |dock, cx| {
3886 dock.activate_panel(panel_index, window, cx);
3887
3888 let panel = dock.active_panel().cloned();
3889 if let Some(panel) = panel.as_ref() {
3890 if should_focus(&**panel, window, cx) {
3891 dock.set_open(true, window, cx);
3892 panel.panel_focus_handle(cx).focus(window, cx);
3893 } else {
3894 focus_center = true;
3895 }
3896 }
3897 panel
3898 });
3899
3900 if focus_center {
3901 self.active_pane
3902 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3903 }
3904
3905 result_panel = panel;
3906 serialize = true;
3907 break;
3908 }
3909 }
3910
3911 if serialize {
3912 self.serialize_workspace(window, cx);
3913 }
3914
3915 cx.notify();
3916 result_panel
3917 }
3918
3919 /// Open the panel of the given type
3920 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3921 for dock in self.all_docks() {
3922 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3923 dock.update(cx, |dock, cx| {
3924 dock.activate_panel(panel_index, window, cx);
3925 dock.set_open(true, window, cx);
3926 });
3927 }
3928 }
3929 }
3930
3931 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
3932 for dock in self.all_docks().iter() {
3933 dock.update(cx, |dock, cx| {
3934 if dock.panel::<T>().is_some() {
3935 dock.set_open(false, window, cx)
3936 }
3937 })
3938 }
3939 }
3940
3941 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
3942 self.all_docks()
3943 .iter()
3944 .find_map(|dock| dock.read(cx).panel::<T>())
3945 }
3946
3947 fn dismiss_zoomed_items_to_reveal(
3948 &mut self,
3949 dock_to_reveal: Option<DockPosition>,
3950 window: &mut Window,
3951 cx: &mut Context<Self>,
3952 ) {
3953 // If a center pane is zoomed, unzoom it.
3954 for pane in &self.panes {
3955 if pane != &self.active_pane || dock_to_reveal.is_some() {
3956 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
3957 }
3958 }
3959
3960 // If another dock is zoomed, hide it.
3961 let mut focus_center = false;
3962 for dock in self.all_docks() {
3963 dock.update(cx, |dock, cx| {
3964 if Some(dock.position()) != dock_to_reveal
3965 && let Some(panel) = dock.active_panel()
3966 && panel.is_zoomed(window, cx)
3967 {
3968 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
3969 dock.set_open(false, window, cx);
3970 }
3971 });
3972 }
3973
3974 if focus_center {
3975 self.active_pane
3976 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3977 }
3978
3979 if self.zoomed_position != dock_to_reveal {
3980 self.zoomed = None;
3981 self.zoomed_position = None;
3982 cx.emit(Event::ZoomChanged);
3983 }
3984
3985 cx.notify();
3986 }
3987
3988 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
3989 let pane = cx.new(|cx| {
3990 let mut pane = Pane::new(
3991 self.weak_handle(),
3992 self.project.clone(),
3993 self.pane_history_timestamp.clone(),
3994 None,
3995 NewFile.boxed_clone(),
3996 true,
3997 window,
3998 cx,
3999 );
4000 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
4001 pane
4002 });
4003 cx.subscribe_in(&pane, window, Self::handle_pane_event)
4004 .detach();
4005 self.panes.push(pane.clone());
4006
4007 window.focus(&pane.focus_handle(cx), cx);
4008
4009 cx.emit(Event::PaneAdded(pane.clone()));
4010 pane
4011 }
4012
4013 pub fn add_item_to_center(
4014 &mut self,
4015 item: Box<dyn ItemHandle>,
4016 window: &mut Window,
4017 cx: &mut Context<Self>,
4018 ) -> bool {
4019 if let Some(center_pane) = self.last_active_center_pane.clone() {
4020 if let Some(center_pane) = center_pane.upgrade() {
4021 center_pane.update(cx, |pane, cx| {
4022 pane.add_item(item, true, true, None, window, cx)
4023 });
4024 true
4025 } else {
4026 false
4027 }
4028 } else {
4029 false
4030 }
4031 }
4032
4033 pub fn add_item_to_active_pane(
4034 &mut self,
4035 item: Box<dyn ItemHandle>,
4036 destination_index: Option<usize>,
4037 focus_item: bool,
4038 window: &mut Window,
4039 cx: &mut App,
4040 ) {
4041 self.add_item(
4042 self.active_pane.clone(),
4043 item,
4044 destination_index,
4045 false,
4046 focus_item,
4047 window,
4048 cx,
4049 )
4050 }
4051
4052 pub fn add_item(
4053 &mut self,
4054 pane: Entity<Pane>,
4055 item: Box<dyn ItemHandle>,
4056 destination_index: Option<usize>,
4057 activate_pane: bool,
4058 focus_item: bool,
4059 window: &mut Window,
4060 cx: &mut App,
4061 ) {
4062 pane.update(cx, |pane, cx| {
4063 pane.add_item(
4064 item,
4065 activate_pane,
4066 focus_item,
4067 destination_index,
4068 window,
4069 cx,
4070 )
4071 });
4072 }
4073
4074 pub fn split_item(
4075 &mut self,
4076 split_direction: SplitDirection,
4077 item: Box<dyn ItemHandle>,
4078 window: &mut Window,
4079 cx: &mut Context<Self>,
4080 ) {
4081 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4082 self.add_item(new_pane, item, None, true, true, window, cx);
4083 }
4084
4085 pub fn open_abs_path(
4086 &mut self,
4087 abs_path: PathBuf,
4088 options: OpenOptions,
4089 window: &mut Window,
4090 cx: &mut Context<Self>,
4091 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4092 cx.spawn_in(window, async move |workspace, cx| {
4093 let open_paths_task_result = workspace
4094 .update_in(cx, |workspace, window, cx| {
4095 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4096 })
4097 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4098 .await;
4099 anyhow::ensure!(
4100 open_paths_task_result.len() == 1,
4101 "open abs path {abs_path:?} task returned incorrect number of results"
4102 );
4103 match open_paths_task_result
4104 .into_iter()
4105 .next()
4106 .expect("ensured single task result")
4107 {
4108 Some(open_result) => {
4109 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4110 }
4111 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4112 }
4113 })
4114 }
4115
4116 pub fn split_abs_path(
4117 &mut self,
4118 abs_path: PathBuf,
4119 visible: bool,
4120 window: &mut Window,
4121 cx: &mut Context<Self>,
4122 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4123 let project_path_task =
4124 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4125 cx.spawn_in(window, async move |this, cx| {
4126 let (_, path) = project_path_task.await?;
4127 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4128 .await
4129 })
4130 }
4131
4132 pub fn open_path(
4133 &mut self,
4134 path: impl Into<ProjectPath>,
4135 pane: Option<WeakEntity<Pane>>,
4136 focus_item: bool,
4137 window: &mut Window,
4138 cx: &mut App,
4139 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4140 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4141 }
4142
4143 pub fn open_path_preview(
4144 &mut self,
4145 path: impl Into<ProjectPath>,
4146 pane: Option<WeakEntity<Pane>>,
4147 focus_item: bool,
4148 allow_preview: bool,
4149 activate: bool,
4150 window: &mut Window,
4151 cx: &mut App,
4152 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4153 let pane = pane.unwrap_or_else(|| {
4154 self.last_active_center_pane.clone().unwrap_or_else(|| {
4155 self.panes
4156 .first()
4157 .expect("There must be an active pane")
4158 .downgrade()
4159 })
4160 });
4161
4162 let project_path = path.into();
4163 let task = self.load_path(project_path.clone(), window, cx);
4164 window.spawn(cx, async move |cx| {
4165 let (project_entry_id, build_item) = task.await?;
4166
4167 pane.update_in(cx, |pane, window, cx| {
4168 pane.open_item(
4169 project_entry_id,
4170 project_path,
4171 focus_item,
4172 allow_preview,
4173 activate,
4174 None,
4175 window,
4176 cx,
4177 build_item,
4178 )
4179 })
4180 })
4181 }
4182
4183 pub fn split_path(
4184 &mut self,
4185 path: impl Into<ProjectPath>,
4186 window: &mut Window,
4187 cx: &mut Context<Self>,
4188 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4189 self.split_path_preview(path, false, None, window, cx)
4190 }
4191
4192 pub fn split_path_preview(
4193 &mut self,
4194 path: impl Into<ProjectPath>,
4195 allow_preview: bool,
4196 split_direction: Option<SplitDirection>,
4197 window: &mut Window,
4198 cx: &mut Context<Self>,
4199 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4200 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4201 self.panes
4202 .first()
4203 .expect("There must be an active pane")
4204 .downgrade()
4205 });
4206
4207 if let Member::Pane(center_pane) = &self.center.root
4208 && center_pane.read(cx).items_len() == 0
4209 {
4210 return self.open_path(path, Some(pane), true, window, cx);
4211 }
4212
4213 let project_path = path.into();
4214 let task = self.load_path(project_path.clone(), window, cx);
4215 cx.spawn_in(window, async move |this, cx| {
4216 let (project_entry_id, build_item) = task.await?;
4217 this.update_in(cx, move |this, window, cx| -> Option<_> {
4218 let pane = pane.upgrade()?;
4219 let new_pane = this.split_pane(
4220 pane,
4221 split_direction.unwrap_or(SplitDirection::Right),
4222 window,
4223 cx,
4224 );
4225 new_pane.update(cx, |new_pane, cx| {
4226 Some(new_pane.open_item(
4227 project_entry_id,
4228 project_path,
4229 true,
4230 allow_preview,
4231 true,
4232 None,
4233 window,
4234 cx,
4235 build_item,
4236 ))
4237 })
4238 })
4239 .map(|option| option.context("pane was dropped"))?
4240 })
4241 }
4242
4243 fn load_path(
4244 &mut self,
4245 path: ProjectPath,
4246 window: &mut Window,
4247 cx: &mut App,
4248 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4249 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4250 registry.open_path(self.project(), &path, window, cx)
4251 }
4252
4253 pub fn find_project_item<T>(
4254 &self,
4255 pane: &Entity<Pane>,
4256 project_item: &Entity<T::Item>,
4257 cx: &App,
4258 ) -> Option<Entity<T>>
4259 where
4260 T: ProjectItem,
4261 {
4262 use project::ProjectItem as _;
4263 let project_item = project_item.read(cx);
4264 let entry_id = project_item.entry_id(cx);
4265 let project_path = project_item.project_path(cx);
4266
4267 let mut item = None;
4268 if let Some(entry_id) = entry_id {
4269 item = pane.read(cx).item_for_entry(entry_id, cx);
4270 }
4271 if item.is_none()
4272 && let Some(project_path) = project_path
4273 {
4274 item = pane.read(cx).item_for_path(project_path, cx);
4275 }
4276
4277 item.and_then(|item| item.downcast::<T>())
4278 }
4279
4280 pub fn is_project_item_open<T>(
4281 &self,
4282 pane: &Entity<Pane>,
4283 project_item: &Entity<T::Item>,
4284 cx: &App,
4285 ) -> bool
4286 where
4287 T: ProjectItem,
4288 {
4289 self.find_project_item::<T>(pane, project_item, cx)
4290 .is_some()
4291 }
4292
4293 pub fn open_project_item<T>(
4294 &mut self,
4295 pane: Entity<Pane>,
4296 project_item: Entity<T::Item>,
4297 activate_pane: bool,
4298 focus_item: bool,
4299 keep_old_preview: bool,
4300 allow_new_preview: bool,
4301 window: &mut Window,
4302 cx: &mut Context<Self>,
4303 ) -> Entity<T>
4304 where
4305 T: ProjectItem,
4306 {
4307 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4308
4309 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4310 if !keep_old_preview
4311 && let Some(old_id) = old_item_id
4312 && old_id != item.item_id()
4313 {
4314 // switching to a different item, so unpreview old active item
4315 pane.update(cx, |pane, _| {
4316 pane.unpreview_item_if_preview(old_id);
4317 });
4318 }
4319
4320 self.activate_item(&item, activate_pane, focus_item, window, cx);
4321 if !allow_new_preview {
4322 pane.update(cx, |pane, _| {
4323 pane.unpreview_item_if_preview(item.item_id());
4324 });
4325 }
4326 return item;
4327 }
4328
4329 let item = pane.update(cx, |pane, cx| {
4330 cx.new(|cx| {
4331 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4332 })
4333 });
4334 let mut destination_index = None;
4335 pane.update(cx, |pane, cx| {
4336 if !keep_old_preview && let Some(old_id) = old_item_id {
4337 pane.unpreview_item_if_preview(old_id);
4338 }
4339 if allow_new_preview {
4340 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4341 }
4342 });
4343
4344 self.add_item(
4345 pane,
4346 Box::new(item.clone()),
4347 destination_index,
4348 activate_pane,
4349 focus_item,
4350 window,
4351 cx,
4352 );
4353 item
4354 }
4355
4356 pub fn open_shared_screen(
4357 &mut self,
4358 peer_id: PeerId,
4359 window: &mut Window,
4360 cx: &mut Context<Self>,
4361 ) {
4362 if let Some(shared_screen) =
4363 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4364 {
4365 self.active_pane.update(cx, |pane, cx| {
4366 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4367 });
4368 }
4369 }
4370
4371 pub fn activate_item(
4372 &mut self,
4373 item: &dyn ItemHandle,
4374 activate_pane: bool,
4375 focus_item: bool,
4376 window: &mut Window,
4377 cx: &mut App,
4378 ) -> bool {
4379 let result = self.panes.iter().find_map(|pane| {
4380 pane.read(cx)
4381 .index_for_item(item)
4382 .map(|ix| (pane.clone(), ix))
4383 });
4384 if let Some((pane, ix)) = result {
4385 pane.update(cx, |pane, cx| {
4386 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4387 });
4388 true
4389 } else {
4390 false
4391 }
4392 }
4393
4394 fn activate_pane_at_index(
4395 &mut self,
4396 action: &ActivatePane,
4397 window: &mut Window,
4398 cx: &mut Context<Self>,
4399 ) {
4400 let panes = self.center.panes();
4401 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4402 window.focus(&pane.focus_handle(cx), cx);
4403 } else {
4404 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4405 .detach();
4406 }
4407 }
4408
4409 fn move_item_to_pane_at_index(
4410 &mut self,
4411 action: &MoveItemToPane,
4412 window: &mut Window,
4413 cx: &mut Context<Self>,
4414 ) {
4415 let panes = self.center.panes();
4416 let destination = match panes.get(action.destination) {
4417 Some(&destination) => destination.clone(),
4418 None => {
4419 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4420 return;
4421 }
4422 let direction = SplitDirection::Right;
4423 let split_off_pane = self
4424 .find_pane_in_direction(direction, cx)
4425 .unwrap_or_else(|| self.active_pane.clone());
4426 let new_pane = self.add_pane(window, cx);
4427 self.center.split(&split_off_pane, &new_pane, direction, cx);
4428 new_pane
4429 }
4430 };
4431
4432 if action.clone {
4433 if self
4434 .active_pane
4435 .read(cx)
4436 .active_item()
4437 .is_some_and(|item| item.can_split(cx))
4438 {
4439 clone_active_item(
4440 self.database_id(),
4441 &self.active_pane,
4442 &destination,
4443 action.focus,
4444 window,
4445 cx,
4446 );
4447 return;
4448 }
4449 }
4450 move_active_item(
4451 &self.active_pane,
4452 &destination,
4453 action.focus,
4454 true,
4455 window,
4456 cx,
4457 )
4458 }
4459
4460 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4461 let panes = self.center.panes();
4462 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4463 let next_ix = (ix + 1) % panes.len();
4464 let next_pane = panes[next_ix].clone();
4465 window.focus(&next_pane.focus_handle(cx), cx);
4466 }
4467 }
4468
4469 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4470 let panes = self.center.panes();
4471 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4472 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4473 let prev_pane = panes[prev_ix].clone();
4474 window.focus(&prev_pane.focus_handle(cx), cx);
4475 }
4476 }
4477
4478 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4479 let last_pane = self.center.last_pane();
4480 window.focus(&last_pane.focus_handle(cx), cx);
4481 }
4482
4483 pub fn activate_pane_in_direction(
4484 &mut self,
4485 direction: SplitDirection,
4486 window: &mut Window,
4487 cx: &mut App,
4488 ) {
4489 use ActivateInDirectionTarget as Target;
4490 enum Origin {
4491 Sidebar,
4492 LeftDock,
4493 RightDock,
4494 BottomDock,
4495 Center,
4496 }
4497
4498 let origin: Origin = if self
4499 .sidebar_focus_handle
4500 .as_ref()
4501 .is_some_and(|h| h.contains_focused(window, cx))
4502 {
4503 Origin::Sidebar
4504 } else {
4505 [
4506 (&self.left_dock, Origin::LeftDock),
4507 (&self.right_dock, Origin::RightDock),
4508 (&self.bottom_dock, Origin::BottomDock),
4509 ]
4510 .into_iter()
4511 .find_map(|(dock, origin)| {
4512 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4513 Some(origin)
4514 } else {
4515 None
4516 }
4517 })
4518 .unwrap_or(Origin::Center)
4519 };
4520
4521 let get_last_active_pane = || {
4522 let pane = self
4523 .last_active_center_pane
4524 .clone()
4525 .unwrap_or_else(|| {
4526 self.panes
4527 .first()
4528 .expect("There must be an active pane")
4529 .downgrade()
4530 })
4531 .upgrade()?;
4532 (pane.read(cx).items_len() != 0).then_some(pane)
4533 };
4534
4535 let try_dock =
4536 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4537
4538 let sidebar_target = self
4539 .sidebar_focus_handle
4540 .as_ref()
4541 .map(|h| Target::Sidebar(h.clone()));
4542
4543 let target = match (origin, direction) {
4544 // From the sidebar, only Right navigates into the workspace.
4545 (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
4546 .or_else(|| get_last_active_pane().map(Target::Pane))
4547 .or_else(|| try_dock(&self.bottom_dock))
4548 .or_else(|| try_dock(&self.right_dock)),
4549
4550 (Origin::Sidebar, _) => None,
4551
4552 // We're in the center, so we first try to go to a different pane,
4553 // otherwise try to go to a dock.
4554 (Origin::Center, direction) => {
4555 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4556 Some(Target::Pane(pane))
4557 } else {
4558 match direction {
4559 SplitDirection::Up => None,
4560 SplitDirection::Down => try_dock(&self.bottom_dock),
4561 SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
4562 SplitDirection::Right => try_dock(&self.right_dock),
4563 }
4564 }
4565 }
4566
4567 (Origin::LeftDock, SplitDirection::Right) => {
4568 if let Some(last_active_pane) = get_last_active_pane() {
4569 Some(Target::Pane(last_active_pane))
4570 } else {
4571 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4572 }
4573 }
4574
4575 (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
4576
4577 (Origin::LeftDock, SplitDirection::Down)
4578 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4579
4580 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4581 (Origin::BottomDock, SplitDirection::Left) => {
4582 try_dock(&self.left_dock).or(sidebar_target)
4583 }
4584 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4585
4586 (Origin::RightDock, SplitDirection::Left) => {
4587 if let Some(last_active_pane) = get_last_active_pane() {
4588 Some(Target::Pane(last_active_pane))
4589 } else {
4590 try_dock(&self.bottom_dock)
4591 .or_else(|| try_dock(&self.left_dock))
4592 .or(sidebar_target)
4593 }
4594 }
4595
4596 _ => None,
4597 };
4598
4599 match target {
4600 Some(ActivateInDirectionTarget::Pane(pane)) => {
4601 let pane = pane.read(cx);
4602 if let Some(item) = pane.active_item() {
4603 item.item_focus_handle(cx).focus(window, cx);
4604 } else {
4605 log::error!(
4606 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4607 );
4608 }
4609 }
4610 Some(ActivateInDirectionTarget::Dock(dock)) => {
4611 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4612 window.defer(cx, move |window, cx| {
4613 let dock = dock.read(cx);
4614 if let Some(panel) = dock.active_panel() {
4615 panel.panel_focus_handle(cx).focus(window, cx);
4616 } else {
4617 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4618 }
4619 })
4620 }
4621 Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
4622 focus_handle.focus(window, cx);
4623 }
4624 None => {}
4625 }
4626 }
4627
4628 pub fn move_item_to_pane_in_direction(
4629 &mut self,
4630 action: &MoveItemToPaneInDirection,
4631 window: &mut Window,
4632 cx: &mut Context<Self>,
4633 ) {
4634 let destination = match self.find_pane_in_direction(action.direction, cx) {
4635 Some(destination) => destination,
4636 None => {
4637 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4638 return;
4639 }
4640 let new_pane = self.add_pane(window, cx);
4641 self.center
4642 .split(&self.active_pane, &new_pane, action.direction, cx);
4643 new_pane
4644 }
4645 };
4646
4647 if action.clone {
4648 if self
4649 .active_pane
4650 .read(cx)
4651 .active_item()
4652 .is_some_and(|item| item.can_split(cx))
4653 {
4654 clone_active_item(
4655 self.database_id(),
4656 &self.active_pane,
4657 &destination,
4658 action.focus,
4659 window,
4660 cx,
4661 );
4662 return;
4663 }
4664 }
4665 move_active_item(
4666 &self.active_pane,
4667 &destination,
4668 action.focus,
4669 true,
4670 window,
4671 cx,
4672 );
4673 }
4674
4675 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4676 self.center.bounding_box_for_pane(pane)
4677 }
4678
4679 pub fn find_pane_in_direction(
4680 &mut self,
4681 direction: SplitDirection,
4682 cx: &App,
4683 ) -> Option<Entity<Pane>> {
4684 self.center
4685 .find_pane_in_direction(&self.active_pane, direction, cx)
4686 .cloned()
4687 }
4688
4689 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4690 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4691 self.center.swap(&self.active_pane, &to, cx);
4692 cx.notify();
4693 }
4694 }
4695
4696 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4697 if self
4698 .center
4699 .move_to_border(&self.active_pane, direction, cx)
4700 .unwrap()
4701 {
4702 cx.notify();
4703 }
4704 }
4705
4706 pub fn resize_pane(
4707 &mut self,
4708 axis: gpui::Axis,
4709 amount: Pixels,
4710 window: &mut Window,
4711 cx: &mut Context<Self>,
4712 ) {
4713 let docks = self.all_docks();
4714 let active_dock = docks
4715 .into_iter()
4716 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4717
4718 if let Some(dock) = active_dock {
4719 let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
4720 return;
4721 };
4722 match dock.read(cx).position() {
4723 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4724 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4725 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4726 }
4727 } else {
4728 self.center
4729 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
4730 }
4731 cx.notify();
4732 }
4733
4734 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
4735 self.center.reset_pane_sizes(cx);
4736 cx.notify();
4737 }
4738
4739 fn handle_pane_focused(
4740 &mut self,
4741 pane: Entity<Pane>,
4742 window: &mut Window,
4743 cx: &mut Context<Self>,
4744 ) {
4745 // This is explicitly hoisted out of the following check for pane identity as
4746 // terminal panel panes are not registered as a center panes.
4747 self.status_bar.update(cx, |status_bar, cx| {
4748 status_bar.set_active_pane(&pane, window, cx);
4749 });
4750 if self.active_pane != pane {
4751 self.set_active_pane(&pane, window, cx);
4752 }
4753
4754 if self.last_active_center_pane.is_none() {
4755 self.last_active_center_pane = Some(pane.downgrade());
4756 }
4757
4758 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
4759 // This prevents the dock from closing when focus events fire during window activation.
4760 // We also preserve any dock whose active panel itself has focus — this covers
4761 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
4762 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
4763 let dock_read = dock.read(cx);
4764 if let Some(panel) = dock_read.active_panel() {
4765 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
4766 || panel.panel_focus_handle(cx).contains_focused(window, cx)
4767 {
4768 return Some(dock_read.position());
4769 }
4770 }
4771 None
4772 });
4773
4774 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
4775 if pane.read(cx).is_zoomed() {
4776 self.zoomed = Some(pane.downgrade().into());
4777 } else {
4778 self.zoomed = None;
4779 }
4780 self.zoomed_position = None;
4781 cx.emit(Event::ZoomChanged);
4782 self.update_active_view_for_followers(window, cx);
4783 pane.update(cx, |pane, _| {
4784 pane.track_alternate_file_items();
4785 });
4786
4787 cx.notify();
4788 }
4789
4790 fn set_active_pane(
4791 &mut self,
4792 pane: &Entity<Pane>,
4793 window: &mut Window,
4794 cx: &mut Context<Self>,
4795 ) {
4796 self.active_pane = pane.clone();
4797 self.active_item_path_changed(true, window, cx);
4798 self.last_active_center_pane = Some(pane.downgrade());
4799 }
4800
4801 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4802 self.update_active_view_for_followers(window, cx);
4803 }
4804
4805 fn handle_pane_event(
4806 &mut self,
4807 pane: &Entity<Pane>,
4808 event: &pane::Event,
4809 window: &mut Window,
4810 cx: &mut Context<Self>,
4811 ) {
4812 let mut serialize_workspace = true;
4813 match event {
4814 pane::Event::AddItem { item } => {
4815 item.added_to_pane(self, pane.clone(), window, cx);
4816 cx.emit(Event::ItemAdded {
4817 item: item.boxed_clone(),
4818 });
4819 }
4820 pane::Event::Split { direction, mode } => {
4821 match mode {
4822 SplitMode::ClonePane => {
4823 self.split_and_clone(pane.clone(), *direction, window, cx)
4824 .detach();
4825 }
4826 SplitMode::EmptyPane => {
4827 self.split_pane(pane.clone(), *direction, window, cx);
4828 }
4829 SplitMode::MovePane => {
4830 self.split_and_move(pane.clone(), *direction, window, cx);
4831 }
4832 };
4833 }
4834 pane::Event::JoinIntoNext => {
4835 self.join_pane_into_next(pane.clone(), window, cx);
4836 }
4837 pane::Event::JoinAll => {
4838 self.join_all_panes(window, cx);
4839 }
4840 pane::Event::Remove { focus_on_pane } => {
4841 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
4842 }
4843 pane::Event::ActivateItem {
4844 local,
4845 focus_changed,
4846 } => {
4847 window.invalidate_character_coordinates();
4848
4849 pane.update(cx, |pane, _| {
4850 pane.track_alternate_file_items();
4851 });
4852 if *local {
4853 self.unfollow_in_pane(pane, window, cx);
4854 }
4855 serialize_workspace = *focus_changed || pane != self.active_pane();
4856 if pane == self.active_pane() {
4857 self.active_item_path_changed(*focus_changed, window, cx);
4858 self.update_active_view_for_followers(window, cx);
4859 } else if *local {
4860 self.set_active_pane(pane, window, cx);
4861 }
4862 }
4863 pane::Event::UserSavedItem { item, save_intent } => {
4864 cx.emit(Event::UserSavedItem {
4865 pane: pane.downgrade(),
4866 item: item.boxed_clone(),
4867 save_intent: *save_intent,
4868 });
4869 serialize_workspace = false;
4870 }
4871 pane::Event::ChangeItemTitle => {
4872 if *pane == self.active_pane {
4873 self.active_item_path_changed(false, window, cx);
4874 }
4875 serialize_workspace = false;
4876 }
4877 pane::Event::RemovedItem { item } => {
4878 cx.emit(Event::ActiveItemChanged);
4879 self.update_window_edited(window, cx);
4880 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
4881 && entry.get().entity_id() == pane.entity_id()
4882 {
4883 entry.remove();
4884 }
4885 cx.emit(Event::ItemRemoved {
4886 item_id: item.item_id(),
4887 });
4888 }
4889 pane::Event::Focus => {
4890 window.invalidate_character_coordinates();
4891 self.handle_pane_focused(pane.clone(), window, cx);
4892 }
4893 pane::Event::ZoomIn => {
4894 if *pane == self.active_pane {
4895 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
4896 if pane.read(cx).has_focus(window, cx) {
4897 self.zoomed = Some(pane.downgrade().into());
4898 self.zoomed_position = None;
4899 cx.emit(Event::ZoomChanged);
4900 }
4901 cx.notify();
4902 }
4903 }
4904 pane::Event::ZoomOut => {
4905 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4906 if self.zoomed_position.is_none() {
4907 self.zoomed = None;
4908 cx.emit(Event::ZoomChanged);
4909 }
4910 cx.notify();
4911 }
4912 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
4913 }
4914
4915 if serialize_workspace {
4916 self.serialize_workspace(window, cx);
4917 }
4918 }
4919
4920 pub fn unfollow_in_pane(
4921 &mut self,
4922 pane: &Entity<Pane>,
4923 window: &mut Window,
4924 cx: &mut Context<Workspace>,
4925 ) -> Option<CollaboratorId> {
4926 let leader_id = self.leader_for_pane(pane)?;
4927 self.unfollow(leader_id, window, cx);
4928 Some(leader_id)
4929 }
4930
4931 pub fn split_pane(
4932 &mut self,
4933 pane_to_split: Entity<Pane>,
4934 split_direction: SplitDirection,
4935 window: &mut Window,
4936 cx: &mut Context<Self>,
4937 ) -> Entity<Pane> {
4938 let new_pane = self.add_pane(window, cx);
4939 self.center
4940 .split(&pane_to_split, &new_pane, split_direction, cx);
4941 cx.notify();
4942 new_pane
4943 }
4944
4945 pub fn split_and_move(
4946 &mut self,
4947 pane: Entity<Pane>,
4948 direction: SplitDirection,
4949 window: &mut Window,
4950 cx: &mut Context<Self>,
4951 ) {
4952 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
4953 return;
4954 };
4955 let new_pane = self.add_pane(window, cx);
4956 new_pane.update(cx, |pane, cx| {
4957 pane.add_item(item, true, true, None, window, cx)
4958 });
4959 self.center.split(&pane, &new_pane, direction, cx);
4960 cx.notify();
4961 }
4962
4963 pub fn split_and_clone(
4964 &mut self,
4965 pane: Entity<Pane>,
4966 direction: SplitDirection,
4967 window: &mut Window,
4968 cx: &mut Context<Self>,
4969 ) -> Task<Option<Entity<Pane>>> {
4970 let Some(item) = pane.read(cx).active_item() else {
4971 return Task::ready(None);
4972 };
4973 if !item.can_split(cx) {
4974 return Task::ready(None);
4975 }
4976 let task = item.clone_on_split(self.database_id(), window, cx);
4977 cx.spawn_in(window, async move |this, cx| {
4978 if let Some(clone) = task.await {
4979 this.update_in(cx, |this, window, cx| {
4980 let new_pane = this.add_pane(window, cx);
4981 let nav_history = pane.read(cx).fork_nav_history();
4982 new_pane.update(cx, |pane, cx| {
4983 pane.set_nav_history(nav_history, cx);
4984 pane.add_item(clone, true, true, None, window, cx)
4985 });
4986 this.center.split(&pane, &new_pane, direction, cx);
4987 cx.notify();
4988 new_pane
4989 })
4990 .ok()
4991 } else {
4992 None
4993 }
4994 })
4995 }
4996
4997 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4998 let active_item = self.active_pane.read(cx).active_item();
4999 for pane in &self.panes {
5000 join_pane_into_active(&self.active_pane, pane, window, cx);
5001 }
5002 if let Some(active_item) = active_item {
5003 self.activate_item(active_item.as_ref(), true, true, window, cx);
5004 }
5005 cx.notify();
5006 }
5007
5008 pub fn join_pane_into_next(
5009 &mut self,
5010 pane: Entity<Pane>,
5011 window: &mut Window,
5012 cx: &mut Context<Self>,
5013 ) {
5014 let next_pane = self
5015 .find_pane_in_direction(SplitDirection::Right, cx)
5016 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
5017 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
5018 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
5019 let Some(next_pane) = next_pane else {
5020 return;
5021 };
5022 move_all_items(&pane, &next_pane, window, cx);
5023 cx.notify();
5024 }
5025
5026 fn remove_pane(
5027 &mut self,
5028 pane: Entity<Pane>,
5029 focus_on: Option<Entity<Pane>>,
5030 window: &mut Window,
5031 cx: &mut Context<Self>,
5032 ) {
5033 if self.center.remove(&pane, cx).unwrap() {
5034 self.force_remove_pane(&pane, &focus_on, window, cx);
5035 self.unfollow_in_pane(&pane, window, cx);
5036 self.last_leaders_by_pane.remove(&pane.downgrade());
5037 for removed_item in pane.read(cx).items() {
5038 self.panes_by_item.remove(&removed_item.item_id());
5039 }
5040
5041 cx.notify();
5042 } else {
5043 self.active_item_path_changed(true, window, cx);
5044 }
5045 cx.emit(Event::PaneRemoved);
5046 }
5047
5048 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5049 &mut self.panes
5050 }
5051
5052 pub fn panes(&self) -> &[Entity<Pane>] {
5053 &self.panes
5054 }
5055
5056 pub fn active_pane(&self) -> &Entity<Pane> {
5057 &self.active_pane
5058 }
5059
5060 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5061 for dock in self.all_docks() {
5062 if dock.focus_handle(cx).contains_focused(window, cx)
5063 && let Some(pane) = dock
5064 .read(cx)
5065 .active_panel()
5066 .and_then(|panel| panel.pane(cx))
5067 {
5068 return pane;
5069 }
5070 }
5071 self.active_pane().clone()
5072 }
5073
5074 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5075 self.find_pane_in_direction(SplitDirection::Right, cx)
5076 .unwrap_or_else(|| {
5077 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5078 })
5079 }
5080
5081 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5082 self.pane_for_item_id(handle.item_id())
5083 }
5084
5085 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5086 let weak_pane = self.panes_by_item.get(&item_id)?;
5087 weak_pane.upgrade()
5088 }
5089
5090 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5091 self.panes
5092 .iter()
5093 .find(|pane| pane.entity_id() == entity_id)
5094 .cloned()
5095 }
5096
5097 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5098 self.follower_states.retain(|leader_id, state| {
5099 if *leader_id == CollaboratorId::PeerId(peer_id) {
5100 for item in state.items_by_leader_view_id.values() {
5101 item.view.set_leader_id(None, window, cx);
5102 }
5103 false
5104 } else {
5105 true
5106 }
5107 });
5108 cx.notify();
5109 }
5110
5111 pub fn start_following(
5112 &mut self,
5113 leader_id: impl Into<CollaboratorId>,
5114 window: &mut Window,
5115 cx: &mut Context<Self>,
5116 ) -> Option<Task<Result<()>>> {
5117 let leader_id = leader_id.into();
5118 let pane = self.active_pane().clone();
5119
5120 self.last_leaders_by_pane
5121 .insert(pane.downgrade(), leader_id);
5122 self.unfollow(leader_id, window, cx);
5123 self.unfollow_in_pane(&pane, window, cx);
5124 self.follower_states.insert(
5125 leader_id,
5126 FollowerState {
5127 center_pane: pane.clone(),
5128 dock_pane: None,
5129 active_view_id: None,
5130 items_by_leader_view_id: Default::default(),
5131 },
5132 );
5133 cx.notify();
5134
5135 match leader_id {
5136 CollaboratorId::PeerId(leader_peer_id) => {
5137 let room_id = self.active_call()?.room_id(cx)?;
5138 let project_id = self.project.read(cx).remote_id();
5139 let request = self.app_state.client.request(proto::Follow {
5140 room_id,
5141 project_id,
5142 leader_id: Some(leader_peer_id),
5143 });
5144
5145 Some(cx.spawn_in(window, async move |this, cx| {
5146 let response = request.await?;
5147 this.update(cx, |this, _| {
5148 let state = this
5149 .follower_states
5150 .get_mut(&leader_id)
5151 .context("following interrupted")?;
5152 state.active_view_id = response
5153 .active_view
5154 .as_ref()
5155 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5156 anyhow::Ok(())
5157 })??;
5158 if let Some(view) = response.active_view {
5159 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5160 }
5161 this.update_in(cx, |this, window, cx| {
5162 this.leader_updated(leader_id, window, cx)
5163 })?;
5164 Ok(())
5165 }))
5166 }
5167 CollaboratorId::Agent => {
5168 self.leader_updated(leader_id, window, cx)?;
5169 Some(Task::ready(Ok(())))
5170 }
5171 }
5172 }
5173
5174 pub fn follow_next_collaborator(
5175 &mut self,
5176 _: &FollowNextCollaborator,
5177 window: &mut Window,
5178 cx: &mut Context<Self>,
5179 ) {
5180 let collaborators = self.project.read(cx).collaborators();
5181 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5182 let mut collaborators = collaborators.keys().copied();
5183 for peer_id in collaborators.by_ref() {
5184 if CollaboratorId::PeerId(peer_id) == leader_id {
5185 break;
5186 }
5187 }
5188 collaborators.next().map(CollaboratorId::PeerId)
5189 } else if let Some(last_leader_id) =
5190 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5191 {
5192 match last_leader_id {
5193 CollaboratorId::PeerId(peer_id) => {
5194 if collaborators.contains_key(peer_id) {
5195 Some(*last_leader_id)
5196 } else {
5197 None
5198 }
5199 }
5200 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5201 }
5202 } else {
5203 None
5204 };
5205
5206 let pane = self.active_pane.clone();
5207 let Some(leader_id) = next_leader_id.or_else(|| {
5208 Some(CollaboratorId::PeerId(
5209 collaborators.keys().copied().next()?,
5210 ))
5211 }) else {
5212 return;
5213 };
5214 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5215 return;
5216 }
5217 if let Some(task) = self.start_following(leader_id, window, cx) {
5218 task.detach_and_log_err(cx)
5219 }
5220 }
5221
5222 pub fn follow(
5223 &mut self,
5224 leader_id: impl Into<CollaboratorId>,
5225 window: &mut Window,
5226 cx: &mut Context<Self>,
5227 ) {
5228 let leader_id = leader_id.into();
5229
5230 if let CollaboratorId::PeerId(peer_id) = leader_id {
5231 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5232 return;
5233 };
5234 let Some(remote_participant) =
5235 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5236 else {
5237 return;
5238 };
5239
5240 let project = self.project.read(cx);
5241
5242 let other_project_id = match remote_participant.location {
5243 ParticipantLocation::External => None,
5244 ParticipantLocation::UnsharedProject => None,
5245 ParticipantLocation::SharedProject { project_id } => {
5246 if Some(project_id) == project.remote_id() {
5247 None
5248 } else {
5249 Some(project_id)
5250 }
5251 }
5252 };
5253
5254 // if they are active in another project, follow there.
5255 if let Some(project_id) = other_project_id {
5256 let app_state = self.app_state.clone();
5257 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5258 .detach_and_log_err(cx);
5259 }
5260 }
5261
5262 // if you're already following, find the right pane and focus it.
5263 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5264 window.focus(&follower_state.pane().focus_handle(cx), cx);
5265
5266 return;
5267 }
5268
5269 // Otherwise, follow.
5270 if let Some(task) = self.start_following(leader_id, window, cx) {
5271 task.detach_and_log_err(cx)
5272 }
5273 }
5274
5275 pub fn unfollow(
5276 &mut self,
5277 leader_id: impl Into<CollaboratorId>,
5278 window: &mut Window,
5279 cx: &mut Context<Self>,
5280 ) -> Option<()> {
5281 cx.notify();
5282
5283 let leader_id = leader_id.into();
5284 let state = self.follower_states.remove(&leader_id)?;
5285 for (_, item) in state.items_by_leader_view_id {
5286 item.view.set_leader_id(None, window, cx);
5287 }
5288
5289 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5290 let project_id = self.project.read(cx).remote_id();
5291 let room_id = self.active_call()?.room_id(cx)?;
5292 self.app_state
5293 .client
5294 .send(proto::Unfollow {
5295 room_id,
5296 project_id,
5297 leader_id: Some(leader_peer_id),
5298 })
5299 .log_err();
5300 }
5301
5302 Some(())
5303 }
5304
5305 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5306 self.follower_states.contains_key(&id.into())
5307 }
5308
5309 fn active_item_path_changed(
5310 &mut self,
5311 focus_changed: bool,
5312 window: &mut Window,
5313 cx: &mut Context<Self>,
5314 ) {
5315 cx.emit(Event::ActiveItemChanged);
5316 let active_entry = self.active_project_path(cx);
5317 self.project.update(cx, |project, cx| {
5318 project.set_active_path(active_entry.clone(), cx)
5319 });
5320
5321 if focus_changed && let Some(project_path) = &active_entry {
5322 let git_store_entity = self.project.read(cx).git_store().clone();
5323 git_store_entity.update(cx, |git_store, cx| {
5324 git_store.set_active_repo_for_path(project_path, cx);
5325 });
5326 }
5327
5328 self.update_window_title(window, cx);
5329 }
5330
5331 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5332 let project = self.project().read(cx);
5333 let mut title = String::new();
5334
5335 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5336 let name = {
5337 let settings_location = SettingsLocation {
5338 worktree_id: worktree.read(cx).id(),
5339 path: RelPath::empty(),
5340 };
5341
5342 let settings = WorktreeSettings::get(Some(settings_location), cx);
5343 match &settings.project_name {
5344 Some(name) => name.as_str(),
5345 None => worktree.read(cx).root_name_str(),
5346 }
5347 };
5348 if i > 0 {
5349 title.push_str(", ");
5350 }
5351 title.push_str(name);
5352 }
5353
5354 if title.is_empty() {
5355 title = "empty project".to_string();
5356 }
5357
5358 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5359 let filename = path.path.file_name().or_else(|| {
5360 Some(
5361 project
5362 .worktree_for_id(path.worktree_id, cx)?
5363 .read(cx)
5364 .root_name_str(),
5365 )
5366 });
5367
5368 if let Some(filename) = filename {
5369 title.push_str(" — ");
5370 title.push_str(filename.as_ref());
5371 }
5372 }
5373
5374 if project.is_via_collab() {
5375 title.push_str(" ↙");
5376 } else if project.is_shared() {
5377 title.push_str(" ↗");
5378 }
5379
5380 if let Some(last_title) = self.last_window_title.as_ref()
5381 && &title == last_title
5382 {
5383 return;
5384 }
5385 window.set_window_title(&title);
5386 SystemWindowTabController::update_tab_title(
5387 cx,
5388 window.window_handle().window_id(),
5389 SharedString::from(&title),
5390 );
5391 self.last_window_title = Some(title);
5392 }
5393
5394 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5395 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5396 if is_edited != self.window_edited {
5397 self.window_edited = is_edited;
5398 window.set_window_edited(self.window_edited)
5399 }
5400 }
5401
5402 fn update_item_dirty_state(
5403 &mut self,
5404 item: &dyn ItemHandle,
5405 window: &mut Window,
5406 cx: &mut App,
5407 ) {
5408 let is_dirty = item.is_dirty(cx);
5409 let item_id = item.item_id();
5410 let was_dirty = self.dirty_items.contains_key(&item_id);
5411 if is_dirty == was_dirty {
5412 return;
5413 }
5414 if was_dirty {
5415 self.dirty_items.remove(&item_id);
5416 self.update_window_edited(window, cx);
5417 return;
5418 }
5419
5420 let workspace = self.weak_handle();
5421 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5422 return;
5423 };
5424 let on_release_callback = Box::new(move |cx: &mut App| {
5425 window_handle
5426 .update(cx, |_, window, cx| {
5427 workspace
5428 .update(cx, |workspace, cx| {
5429 workspace.dirty_items.remove(&item_id);
5430 workspace.update_window_edited(window, cx)
5431 })
5432 .ok();
5433 })
5434 .ok();
5435 });
5436
5437 let s = item.on_release(cx, on_release_callback);
5438 self.dirty_items.insert(item_id, s);
5439 self.update_window_edited(window, cx);
5440 }
5441
5442 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5443 if self.notifications.is_empty() {
5444 None
5445 } else {
5446 Some(
5447 div()
5448 .absolute()
5449 .right_3()
5450 .bottom_3()
5451 .w_112()
5452 .h_full()
5453 .flex()
5454 .flex_col()
5455 .justify_end()
5456 .gap_2()
5457 .children(
5458 self.notifications
5459 .iter()
5460 .map(|(_, notification)| notification.clone().into_any()),
5461 ),
5462 )
5463 }
5464 }
5465
5466 // RPC handlers
5467
5468 fn active_view_for_follower(
5469 &self,
5470 follower_project_id: Option<u64>,
5471 window: &mut Window,
5472 cx: &mut Context<Self>,
5473 ) -> Option<proto::View> {
5474 let (item, panel_id) = self.active_item_for_followers(window, cx);
5475 let item = item?;
5476 let leader_id = self
5477 .pane_for(&*item)
5478 .and_then(|pane| self.leader_for_pane(&pane));
5479 let leader_peer_id = match leader_id {
5480 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5481 Some(CollaboratorId::Agent) | None => None,
5482 };
5483
5484 let item_handle = item.to_followable_item_handle(cx)?;
5485 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5486 let variant = item_handle.to_state_proto(window, cx)?;
5487
5488 if item_handle.is_project_item(window, cx)
5489 && (follower_project_id.is_none()
5490 || follower_project_id != self.project.read(cx).remote_id())
5491 {
5492 return None;
5493 }
5494
5495 Some(proto::View {
5496 id: id.to_proto(),
5497 leader_id: leader_peer_id,
5498 variant: Some(variant),
5499 panel_id: panel_id.map(|id| id as i32),
5500 })
5501 }
5502
5503 fn handle_follow(
5504 &mut self,
5505 follower_project_id: Option<u64>,
5506 window: &mut Window,
5507 cx: &mut Context<Self>,
5508 ) -> proto::FollowResponse {
5509 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5510
5511 cx.notify();
5512 proto::FollowResponse {
5513 views: active_view.iter().cloned().collect(),
5514 active_view,
5515 }
5516 }
5517
5518 fn handle_update_followers(
5519 &mut self,
5520 leader_id: PeerId,
5521 message: proto::UpdateFollowers,
5522 _window: &mut Window,
5523 _cx: &mut Context<Self>,
5524 ) {
5525 self.leader_updates_tx
5526 .unbounded_send((leader_id, message))
5527 .ok();
5528 }
5529
5530 async fn process_leader_update(
5531 this: &WeakEntity<Self>,
5532 leader_id: PeerId,
5533 update: proto::UpdateFollowers,
5534 cx: &mut AsyncWindowContext,
5535 ) -> Result<()> {
5536 match update.variant.context("invalid update")? {
5537 proto::update_followers::Variant::CreateView(view) => {
5538 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5539 let should_add_view = this.update(cx, |this, _| {
5540 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5541 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5542 } else {
5543 anyhow::Ok(false)
5544 }
5545 })??;
5546
5547 if should_add_view {
5548 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5549 }
5550 }
5551 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5552 let should_add_view = this.update(cx, |this, _| {
5553 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5554 state.active_view_id = update_active_view
5555 .view
5556 .as_ref()
5557 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5558
5559 if state.active_view_id.is_some_and(|view_id| {
5560 !state.items_by_leader_view_id.contains_key(&view_id)
5561 }) {
5562 anyhow::Ok(true)
5563 } else {
5564 anyhow::Ok(false)
5565 }
5566 } else {
5567 anyhow::Ok(false)
5568 }
5569 })??;
5570
5571 if should_add_view && let Some(view) = update_active_view.view {
5572 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5573 }
5574 }
5575 proto::update_followers::Variant::UpdateView(update_view) => {
5576 let variant = update_view.variant.context("missing update view variant")?;
5577 let id = update_view.id.context("missing update view id")?;
5578 let mut tasks = Vec::new();
5579 this.update_in(cx, |this, window, cx| {
5580 let project = this.project.clone();
5581 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5582 let view_id = ViewId::from_proto(id.clone())?;
5583 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5584 tasks.push(item.view.apply_update_proto(
5585 &project,
5586 variant.clone(),
5587 window,
5588 cx,
5589 ));
5590 }
5591 }
5592 anyhow::Ok(())
5593 })??;
5594 try_join_all(tasks).await.log_err();
5595 }
5596 }
5597 this.update_in(cx, |this, window, cx| {
5598 this.leader_updated(leader_id, window, cx)
5599 })?;
5600 Ok(())
5601 }
5602
5603 async fn add_view_from_leader(
5604 this: WeakEntity<Self>,
5605 leader_id: PeerId,
5606 view: &proto::View,
5607 cx: &mut AsyncWindowContext,
5608 ) -> Result<()> {
5609 let this = this.upgrade().context("workspace dropped")?;
5610
5611 let Some(id) = view.id.clone() else {
5612 anyhow::bail!("no id for view");
5613 };
5614 let id = ViewId::from_proto(id)?;
5615 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5616
5617 let pane = this.update(cx, |this, _cx| {
5618 let state = this
5619 .follower_states
5620 .get(&leader_id.into())
5621 .context("stopped following")?;
5622 anyhow::Ok(state.pane().clone())
5623 })?;
5624 let existing_item = pane.update_in(cx, |pane, window, cx| {
5625 let client = this.read(cx).client().clone();
5626 pane.items().find_map(|item| {
5627 let item = item.to_followable_item_handle(cx)?;
5628 if item.remote_id(&client, window, cx) == Some(id) {
5629 Some(item)
5630 } else {
5631 None
5632 }
5633 })
5634 })?;
5635 let item = if let Some(existing_item) = existing_item {
5636 existing_item
5637 } else {
5638 let variant = view.variant.clone();
5639 anyhow::ensure!(variant.is_some(), "missing view variant");
5640
5641 let task = cx.update(|window, cx| {
5642 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5643 })?;
5644
5645 let Some(task) = task else {
5646 anyhow::bail!(
5647 "failed to construct view from leader (maybe from a different version of zed?)"
5648 );
5649 };
5650
5651 let mut new_item = task.await?;
5652 pane.update_in(cx, |pane, window, cx| {
5653 let mut item_to_remove = None;
5654 for (ix, item) in pane.items().enumerate() {
5655 if let Some(item) = item.to_followable_item_handle(cx) {
5656 match new_item.dedup(item.as_ref(), window, cx) {
5657 Some(item::Dedup::KeepExisting) => {
5658 new_item =
5659 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5660 break;
5661 }
5662 Some(item::Dedup::ReplaceExisting) => {
5663 item_to_remove = Some((ix, item.item_id()));
5664 break;
5665 }
5666 None => {}
5667 }
5668 }
5669 }
5670
5671 if let Some((ix, id)) = item_to_remove {
5672 pane.remove_item(id, false, false, window, cx);
5673 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5674 }
5675 })?;
5676
5677 new_item
5678 };
5679
5680 this.update_in(cx, |this, window, cx| {
5681 let state = this.follower_states.get_mut(&leader_id.into())?;
5682 item.set_leader_id(Some(leader_id.into()), window, cx);
5683 state.items_by_leader_view_id.insert(
5684 id,
5685 FollowerView {
5686 view: item,
5687 location: panel_id,
5688 },
5689 );
5690
5691 Some(())
5692 })
5693 .context("no follower state")?;
5694
5695 Ok(())
5696 }
5697
5698 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5699 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5700 return;
5701 };
5702
5703 if let Some(agent_location) = self.project.read(cx).agent_location() {
5704 let buffer_entity_id = agent_location.buffer.entity_id();
5705 let view_id = ViewId {
5706 creator: CollaboratorId::Agent,
5707 id: buffer_entity_id.as_u64(),
5708 };
5709 follower_state.active_view_id = Some(view_id);
5710
5711 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5712 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5713 hash_map::Entry::Vacant(entry) => {
5714 let existing_view =
5715 follower_state
5716 .center_pane
5717 .read(cx)
5718 .items()
5719 .find_map(|item| {
5720 let item = item.to_followable_item_handle(cx)?;
5721 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5722 && item.project_item_model_ids(cx).as_slice()
5723 == [buffer_entity_id]
5724 {
5725 Some(item)
5726 } else {
5727 None
5728 }
5729 });
5730 let view = existing_view.or_else(|| {
5731 agent_location.buffer.upgrade().and_then(|buffer| {
5732 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
5733 registry.build_item(buffer, self.project.clone(), None, window, cx)
5734 })?
5735 .to_followable_item_handle(cx)
5736 })
5737 });
5738
5739 view.map(|view| {
5740 entry.insert(FollowerView {
5741 view,
5742 location: None,
5743 })
5744 })
5745 }
5746 };
5747
5748 if let Some(item) = item {
5749 item.view
5750 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
5751 item.view
5752 .update_agent_location(agent_location.position, window, cx);
5753 }
5754 } else {
5755 follower_state.active_view_id = None;
5756 }
5757
5758 self.leader_updated(CollaboratorId::Agent, window, cx);
5759 }
5760
5761 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
5762 let mut is_project_item = true;
5763 let mut update = proto::UpdateActiveView::default();
5764 if window.is_window_active() {
5765 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
5766
5767 if let Some(item) = active_item
5768 && item.item_focus_handle(cx).contains_focused(window, cx)
5769 {
5770 let leader_id = self
5771 .pane_for(&*item)
5772 .and_then(|pane| self.leader_for_pane(&pane));
5773 let leader_peer_id = match leader_id {
5774 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5775 Some(CollaboratorId::Agent) | None => None,
5776 };
5777
5778 if let Some(item) = item.to_followable_item_handle(cx) {
5779 let id = item
5780 .remote_id(&self.app_state.client, window, cx)
5781 .map(|id| id.to_proto());
5782
5783 if let Some(id) = id
5784 && let Some(variant) = item.to_state_proto(window, cx)
5785 {
5786 let view = Some(proto::View {
5787 id,
5788 leader_id: leader_peer_id,
5789 variant: Some(variant),
5790 panel_id: panel_id.map(|id| id as i32),
5791 });
5792
5793 is_project_item = item.is_project_item(window, cx);
5794 update = proto::UpdateActiveView { view };
5795 };
5796 }
5797 }
5798 }
5799
5800 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
5801 if active_view_id != self.last_active_view_id.as_ref() {
5802 self.last_active_view_id = active_view_id.cloned();
5803 self.update_followers(
5804 is_project_item,
5805 proto::update_followers::Variant::UpdateActiveView(update),
5806 window,
5807 cx,
5808 );
5809 }
5810 }
5811
5812 fn active_item_for_followers(
5813 &self,
5814 window: &mut Window,
5815 cx: &mut App,
5816 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
5817 let mut active_item = None;
5818 let mut panel_id = None;
5819 for dock in self.all_docks() {
5820 if dock.focus_handle(cx).contains_focused(window, cx)
5821 && let Some(panel) = dock.read(cx).active_panel()
5822 && let Some(pane) = panel.pane(cx)
5823 && let Some(item) = pane.read(cx).active_item()
5824 {
5825 active_item = Some(item);
5826 panel_id = panel.remote_id();
5827 break;
5828 }
5829 }
5830
5831 if active_item.is_none() {
5832 active_item = self.active_pane().read(cx).active_item();
5833 }
5834 (active_item, panel_id)
5835 }
5836
5837 fn update_followers(
5838 &self,
5839 project_only: bool,
5840 update: proto::update_followers::Variant,
5841 _: &mut Window,
5842 cx: &mut App,
5843 ) -> Option<()> {
5844 // If this update only applies to for followers in the current project,
5845 // then skip it unless this project is shared. If it applies to all
5846 // followers, regardless of project, then set `project_id` to none,
5847 // indicating that it goes to all followers.
5848 let project_id = if project_only {
5849 Some(self.project.read(cx).remote_id()?)
5850 } else {
5851 None
5852 };
5853 self.app_state().workspace_store.update(cx, |store, cx| {
5854 store.update_followers(project_id, update, cx)
5855 })
5856 }
5857
5858 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
5859 self.follower_states.iter().find_map(|(leader_id, state)| {
5860 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
5861 Some(*leader_id)
5862 } else {
5863 None
5864 }
5865 })
5866 }
5867
5868 fn leader_updated(
5869 &mut self,
5870 leader_id: impl Into<CollaboratorId>,
5871 window: &mut Window,
5872 cx: &mut Context<Self>,
5873 ) -> Option<Box<dyn ItemHandle>> {
5874 cx.notify();
5875
5876 let leader_id = leader_id.into();
5877 let (panel_id, item) = match leader_id {
5878 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
5879 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
5880 };
5881
5882 let state = self.follower_states.get(&leader_id)?;
5883 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
5884 let pane;
5885 if let Some(panel_id) = panel_id {
5886 pane = self
5887 .activate_panel_for_proto_id(panel_id, window, cx)?
5888 .pane(cx)?;
5889 let state = self.follower_states.get_mut(&leader_id)?;
5890 state.dock_pane = Some(pane.clone());
5891 } else {
5892 pane = state.center_pane.clone();
5893 let state = self.follower_states.get_mut(&leader_id)?;
5894 if let Some(dock_pane) = state.dock_pane.take() {
5895 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
5896 }
5897 }
5898
5899 pane.update(cx, |pane, cx| {
5900 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
5901 if let Some(index) = pane.index_for_item(item.as_ref()) {
5902 pane.activate_item(index, false, false, window, cx);
5903 } else {
5904 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
5905 }
5906
5907 if focus_active_item {
5908 pane.focus_active_item(window, cx)
5909 }
5910 });
5911
5912 Some(item)
5913 }
5914
5915 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
5916 let state = self.follower_states.get(&CollaboratorId::Agent)?;
5917 let active_view_id = state.active_view_id?;
5918 Some(
5919 state
5920 .items_by_leader_view_id
5921 .get(&active_view_id)?
5922 .view
5923 .boxed_clone(),
5924 )
5925 }
5926
5927 fn active_item_for_peer(
5928 &self,
5929 peer_id: PeerId,
5930 window: &mut Window,
5931 cx: &mut Context<Self>,
5932 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
5933 let call = self.active_call()?;
5934 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
5935 let leader_in_this_app;
5936 let leader_in_this_project;
5937 match participant.location {
5938 ParticipantLocation::SharedProject { project_id } => {
5939 leader_in_this_app = true;
5940 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
5941 }
5942 ParticipantLocation::UnsharedProject => {
5943 leader_in_this_app = true;
5944 leader_in_this_project = false;
5945 }
5946 ParticipantLocation::External => {
5947 leader_in_this_app = false;
5948 leader_in_this_project = false;
5949 }
5950 };
5951 let state = self.follower_states.get(&peer_id.into())?;
5952 let mut item_to_activate = None;
5953 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
5954 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
5955 && (leader_in_this_project || !item.view.is_project_item(window, cx))
5956 {
5957 item_to_activate = Some((item.location, item.view.boxed_clone()));
5958 }
5959 } else if let Some(shared_screen) =
5960 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
5961 {
5962 item_to_activate = Some((None, Box::new(shared_screen)));
5963 }
5964 item_to_activate
5965 }
5966
5967 fn shared_screen_for_peer(
5968 &self,
5969 peer_id: PeerId,
5970 pane: &Entity<Pane>,
5971 window: &mut Window,
5972 cx: &mut App,
5973 ) -> Option<Entity<SharedScreen>> {
5974 self.active_call()?
5975 .create_shared_screen(peer_id, pane, window, cx)
5976 }
5977
5978 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5979 if window.is_window_active() {
5980 self.update_active_view_for_followers(window, cx);
5981
5982 if let Some(database_id) = self.database_id {
5983 let db = WorkspaceDb::global(cx);
5984 cx.background_spawn(async move { db.update_timestamp(database_id).await })
5985 .detach();
5986 }
5987 } else {
5988 for pane in &self.panes {
5989 pane.update(cx, |pane, cx| {
5990 if let Some(item) = pane.active_item() {
5991 item.workspace_deactivated(window, cx);
5992 }
5993 for item in pane.items() {
5994 if matches!(
5995 item.workspace_settings(cx).autosave,
5996 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
5997 ) {
5998 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
5999 .detach_and_log_err(cx);
6000 }
6001 }
6002 });
6003 }
6004 }
6005 }
6006
6007 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
6008 self.active_call.as_ref().map(|(call, _)| &*call.0)
6009 }
6010
6011 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
6012 self.active_call.as_ref().map(|(call, _)| call.clone())
6013 }
6014
6015 fn on_active_call_event(
6016 &mut self,
6017 event: &ActiveCallEvent,
6018 window: &mut Window,
6019 cx: &mut Context<Self>,
6020 ) {
6021 match event {
6022 ActiveCallEvent::ParticipantLocationChanged { participant_id }
6023 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
6024 self.leader_updated(participant_id, window, cx);
6025 }
6026 }
6027 }
6028
6029 pub fn database_id(&self) -> Option<WorkspaceId> {
6030 self.database_id
6031 }
6032
6033 #[cfg(any(test, feature = "test-support"))]
6034 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
6035 self.database_id = Some(id);
6036 }
6037
6038 pub fn session_id(&self) -> Option<String> {
6039 self.session_id.clone()
6040 }
6041
6042 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6043 let Some(display) = window.display(cx) else {
6044 return Task::ready(());
6045 };
6046 let Ok(display_uuid) = display.uuid() else {
6047 return Task::ready(());
6048 };
6049
6050 let window_bounds = window.inner_window_bounds();
6051 let database_id = self.database_id;
6052 let has_paths = !self.root_paths(cx).is_empty();
6053 let db = WorkspaceDb::global(cx);
6054 let kvp = db::kvp::KeyValueStore::global(cx);
6055
6056 cx.background_executor().spawn(async move {
6057 if !has_paths {
6058 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6059 .await
6060 .log_err();
6061 }
6062 if let Some(database_id) = database_id {
6063 db.set_window_open_status(
6064 database_id,
6065 SerializedWindowBounds(window_bounds),
6066 display_uuid,
6067 )
6068 .await
6069 .log_err();
6070 } else {
6071 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6072 .await
6073 .log_err();
6074 }
6075 })
6076 }
6077
6078 /// Bypass the 200ms serialization throttle and write workspace state to
6079 /// the DB immediately. Returns a task the caller can await to ensure the
6080 /// write completes. Used by the quit handler so the most recent state
6081 /// isn't lost to a pending throttle timer when the process exits.
6082 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6083 self._schedule_serialize_workspace.take();
6084 self._serialize_workspace_task.take();
6085 self.bounds_save_task_queued.take();
6086
6087 let bounds_task = self.save_window_bounds(window, cx);
6088 let serialize_task = self.serialize_workspace_internal(window, cx);
6089 cx.spawn(async move |_| {
6090 bounds_task.await;
6091 serialize_task.await;
6092 })
6093 }
6094
6095 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6096 let project = self.project().read(cx);
6097 project
6098 .visible_worktrees(cx)
6099 .map(|worktree| worktree.read(cx).abs_path())
6100 .collect::<Vec<_>>()
6101 }
6102
6103 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6104 match member {
6105 Member::Axis(PaneAxis { members, .. }) => {
6106 for child in members.iter() {
6107 self.remove_panes(child.clone(), window, cx)
6108 }
6109 }
6110 Member::Pane(pane) => {
6111 self.force_remove_pane(&pane, &None, window, cx);
6112 }
6113 }
6114 }
6115
6116 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6117 self.session_id.take();
6118 self.serialize_workspace_internal(window, cx)
6119 }
6120
6121 fn force_remove_pane(
6122 &mut self,
6123 pane: &Entity<Pane>,
6124 focus_on: &Option<Entity<Pane>>,
6125 window: &mut Window,
6126 cx: &mut Context<Workspace>,
6127 ) {
6128 self.panes.retain(|p| p != pane);
6129 if let Some(focus_on) = focus_on {
6130 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6131 } else if self.active_pane() == pane {
6132 self.panes
6133 .last()
6134 .unwrap()
6135 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6136 }
6137 if self.last_active_center_pane == Some(pane.downgrade()) {
6138 self.last_active_center_pane = None;
6139 }
6140 cx.notify();
6141 }
6142
6143 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6144 if self._schedule_serialize_workspace.is_none() {
6145 self._schedule_serialize_workspace =
6146 Some(cx.spawn_in(window, async move |this, cx| {
6147 cx.background_executor()
6148 .timer(SERIALIZATION_THROTTLE_TIME)
6149 .await;
6150 this.update_in(cx, |this, window, cx| {
6151 this._serialize_workspace_task =
6152 Some(this.serialize_workspace_internal(window, cx));
6153 this._schedule_serialize_workspace.take();
6154 })
6155 .log_err();
6156 }));
6157 }
6158 }
6159
6160 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6161 let Some(database_id) = self.database_id() else {
6162 return Task::ready(());
6163 };
6164
6165 fn serialize_pane_handle(
6166 pane_handle: &Entity<Pane>,
6167 window: &mut Window,
6168 cx: &mut App,
6169 ) -> SerializedPane {
6170 let (items, active, pinned_count) = {
6171 let pane = pane_handle.read(cx);
6172 let active_item_id = pane.active_item().map(|item| item.item_id());
6173 (
6174 pane.items()
6175 .filter_map(|handle| {
6176 let handle = handle.to_serializable_item_handle(cx)?;
6177
6178 Some(SerializedItem {
6179 kind: Arc::from(handle.serialized_item_kind()),
6180 item_id: handle.item_id().as_u64(),
6181 active: Some(handle.item_id()) == active_item_id,
6182 preview: pane.is_active_preview_item(handle.item_id()),
6183 })
6184 })
6185 .collect::<Vec<_>>(),
6186 pane.has_focus(window, cx),
6187 pane.pinned_count(),
6188 )
6189 };
6190
6191 SerializedPane::new(items, active, pinned_count)
6192 }
6193
6194 fn build_serialized_pane_group(
6195 pane_group: &Member,
6196 window: &mut Window,
6197 cx: &mut App,
6198 ) -> SerializedPaneGroup {
6199 match pane_group {
6200 Member::Axis(PaneAxis {
6201 axis,
6202 members,
6203 flexes,
6204 bounding_boxes: _,
6205 }) => SerializedPaneGroup::Group {
6206 axis: SerializedAxis(*axis),
6207 children: members
6208 .iter()
6209 .map(|member| build_serialized_pane_group(member, window, cx))
6210 .collect::<Vec<_>>(),
6211 flexes: Some(flexes.lock().clone()),
6212 },
6213 Member::Pane(pane_handle) => {
6214 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6215 }
6216 }
6217 }
6218
6219 fn build_serialized_docks(
6220 this: &Workspace,
6221 window: &mut Window,
6222 cx: &mut App,
6223 ) -> DockStructure {
6224 this.capture_dock_state(window, cx)
6225 }
6226
6227 match self.workspace_location(cx) {
6228 WorkspaceLocation::Location(location, paths) => {
6229 let breakpoints = self.project.update(cx, |project, cx| {
6230 project
6231 .breakpoint_store()
6232 .read(cx)
6233 .all_source_breakpoints(cx)
6234 });
6235 let user_toolchains = self
6236 .project
6237 .read(cx)
6238 .user_toolchains(cx)
6239 .unwrap_or_default();
6240
6241 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6242 let docks = build_serialized_docks(self, window, cx);
6243 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6244
6245 let serialized_workspace = SerializedWorkspace {
6246 id: database_id,
6247 location,
6248 paths,
6249 center_group,
6250 window_bounds,
6251 display: Default::default(),
6252 docks,
6253 centered_layout: self.centered_layout,
6254 session_id: self.session_id.clone(),
6255 breakpoints,
6256 window_id: Some(window.window_handle().window_id().as_u64()),
6257 user_toolchains,
6258 };
6259
6260 let db = WorkspaceDb::global(cx);
6261 window.spawn(cx, async move |_| {
6262 db.save_workspace(serialized_workspace).await;
6263 })
6264 }
6265 WorkspaceLocation::DetachFromSession => {
6266 let window_bounds = SerializedWindowBounds(window.window_bounds());
6267 let display = window.display(cx).and_then(|d| d.uuid().ok());
6268 // Save dock state for empty local workspaces
6269 let docks = build_serialized_docks(self, window, cx);
6270 let db = WorkspaceDb::global(cx);
6271 let kvp = db::kvp::KeyValueStore::global(cx);
6272 window.spawn(cx, async move |_| {
6273 db.set_window_open_status(
6274 database_id,
6275 window_bounds,
6276 display.unwrap_or_default(),
6277 )
6278 .await
6279 .log_err();
6280 db.set_session_id(database_id, None).await.log_err();
6281 persistence::write_default_dock_state(&kvp, docks)
6282 .await
6283 .log_err();
6284 })
6285 }
6286 WorkspaceLocation::None => {
6287 // Save dock state for empty non-local workspaces
6288 let docks = build_serialized_docks(self, window, cx);
6289 let kvp = db::kvp::KeyValueStore::global(cx);
6290 window.spawn(cx, async move |_| {
6291 persistence::write_default_dock_state(&kvp, docks)
6292 .await
6293 .log_err();
6294 })
6295 }
6296 }
6297 }
6298
6299 fn has_any_items_open(&self, cx: &App) -> bool {
6300 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6301 }
6302
6303 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6304 let paths = PathList::new(&self.root_paths(cx));
6305 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6306 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6307 } else if self.project.read(cx).is_local() {
6308 if !paths.is_empty() || self.has_any_items_open(cx) {
6309 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6310 } else {
6311 WorkspaceLocation::DetachFromSession
6312 }
6313 } else {
6314 WorkspaceLocation::None
6315 }
6316 }
6317
6318 fn update_history(&self, cx: &mut App) {
6319 let Some(id) = self.database_id() else {
6320 return;
6321 };
6322 if !self.project.read(cx).is_local() {
6323 return;
6324 }
6325 if let Some(manager) = HistoryManager::global(cx) {
6326 let paths = PathList::new(&self.root_paths(cx));
6327 manager.update(cx, |this, cx| {
6328 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6329 });
6330 }
6331 }
6332
6333 async fn serialize_items(
6334 this: &WeakEntity<Self>,
6335 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6336 cx: &mut AsyncWindowContext,
6337 ) -> Result<()> {
6338 const CHUNK_SIZE: usize = 200;
6339
6340 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6341
6342 while let Some(items_received) = serializable_items.next().await {
6343 let unique_items =
6344 items_received
6345 .into_iter()
6346 .fold(HashMap::default(), |mut acc, item| {
6347 acc.entry(item.item_id()).or_insert(item);
6348 acc
6349 });
6350
6351 // We use into_iter() here so that the references to the items are moved into
6352 // the tasks and not kept alive while we're sleeping.
6353 for (_, item) in unique_items.into_iter() {
6354 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6355 item.serialize(workspace, false, window, cx)
6356 }) {
6357 cx.background_spawn(async move { task.await.log_err() })
6358 .detach();
6359 }
6360 }
6361
6362 cx.background_executor()
6363 .timer(SERIALIZATION_THROTTLE_TIME)
6364 .await;
6365 }
6366
6367 Ok(())
6368 }
6369
6370 pub(crate) fn enqueue_item_serialization(
6371 &mut self,
6372 item: Box<dyn SerializableItemHandle>,
6373 ) -> Result<()> {
6374 self.serializable_items_tx
6375 .unbounded_send(item)
6376 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6377 }
6378
6379 pub(crate) fn load_workspace(
6380 serialized_workspace: SerializedWorkspace,
6381 paths_to_open: Vec<Option<ProjectPath>>,
6382 window: &mut Window,
6383 cx: &mut Context<Workspace>,
6384 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6385 cx.spawn_in(window, async move |workspace, cx| {
6386 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6387
6388 let mut center_group = None;
6389 let mut center_items = None;
6390
6391 // Traverse the splits tree and add to things
6392 if let Some((group, active_pane, items)) = serialized_workspace
6393 .center_group
6394 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6395 .await
6396 {
6397 center_items = Some(items);
6398 center_group = Some((group, active_pane))
6399 }
6400
6401 let mut items_by_project_path = HashMap::default();
6402 let mut item_ids_by_kind = HashMap::default();
6403 let mut all_deserialized_items = Vec::default();
6404 cx.update(|_, cx| {
6405 for item in center_items.unwrap_or_default().into_iter().flatten() {
6406 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6407 item_ids_by_kind
6408 .entry(serializable_item_handle.serialized_item_kind())
6409 .or_insert(Vec::new())
6410 .push(item.item_id().as_u64() as ItemId);
6411 }
6412
6413 if let Some(project_path) = item.project_path(cx) {
6414 items_by_project_path.insert(project_path, item.clone());
6415 }
6416 all_deserialized_items.push(item);
6417 }
6418 })?;
6419
6420 let opened_items = paths_to_open
6421 .into_iter()
6422 .map(|path_to_open| {
6423 path_to_open
6424 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6425 })
6426 .collect::<Vec<_>>();
6427
6428 // Remove old panes from workspace panes list
6429 workspace.update_in(cx, |workspace, window, cx| {
6430 if let Some((center_group, active_pane)) = center_group {
6431 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6432
6433 // Swap workspace center group
6434 workspace.center = PaneGroup::with_root(center_group);
6435 workspace.center.set_is_center(true);
6436 workspace.center.mark_positions(cx);
6437
6438 if let Some(active_pane) = active_pane {
6439 workspace.set_active_pane(&active_pane, window, cx);
6440 cx.focus_self(window);
6441 } else {
6442 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6443 }
6444 }
6445
6446 let docks = serialized_workspace.docks;
6447
6448 for (dock, serialized_dock) in [
6449 (&mut workspace.right_dock, docks.right),
6450 (&mut workspace.left_dock, docks.left),
6451 (&mut workspace.bottom_dock, docks.bottom),
6452 ]
6453 .iter_mut()
6454 {
6455 dock.update(cx, |dock, cx| {
6456 dock.serialized_dock = Some(serialized_dock.clone());
6457 dock.restore_state(window, cx);
6458 });
6459 }
6460
6461 cx.notify();
6462 })?;
6463
6464 let _ = project
6465 .update(cx, |project, cx| {
6466 project
6467 .breakpoint_store()
6468 .update(cx, |breakpoint_store, cx| {
6469 breakpoint_store
6470 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6471 })
6472 })
6473 .await;
6474
6475 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6476 // after loading the items, we might have different items and in order to avoid
6477 // the database filling up, we delete items that haven't been loaded now.
6478 //
6479 // The items that have been loaded, have been saved after they've been added to the workspace.
6480 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6481 item_ids_by_kind
6482 .into_iter()
6483 .map(|(item_kind, loaded_items)| {
6484 SerializableItemRegistry::cleanup(
6485 item_kind,
6486 serialized_workspace.id,
6487 loaded_items,
6488 window,
6489 cx,
6490 )
6491 .log_err()
6492 })
6493 .collect::<Vec<_>>()
6494 })?;
6495
6496 futures::future::join_all(clean_up_tasks).await;
6497
6498 workspace
6499 .update_in(cx, |workspace, window, cx| {
6500 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6501 workspace.serialize_workspace_internal(window, cx).detach();
6502
6503 // Ensure that we mark the window as edited if we did load dirty items
6504 workspace.update_window_edited(window, cx);
6505 })
6506 .ok();
6507
6508 Ok(opened_items)
6509 })
6510 }
6511
6512 pub fn key_context(&self, cx: &App) -> KeyContext {
6513 let mut context = KeyContext::new_with_defaults();
6514 context.add("Workspace");
6515 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6516 if let Some(status) = self
6517 .debugger_provider
6518 .as_ref()
6519 .and_then(|provider| provider.active_thread_state(cx))
6520 {
6521 match status {
6522 ThreadStatus::Running | ThreadStatus::Stepping => {
6523 context.add("debugger_running");
6524 }
6525 ThreadStatus::Stopped => context.add("debugger_stopped"),
6526 ThreadStatus::Exited | ThreadStatus::Ended => {}
6527 }
6528 }
6529
6530 if self.left_dock.read(cx).is_open() {
6531 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6532 context.set("left_dock", active_panel.panel_key());
6533 }
6534 }
6535
6536 if self.right_dock.read(cx).is_open() {
6537 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6538 context.set("right_dock", active_panel.panel_key());
6539 }
6540 }
6541
6542 if self.bottom_dock.read(cx).is_open() {
6543 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6544 context.set("bottom_dock", active_panel.panel_key());
6545 }
6546 }
6547
6548 context
6549 }
6550
6551 /// Multiworkspace uses this to add workspace action handling to itself
6552 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6553 self.add_workspace_actions_listeners(div, window, cx)
6554 .on_action(cx.listener(
6555 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6556 for action in &action_sequence.0 {
6557 window.dispatch_action(action.boxed_clone(), cx);
6558 }
6559 },
6560 ))
6561 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6562 .on_action(cx.listener(Self::close_all_items_and_panes))
6563 .on_action(cx.listener(Self::close_item_in_all_panes))
6564 .on_action(cx.listener(Self::save_all))
6565 .on_action(cx.listener(Self::send_keystrokes))
6566 .on_action(cx.listener(Self::add_folder_to_project))
6567 .on_action(cx.listener(Self::follow_next_collaborator))
6568 .on_action(cx.listener(Self::activate_pane_at_index))
6569 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6570 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6571 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6572 .on_action(cx.listener(Self::toggle_theme_mode))
6573 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6574 let pane = workspace.active_pane().clone();
6575 workspace.unfollow_in_pane(&pane, window, cx);
6576 }))
6577 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6578 workspace
6579 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6580 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6581 }))
6582 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6583 workspace
6584 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6585 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6586 }))
6587 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6588 workspace
6589 .save_active_item(SaveIntent::SaveAs, window, cx)
6590 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6591 }))
6592 .on_action(
6593 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6594 workspace.activate_previous_pane(window, cx)
6595 }),
6596 )
6597 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6598 workspace.activate_next_pane(window, cx)
6599 }))
6600 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6601 workspace.activate_last_pane(window, cx)
6602 }))
6603 .on_action(
6604 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6605 workspace.activate_next_window(cx)
6606 }),
6607 )
6608 .on_action(
6609 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6610 workspace.activate_previous_window(cx)
6611 }),
6612 )
6613 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6614 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6615 }))
6616 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6617 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6618 }))
6619 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6620 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6621 }))
6622 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6623 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6624 }))
6625 .on_action(cx.listener(
6626 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6627 workspace.move_item_to_pane_in_direction(action, window, cx)
6628 },
6629 ))
6630 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6631 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6632 }))
6633 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6634 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6635 }))
6636 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6637 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6638 }))
6639 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6640 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6641 }))
6642 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6643 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6644 SplitDirection::Down,
6645 SplitDirection::Up,
6646 SplitDirection::Right,
6647 SplitDirection::Left,
6648 ];
6649 for dir in DIRECTION_PRIORITY {
6650 if workspace.find_pane_in_direction(dir, cx).is_some() {
6651 workspace.swap_pane_in_direction(dir, cx);
6652 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6653 break;
6654 }
6655 }
6656 }))
6657 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6658 workspace.move_pane_to_border(SplitDirection::Left, cx)
6659 }))
6660 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6661 workspace.move_pane_to_border(SplitDirection::Right, cx)
6662 }))
6663 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6664 workspace.move_pane_to_border(SplitDirection::Up, cx)
6665 }))
6666 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6667 workspace.move_pane_to_border(SplitDirection::Down, cx)
6668 }))
6669 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6670 this.toggle_dock(DockPosition::Left, window, cx);
6671 }))
6672 .on_action(cx.listener(
6673 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6674 workspace.toggle_dock(DockPosition::Right, window, cx);
6675 },
6676 ))
6677 .on_action(cx.listener(
6678 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6679 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6680 },
6681 ))
6682 .on_action(cx.listener(
6683 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6684 if !workspace.close_active_dock(window, cx) {
6685 cx.propagate();
6686 }
6687 },
6688 ))
6689 .on_action(
6690 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6691 workspace.close_all_docks(window, cx);
6692 }),
6693 )
6694 .on_action(cx.listener(Self::toggle_all_docks))
6695 .on_action(cx.listener(
6696 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6697 workspace.clear_all_notifications(cx);
6698 },
6699 ))
6700 .on_action(cx.listener(
6701 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6702 workspace.clear_navigation_history(window, cx);
6703 },
6704 ))
6705 .on_action(cx.listener(
6706 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6707 if let Some((notification_id, _)) = workspace.notifications.pop() {
6708 workspace.suppress_notification(¬ification_id, cx);
6709 }
6710 },
6711 ))
6712 .on_action(cx.listener(
6713 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6714 workspace.show_worktree_trust_security_modal(true, window, cx);
6715 },
6716 ))
6717 .on_action(
6718 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6719 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6720 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6721 trusted_worktrees.clear_trusted_paths()
6722 });
6723 let db = WorkspaceDb::global(cx);
6724 cx.spawn(async move |_, cx| {
6725 if db.clear_trusted_worktrees().await.log_err().is_some() {
6726 cx.update(|cx| reload(cx));
6727 }
6728 })
6729 .detach();
6730 }
6731 }),
6732 )
6733 .on_action(cx.listener(
6734 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
6735 workspace.reopen_closed_item(window, cx).detach();
6736 },
6737 ))
6738 .on_action(cx.listener(
6739 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
6740 for dock in workspace.all_docks() {
6741 if dock.focus_handle(cx).contains_focused(window, cx) {
6742 let Some(panel) = dock.read(cx).active_panel() else {
6743 return;
6744 };
6745
6746 // Set to `None`, then the size will fall back to the default.
6747 panel.clone().set_size(None, window, cx);
6748
6749 return;
6750 }
6751 }
6752 },
6753 ))
6754 .on_action(cx.listener(
6755 |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
6756 for dock in workspace.all_docks() {
6757 if let Some(panel) = dock.read(cx).visible_panel() {
6758 // Set to `None`, then the size will fall back to the default.
6759 panel.clone().set_size(None, window, cx);
6760 }
6761 }
6762 },
6763 ))
6764 .on_action(cx.listener(
6765 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
6766 adjust_active_dock_size_by_px(
6767 px_with_ui_font_fallback(act.px, cx),
6768 workspace,
6769 window,
6770 cx,
6771 );
6772 },
6773 ))
6774 .on_action(cx.listener(
6775 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
6776 adjust_active_dock_size_by_px(
6777 px_with_ui_font_fallback(act.px, cx) * -1.,
6778 workspace,
6779 window,
6780 cx,
6781 );
6782 },
6783 ))
6784 .on_action(cx.listener(
6785 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
6786 adjust_open_docks_size_by_px(
6787 px_with_ui_font_fallback(act.px, cx),
6788 workspace,
6789 window,
6790 cx,
6791 );
6792 },
6793 ))
6794 .on_action(cx.listener(
6795 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
6796 adjust_open_docks_size_by_px(
6797 px_with_ui_font_fallback(act.px, cx) * -1.,
6798 workspace,
6799 window,
6800 cx,
6801 );
6802 },
6803 ))
6804 .on_action(cx.listener(Workspace::toggle_centered_layout))
6805 .on_action(cx.listener(
6806 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
6807 if let Some(active_dock) = workspace.active_dock(window, cx) {
6808 let dock = active_dock.read(cx);
6809 if let Some(active_panel) = dock.active_panel() {
6810 if active_panel.pane(cx).is_none() {
6811 let mut recent_pane: Option<Entity<Pane>> = None;
6812 let mut recent_timestamp = 0;
6813 for pane_handle in workspace.panes() {
6814 let pane = pane_handle.read(cx);
6815 for entry in pane.activation_history() {
6816 if entry.timestamp > recent_timestamp {
6817 recent_timestamp = entry.timestamp;
6818 recent_pane = Some(pane_handle.clone());
6819 }
6820 }
6821 }
6822
6823 if let Some(pane) = recent_pane {
6824 pane.update(cx, |pane, cx| {
6825 let current_index = pane.active_item_index();
6826 let items_len = pane.items_len();
6827 if items_len > 0 {
6828 let next_index = if current_index + 1 < items_len {
6829 current_index + 1
6830 } else {
6831 0
6832 };
6833 pane.activate_item(
6834 next_index, false, false, window, cx,
6835 );
6836 }
6837 });
6838 return;
6839 }
6840 }
6841 }
6842 }
6843 cx.propagate();
6844 },
6845 ))
6846 .on_action(cx.listener(
6847 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
6848 if let Some(active_dock) = workspace.active_dock(window, cx) {
6849 let dock = active_dock.read(cx);
6850 if let Some(active_panel) = dock.active_panel() {
6851 if active_panel.pane(cx).is_none() {
6852 let mut recent_pane: Option<Entity<Pane>> = None;
6853 let mut recent_timestamp = 0;
6854 for pane_handle in workspace.panes() {
6855 let pane = pane_handle.read(cx);
6856 for entry in pane.activation_history() {
6857 if entry.timestamp > recent_timestamp {
6858 recent_timestamp = entry.timestamp;
6859 recent_pane = Some(pane_handle.clone());
6860 }
6861 }
6862 }
6863
6864 if let Some(pane) = recent_pane {
6865 pane.update(cx, |pane, cx| {
6866 let current_index = pane.active_item_index();
6867 let items_len = pane.items_len();
6868 if items_len > 0 {
6869 let prev_index = if current_index > 0 {
6870 current_index - 1
6871 } else {
6872 items_len.saturating_sub(1)
6873 };
6874 pane.activate_item(
6875 prev_index, false, false, window, cx,
6876 );
6877 }
6878 });
6879 return;
6880 }
6881 }
6882 }
6883 }
6884 cx.propagate();
6885 },
6886 ))
6887 .on_action(cx.listener(
6888 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
6889 if let Some(active_dock) = workspace.active_dock(window, cx) {
6890 let dock = active_dock.read(cx);
6891 if let Some(active_panel) = dock.active_panel() {
6892 if active_panel.pane(cx).is_none() {
6893 let active_pane = workspace.active_pane().clone();
6894 active_pane.update(cx, |pane, cx| {
6895 pane.close_active_item(action, window, cx)
6896 .detach_and_log_err(cx);
6897 });
6898 return;
6899 }
6900 }
6901 }
6902 cx.propagate();
6903 },
6904 ))
6905 .on_action(
6906 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
6907 let pane = workspace.active_pane().clone();
6908 if let Some(item) = pane.read(cx).active_item() {
6909 item.toggle_read_only(window, cx);
6910 }
6911 }),
6912 )
6913 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
6914 workspace.focus_center_pane(window, cx);
6915 }))
6916 .on_action(cx.listener(Workspace::cancel))
6917 }
6918
6919 #[cfg(any(test, feature = "test-support"))]
6920 pub fn set_random_database_id(&mut self) {
6921 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
6922 }
6923
6924 #[cfg(any(test, feature = "test-support"))]
6925 pub(crate) fn test_new(
6926 project: Entity<Project>,
6927 window: &mut Window,
6928 cx: &mut Context<Self>,
6929 ) -> Self {
6930 use node_runtime::NodeRuntime;
6931 use session::Session;
6932
6933 let client = project.read(cx).client();
6934 let user_store = project.read(cx).user_store();
6935 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
6936 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
6937 window.activate_window();
6938 let app_state = Arc::new(AppState {
6939 languages: project.read(cx).languages().clone(),
6940 workspace_store,
6941 client,
6942 user_store,
6943 fs: project.read(cx).fs().clone(),
6944 build_window_options: |_, _| Default::default(),
6945 node_runtime: NodeRuntime::unavailable(),
6946 session,
6947 });
6948 let workspace = Self::new(Default::default(), project, app_state, window, cx);
6949 workspace
6950 .active_pane
6951 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6952 workspace
6953 }
6954
6955 pub fn register_action<A: Action>(
6956 &mut self,
6957 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
6958 ) -> &mut Self {
6959 let callback = Arc::new(callback);
6960
6961 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
6962 let callback = callback.clone();
6963 div.on_action(cx.listener(move |workspace, event, window, cx| {
6964 (callback)(workspace, event, window, cx)
6965 }))
6966 }));
6967 self
6968 }
6969 pub fn register_action_renderer(
6970 &mut self,
6971 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
6972 ) -> &mut Self {
6973 self.workspace_actions.push(Box::new(callback));
6974 self
6975 }
6976
6977 fn add_workspace_actions_listeners(
6978 &self,
6979 mut div: Div,
6980 window: &mut Window,
6981 cx: &mut Context<Self>,
6982 ) -> Div {
6983 for action in self.workspace_actions.iter() {
6984 div = (action)(div, self, window, cx)
6985 }
6986 div
6987 }
6988
6989 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
6990 self.modal_layer.read(cx).has_active_modal()
6991 }
6992
6993 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
6994 self.modal_layer.read(cx).active_modal()
6995 }
6996
6997 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
6998 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
6999 /// If no modal is active, the new modal will be shown.
7000 ///
7001 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
7002 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
7003 /// will not be shown.
7004 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
7005 where
7006 B: FnOnce(&mut Window, &mut Context<V>) -> V,
7007 {
7008 self.modal_layer.update(cx, |modal_layer, cx| {
7009 modal_layer.toggle_modal(window, cx, build)
7010 })
7011 }
7012
7013 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
7014 self.modal_layer
7015 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
7016 }
7017
7018 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
7019 self.toast_layer
7020 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
7021 }
7022
7023 pub fn toggle_centered_layout(
7024 &mut self,
7025 _: &ToggleCenteredLayout,
7026 _: &mut Window,
7027 cx: &mut Context<Self>,
7028 ) {
7029 self.centered_layout = !self.centered_layout;
7030 if let Some(database_id) = self.database_id() {
7031 let db = WorkspaceDb::global(cx);
7032 let centered_layout = self.centered_layout;
7033 cx.background_spawn(async move {
7034 db.set_centered_layout(database_id, centered_layout).await
7035 })
7036 .detach_and_log_err(cx);
7037 }
7038 cx.notify();
7039 }
7040
7041 fn adjust_padding(padding: Option<f32>) -> f32 {
7042 padding
7043 .unwrap_or(CenteredPaddingSettings::default().0)
7044 .clamp(
7045 CenteredPaddingSettings::MIN_PADDING,
7046 CenteredPaddingSettings::MAX_PADDING,
7047 )
7048 }
7049
7050 fn render_dock(
7051 &self,
7052 position: DockPosition,
7053 dock: &Entity<Dock>,
7054 window: &mut Window,
7055 cx: &mut App,
7056 ) -> Option<Div> {
7057 if self.zoomed_position == Some(position) {
7058 return None;
7059 }
7060
7061 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7062 let pane = panel.pane(cx)?;
7063 let follower_states = &self.follower_states;
7064 leader_border_for_pane(follower_states, &pane, window, cx)
7065 });
7066
7067 Some(
7068 div()
7069 .flex()
7070 .flex_none()
7071 .overflow_hidden()
7072 .child(dock.clone())
7073 .children(leader_border),
7074 )
7075 }
7076
7077 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7078 window
7079 .root::<MultiWorkspace>()
7080 .flatten()
7081 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7082 }
7083
7084 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7085 self.zoomed.as_ref()
7086 }
7087
7088 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7089 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7090 return;
7091 };
7092 let windows = cx.windows();
7093 let next_window =
7094 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7095 || {
7096 windows
7097 .iter()
7098 .cycle()
7099 .skip_while(|window| window.window_id() != current_window_id)
7100 .nth(1)
7101 },
7102 );
7103
7104 if let Some(window) = next_window {
7105 window
7106 .update(cx, |_, window, _| window.activate_window())
7107 .ok();
7108 }
7109 }
7110
7111 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7112 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7113 return;
7114 };
7115 let windows = cx.windows();
7116 let prev_window =
7117 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7118 || {
7119 windows
7120 .iter()
7121 .rev()
7122 .cycle()
7123 .skip_while(|window| window.window_id() != current_window_id)
7124 .nth(1)
7125 },
7126 );
7127
7128 if let Some(window) = prev_window {
7129 window
7130 .update(cx, |_, window, _| window.activate_window())
7131 .ok();
7132 }
7133 }
7134
7135 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7136 if cx.stop_active_drag(window) {
7137 } else if let Some((notification_id, _)) = self.notifications.pop() {
7138 dismiss_app_notification(¬ification_id, cx);
7139 } else {
7140 cx.propagate();
7141 }
7142 }
7143
7144 fn adjust_dock_size_by_px(
7145 &mut self,
7146 panel_size: Pixels,
7147 dock_pos: DockPosition,
7148 px: Pixels,
7149 window: &mut Window,
7150 cx: &mut Context<Self>,
7151 ) {
7152 match dock_pos {
7153 DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
7154 DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
7155 DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
7156 }
7157 }
7158
7159 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7160 let workspace_width = self.bounds.size.width;
7161 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7162
7163 self.right_dock.read_with(cx, |right_dock, cx| {
7164 let right_dock_size = right_dock
7165 .active_panel_size(window, cx)
7166 .unwrap_or(Pixels::ZERO);
7167 if right_dock_size + size > workspace_width {
7168 size = workspace_width - right_dock_size
7169 }
7170 });
7171
7172 self.left_dock.update(cx, |left_dock, cx| {
7173 if WorkspaceSettings::get_global(cx)
7174 .resize_all_panels_in_dock
7175 .contains(&DockPosition::Left)
7176 {
7177 left_dock.resize_all_panels(Some(size), window, cx);
7178 } else {
7179 left_dock.resize_active_panel(Some(size), window, cx);
7180 }
7181 });
7182 }
7183
7184 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7185 let workspace_width = self.bounds.size.width;
7186 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7187 self.left_dock.read_with(cx, |left_dock, cx| {
7188 let left_dock_size = left_dock
7189 .active_panel_size(window, cx)
7190 .unwrap_or(Pixels::ZERO);
7191 if left_dock_size + size > workspace_width {
7192 size = workspace_width - left_dock_size
7193 }
7194 });
7195 self.right_dock.update(cx, |right_dock, cx| {
7196 if WorkspaceSettings::get_global(cx)
7197 .resize_all_panels_in_dock
7198 .contains(&DockPosition::Right)
7199 {
7200 right_dock.resize_all_panels(Some(size), window, cx);
7201 } else {
7202 right_dock.resize_active_panel(Some(size), window, cx);
7203 }
7204 });
7205 }
7206
7207 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7208 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7209 self.bottom_dock.update(cx, |bottom_dock, cx| {
7210 if WorkspaceSettings::get_global(cx)
7211 .resize_all_panels_in_dock
7212 .contains(&DockPosition::Bottom)
7213 {
7214 bottom_dock.resize_all_panels(Some(size), window, cx);
7215 } else {
7216 bottom_dock.resize_active_panel(Some(size), window, cx);
7217 }
7218 });
7219 }
7220
7221 fn toggle_edit_predictions_all_files(
7222 &mut self,
7223 _: &ToggleEditPrediction,
7224 _window: &mut Window,
7225 cx: &mut Context<Self>,
7226 ) {
7227 let fs = self.project().read(cx).fs().clone();
7228 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7229 update_settings_file(fs, cx, move |file, _| {
7230 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7231 });
7232 }
7233
7234 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7235 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7236 let next_mode = match current_mode {
7237 Some(theme::ThemeAppearanceMode::Light) => theme::ThemeAppearanceMode::Dark,
7238 Some(theme::ThemeAppearanceMode::Dark) => theme::ThemeAppearanceMode::Light,
7239 Some(theme::ThemeAppearanceMode::System) | None => match cx.theme().appearance() {
7240 theme::Appearance::Light => theme::ThemeAppearanceMode::Dark,
7241 theme::Appearance::Dark => theme::ThemeAppearanceMode::Light,
7242 },
7243 };
7244
7245 let fs = self.project().read(cx).fs().clone();
7246 settings::update_settings_file(fs, cx, move |settings, _cx| {
7247 theme::set_mode(settings, next_mode);
7248 });
7249 }
7250
7251 pub fn show_worktree_trust_security_modal(
7252 &mut self,
7253 toggle: bool,
7254 window: &mut Window,
7255 cx: &mut Context<Self>,
7256 ) {
7257 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7258 if toggle {
7259 security_modal.update(cx, |security_modal, cx| {
7260 security_modal.dismiss(cx);
7261 })
7262 } else {
7263 security_modal.update(cx, |security_modal, cx| {
7264 security_modal.refresh_restricted_paths(cx);
7265 });
7266 }
7267 } else {
7268 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7269 .map(|trusted_worktrees| {
7270 trusted_worktrees
7271 .read(cx)
7272 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7273 })
7274 .unwrap_or(false);
7275 if has_restricted_worktrees {
7276 let project = self.project().read(cx);
7277 let remote_host = project
7278 .remote_connection_options(cx)
7279 .map(RemoteHostLocation::from);
7280 let worktree_store = project.worktree_store().downgrade();
7281 self.toggle_modal(window, cx, |_, cx| {
7282 SecurityModal::new(worktree_store, remote_host, cx)
7283 });
7284 }
7285 }
7286 }
7287}
7288
7289pub trait AnyActiveCall {
7290 fn entity(&self) -> AnyEntity;
7291 fn is_in_room(&self, _: &App) -> bool;
7292 fn room_id(&self, _: &App) -> Option<u64>;
7293 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7294 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7295 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7296 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7297 fn is_sharing_project(&self, _: &App) -> bool;
7298 fn has_remote_participants(&self, _: &App) -> bool;
7299 fn local_participant_is_guest(&self, _: &App) -> bool;
7300 fn client(&self, _: &App) -> Arc<Client>;
7301 fn share_on_join(&self, _: &App) -> bool;
7302 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7303 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7304 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7305 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7306 fn join_project(
7307 &self,
7308 _: u64,
7309 _: Arc<LanguageRegistry>,
7310 _: Arc<dyn Fs>,
7311 _: &mut App,
7312 ) -> Task<Result<Entity<Project>>>;
7313 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7314 fn subscribe(
7315 &self,
7316 _: &mut Window,
7317 _: &mut Context<Workspace>,
7318 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7319 ) -> Subscription;
7320 fn create_shared_screen(
7321 &self,
7322 _: PeerId,
7323 _: &Entity<Pane>,
7324 _: &mut Window,
7325 _: &mut App,
7326 ) -> Option<Entity<SharedScreen>>;
7327}
7328
7329#[derive(Clone)]
7330pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7331impl Global for GlobalAnyActiveCall {}
7332
7333impl GlobalAnyActiveCall {
7334 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7335 cx.try_global()
7336 }
7337
7338 pub(crate) fn global(cx: &App) -> &Self {
7339 cx.global()
7340 }
7341}
7342
7343pub fn merge_conflict_notification_id() -> NotificationId {
7344 struct MergeConflictNotification;
7345 NotificationId::unique::<MergeConflictNotification>()
7346}
7347
7348/// Workspace-local view of a remote participant's location.
7349#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7350pub enum ParticipantLocation {
7351 SharedProject { project_id: u64 },
7352 UnsharedProject,
7353 External,
7354}
7355
7356impl ParticipantLocation {
7357 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7358 match location
7359 .and_then(|l| l.variant)
7360 .context("participant location was not provided")?
7361 {
7362 proto::participant_location::Variant::SharedProject(project) => {
7363 Ok(Self::SharedProject {
7364 project_id: project.id,
7365 })
7366 }
7367 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7368 proto::participant_location::Variant::External(_) => Ok(Self::External),
7369 }
7370 }
7371}
7372/// Workspace-local view of a remote collaborator's state.
7373/// This is the subset of `call::RemoteParticipant` that workspace needs.
7374#[derive(Clone)]
7375pub struct RemoteCollaborator {
7376 pub user: Arc<User>,
7377 pub peer_id: PeerId,
7378 pub location: ParticipantLocation,
7379 pub participant_index: ParticipantIndex,
7380}
7381
7382pub enum ActiveCallEvent {
7383 ParticipantLocationChanged { participant_id: PeerId },
7384 RemoteVideoTracksChanged { participant_id: PeerId },
7385}
7386
7387fn leader_border_for_pane(
7388 follower_states: &HashMap<CollaboratorId, FollowerState>,
7389 pane: &Entity<Pane>,
7390 _: &Window,
7391 cx: &App,
7392) -> Option<Div> {
7393 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7394 if state.pane() == pane {
7395 Some((*leader_id, state))
7396 } else {
7397 None
7398 }
7399 })?;
7400
7401 let mut leader_color = match leader_id {
7402 CollaboratorId::PeerId(leader_peer_id) => {
7403 let leader = GlobalAnyActiveCall::try_global(cx)?
7404 .0
7405 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7406
7407 cx.theme()
7408 .players()
7409 .color_for_participant(leader.participant_index.0)
7410 .cursor
7411 }
7412 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7413 };
7414 leader_color.fade_out(0.3);
7415 Some(
7416 div()
7417 .absolute()
7418 .size_full()
7419 .left_0()
7420 .top_0()
7421 .border_2()
7422 .border_color(leader_color),
7423 )
7424}
7425
7426fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7427 ZED_WINDOW_POSITION
7428 .zip(*ZED_WINDOW_SIZE)
7429 .map(|(position, size)| Bounds {
7430 origin: position,
7431 size,
7432 })
7433}
7434
7435fn open_items(
7436 serialized_workspace: Option<SerializedWorkspace>,
7437 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7438 window: &mut Window,
7439 cx: &mut Context<Workspace>,
7440) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7441 let restored_items = serialized_workspace.map(|serialized_workspace| {
7442 Workspace::load_workspace(
7443 serialized_workspace,
7444 project_paths_to_open
7445 .iter()
7446 .map(|(_, project_path)| project_path)
7447 .cloned()
7448 .collect(),
7449 window,
7450 cx,
7451 )
7452 });
7453
7454 cx.spawn_in(window, async move |workspace, cx| {
7455 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7456
7457 if let Some(restored_items) = restored_items {
7458 let restored_items = restored_items.await?;
7459
7460 let restored_project_paths = restored_items
7461 .iter()
7462 .filter_map(|item| {
7463 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7464 .ok()
7465 .flatten()
7466 })
7467 .collect::<HashSet<_>>();
7468
7469 for restored_item in restored_items {
7470 opened_items.push(restored_item.map(Ok));
7471 }
7472
7473 project_paths_to_open
7474 .iter_mut()
7475 .for_each(|(_, project_path)| {
7476 if let Some(project_path_to_open) = project_path
7477 && restored_project_paths.contains(project_path_to_open)
7478 {
7479 *project_path = None;
7480 }
7481 });
7482 } else {
7483 for _ in 0..project_paths_to_open.len() {
7484 opened_items.push(None);
7485 }
7486 }
7487 assert!(opened_items.len() == project_paths_to_open.len());
7488
7489 let tasks =
7490 project_paths_to_open
7491 .into_iter()
7492 .enumerate()
7493 .map(|(ix, (abs_path, project_path))| {
7494 let workspace = workspace.clone();
7495 cx.spawn(async move |cx| {
7496 let file_project_path = project_path?;
7497 let abs_path_task = workspace.update(cx, |workspace, cx| {
7498 workspace.project().update(cx, |project, cx| {
7499 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7500 })
7501 });
7502
7503 // We only want to open file paths here. If one of the items
7504 // here is a directory, it was already opened further above
7505 // with a `find_or_create_worktree`.
7506 if let Ok(task) = abs_path_task
7507 && task.await.is_none_or(|p| p.is_file())
7508 {
7509 return Some((
7510 ix,
7511 workspace
7512 .update_in(cx, |workspace, window, cx| {
7513 workspace.open_path(
7514 file_project_path,
7515 None,
7516 true,
7517 window,
7518 cx,
7519 )
7520 })
7521 .log_err()?
7522 .await,
7523 ));
7524 }
7525 None
7526 })
7527 });
7528
7529 let tasks = tasks.collect::<Vec<_>>();
7530
7531 let tasks = futures::future::join_all(tasks);
7532 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7533 opened_items[ix] = Some(path_open_result);
7534 }
7535
7536 Ok(opened_items)
7537 })
7538}
7539
7540#[derive(Clone)]
7541enum ActivateInDirectionTarget {
7542 Pane(Entity<Pane>),
7543 Dock(Entity<Dock>),
7544 Sidebar(FocusHandle),
7545}
7546
7547fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7548 window
7549 .update(cx, |multi_workspace, _, cx| {
7550 let workspace = multi_workspace.workspace().clone();
7551 workspace.update(cx, |workspace, cx| {
7552 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7553 struct DatabaseFailedNotification;
7554
7555 workspace.show_notification(
7556 NotificationId::unique::<DatabaseFailedNotification>(),
7557 cx,
7558 |cx| {
7559 cx.new(|cx| {
7560 MessageNotification::new("Failed to load the database file.", cx)
7561 .primary_message("File an Issue")
7562 .primary_icon(IconName::Plus)
7563 .primary_on_click(|window, cx| {
7564 window.dispatch_action(Box::new(FileBugReport), cx)
7565 })
7566 })
7567 },
7568 );
7569 }
7570 });
7571 })
7572 .log_err();
7573}
7574
7575fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7576 if val == 0 {
7577 ThemeSettings::get_global(cx).ui_font_size(cx)
7578 } else {
7579 px(val as f32)
7580 }
7581}
7582
7583fn adjust_active_dock_size_by_px(
7584 px: Pixels,
7585 workspace: &mut Workspace,
7586 window: &mut Window,
7587 cx: &mut Context<Workspace>,
7588) {
7589 let Some(active_dock) = workspace
7590 .all_docks()
7591 .into_iter()
7592 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7593 else {
7594 return;
7595 };
7596 let dock = active_dock.read(cx);
7597 let Some(panel_size) = dock.active_panel_size(window, cx) else {
7598 return;
7599 };
7600 let dock_pos = dock.position();
7601 workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
7602}
7603
7604fn adjust_open_docks_size_by_px(
7605 px: Pixels,
7606 workspace: &mut Workspace,
7607 window: &mut Window,
7608 cx: &mut Context<Workspace>,
7609) {
7610 let docks = workspace
7611 .all_docks()
7612 .into_iter()
7613 .filter_map(|dock| {
7614 if dock.read(cx).is_open() {
7615 let dock = dock.read(cx);
7616 let panel_size = dock.active_panel_size(window, cx)?;
7617 let dock_pos = dock.position();
7618 Some((panel_size, dock_pos, px))
7619 } else {
7620 None
7621 }
7622 })
7623 .collect::<Vec<_>>();
7624
7625 docks
7626 .into_iter()
7627 .for_each(|(panel_size, dock_pos, offset)| {
7628 workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
7629 });
7630}
7631
7632impl Focusable for Workspace {
7633 fn focus_handle(&self, cx: &App) -> FocusHandle {
7634 self.active_pane.focus_handle(cx)
7635 }
7636}
7637
7638#[derive(Clone)]
7639struct DraggedDock(DockPosition);
7640
7641impl Render for DraggedDock {
7642 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7643 gpui::Empty
7644 }
7645}
7646
7647impl Render for Workspace {
7648 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7649 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7650 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7651 log::info!("Rendered first frame");
7652 }
7653
7654 let centered_layout = self.centered_layout
7655 && self.center.panes().len() == 1
7656 && self.active_item(cx).is_some();
7657 let render_padding = |size| {
7658 (size > 0.0).then(|| {
7659 div()
7660 .h_full()
7661 .w(relative(size))
7662 .bg(cx.theme().colors().editor_background)
7663 .border_color(cx.theme().colors().pane_group_border)
7664 })
7665 };
7666 let paddings = if centered_layout {
7667 let settings = WorkspaceSettings::get_global(cx).centered_layout;
7668 (
7669 render_padding(Self::adjust_padding(
7670 settings.left_padding.map(|padding| padding.0),
7671 )),
7672 render_padding(Self::adjust_padding(
7673 settings.right_padding.map(|padding| padding.0),
7674 )),
7675 )
7676 } else {
7677 (None, None)
7678 };
7679 let ui_font = theme::setup_ui_font(window, cx);
7680
7681 let theme = cx.theme().clone();
7682 let colors = theme.colors();
7683 let notification_entities = self
7684 .notifications
7685 .iter()
7686 .map(|(_, notification)| notification.entity_id())
7687 .collect::<Vec<_>>();
7688 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
7689
7690 div()
7691 .relative()
7692 .size_full()
7693 .flex()
7694 .flex_col()
7695 .font(ui_font)
7696 .gap_0()
7697 .justify_start()
7698 .items_start()
7699 .text_color(colors.text)
7700 .overflow_hidden()
7701 .children(self.titlebar_item.clone())
7702 .on_modifiers_changed(move |_, _, cx| {
7703 for &id in ¬ification_entities {
7704 cx.notify(id);
7705 }
7706 })
7707 .child(
7708 div()
7709 .size_full()
7710 .relative()
7711 .flex_1()
7712 .flex()
7713 .flex_col()
7714 .child(
7715 div()
7716 .id("workspace")
7717 .bg(colors.background)
7718 .relative()
7719 .flex_1()
7720 .w_full()
7721 .flex()
7722 .flex_col()
7723 .overflow_hidden()
7724 .border_t_1()
7725 .border_b_1()
7726 .border_color(colors.border)
7727 .child({
7728 let this = cx.entity();
7729 canvas(
7730 move |bounds, window, cx| {
7731 this.update(cx, |this, cx| {
7732 let bounds_changed = this.bounds != bounds;
7733 this.bounds = bounds;
7734
7735 if bounds_changed {
7736 this.left_dock.update(cx, |dock, cx| {
7737 dock.clamp_panel_size(
7738 bounds.size.width,
7739 window,
7740 cx,
7741 )
7742 });
7743
7744 this.right_dock.update(cx, |dock, cx| {
7745 dock.clamp_panel_size(
7746 bounds.size.width,
7747 window,
7748 cx,
7749 )
7750 });
7751
7752 this.bottom_dock.update(cx, |dock, cx| {
7753 dock.clamp_panel_size(
7754 bounds.size.height,
7755 window,
7756 cx,
7757 )
7758 });
7759 }
7760 })
7761 },
7762 |_, _, _, _| {},
7763 )
7764 .absolute()
7765 .size_full()
7766 })
7767 .when(self.zoomed.is_none(), |this| {
7768 this.on_drag_move(cx.listener(
7769 move |workspace,
7770 e: &DragMoveEvent<DraggedDock>,
7771 window,
7772 cx| {
7773 if workspace.previous_dock_drag_coordinates
7774 != Some(e.event.position)
7775 {
7776 workspace.previous_dock_drag_coordinates =
7777 Some(e.event.position);
7778
7779 match e.drag(cx).0 {
7780 DockPosition::Left => {
7781 workspace.resize_left_dock(
7782 e.event.position.x
7783 - workspace.bounds.left(),
7784 window,
7785 cx,
7786 );
7787 }
7788 DockPosition::Right => {
7789 workspace.resize_right_dock(
7790 workspace.bounds.right()
7791 - e.event.position.x,
7792 window,
7793 cx,
7794 );
7795 }
7796 DockPosition::Bottom => {
7797 workspace.resize_bottom_dock(
7798 workspace.bounds.bottom()
7799 - e.event.position.y,
7800 window,
7801 cx,
7802 );
7803 }
7804 };
7805 workspace.serialize_workspace(window, cx);
7806 }
7807 },
7808 ))
7809
7810 })
7811 .child({
7812 match bottom_dock_layout {
7813 BottomDockLayout::Full => div()
7814 .flex()
7815 .flex_col()
7816 .h_full()
7817 .child(
7818 div()
7819 .flex()
7820 .flex_row()
7821 .flex_1()
7822 .overflow_hidden()
7823 .children(self.render_dock(
7824 DockPosition::Left,
7825 &self.left_dock,
7826 window,
7827 cx,
7828 ))
7829
7830 .child(
7831 div()
7832 .flex()
7833 .flex_col()
7834 .flex_1()
7835 .overflow_hidden()
7836 .child(
7837 h_flex()
7838 .flex_1()
7839 .when_some(
7840 paddings.0,
7841 |this, p| {
7842 this.child(
7843 p.border_r_1(),
7844 )
7845 },
7846 )
7847 .child(self.center.render(
7848 self.zoomed.as_ref(),
7849 &PaneRenderContext {
7850 follower_states:
7851 &self.follower_states,
7852 active_call: self.active_call(),
7853 active_pane: &self.active_pane,
7854 app_state: &self.app_state,
7855 project: &self.project,
7856 workspace: &self.weak_self,
7857 },
7858 window,
7859 cx,
7860 ))
7861 .when_some(
7862 paddings.1,
7863 |this, p| {
7864 this.child(
7865 p.border_l_1(),
7866 )
7867 },
7868 ),
7869 ),
7870 )
7871
7872 .children(self.render_dock(
7873 DockPosition::Right,
7874 &self.right_dock,
7875 window,
7876 cx,
7877 )),
7878 )
7879 .child(div().w_full().children(self.render_dock(
7880 DockPosition::Bottom,
7881 &self.bottom_dock,
7882 window,
7883 cx
7884 ))),
7885
7886 BottomDockLayout::LeftAligned => div()
7887 .flex()
7888 .flex_row()
7889 .h_full()
7890 .child(
7891 div()
7892 .flex()
7893 .flex_col()
7894 .flex_1()
7895 .h_full()
7896 .child(
7897 div()
7898 .flex()
7899 .flex_row()
7900 .flex_1()
7901 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
7902
7903 .child(
7904 div()
7905 .flex()
7906 .flex_col()
7907 .flex_1()
7908 .overflow_hidden()
7909 .child(
7910 h_flex()
7911 .flex_1()
7912 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7913 .child(self.center.render(
7914 self.zoomed.as_ref(),
7915 &PaneRenderContext {
7916 follower_states:
7917 &self.follower_states,
7918 active_call: self.active_call(),
7919 active_pane: &self.active_pane,
7920 app_state: &self.app_state,
7921 project: &self.project,
7922 workspace: &self.weak_self,
7923 },
7924 window,
7925 cx,
7926 ))
7927 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7928 )
7929 )
7930
7931 )
7932 .child(
7933 div()
7934 .w_full()
7935 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7936 ),
7937 )
7938 .children(self.render_dock(
7939 DockPosition::Right,
7940 &self.right_dock,
7941 window,
7942 cx,
7943 )),
7944 BottomDockLayout::RightAligned => div()
7945 .flex()
7946 .flex_row()
7947 .h_full()
7948 .children(self.render_dock(
7949 DockPosition::Left,
7950 &self.left_dock,
7951 window,
7952 cx,
7953 ))
7954
7955 .child(
7956 div()
7957 .flex()
7958 .flex_col()
7959 .flex_1()
7960 .h_full()
7961 .child(
7962 div()
7963 .flex()
7964 .flex_row()
7965 .flex_1()
7966 .child(
7967 div()
7968 .flex()
7969 .flex_col()
7970 .flex_1()
7971 .overflow_hidden()
7972 .child(
7973 h_flex()
7974 .flex_1()
7975 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7976 .child(self.center.render(
7977 self.zoomed.as_ref(),
7978 &PaneRenderContext {
7979 follower_states:
7980 &self.follower_states,
7981 active_call: self.active_call(),
7982 active_pane: &self.active_pane,
7983 app_state: &self.app_state,
7984 project: &self.project,
7985 workspace: &self.weak_self,
7986 },
7987 window,
7988 cx,
7989 ))
7990 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7991 )
7992 )
7993
7994 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
7995 )
7996 .child(
7997 div()
7998 .w_full()
7999 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8000 ),
8001 ),
8002 BottomDockLayout::Contained => div()
8003 .flex()
8004 .flex_row()
8005 .h_full()
8006 .children(self.render_dock(
8007 DockPosition::Left,
8008 &self.left_dock,
8009 window,
8010 cx,
8011 ))
8012
8013 .child(
8014 div()
8015 .flex()
8016 .flex_col()
8017 .flex_1()
8018 .overflow_hidden()
8019 .child(
8020 h_flex()
8021 .flex_1()
8022 .when_some(paddings.0, |this, p| {
8023 this.child(p.border_r_1())
8024 })
8025 .child(self.center.render(
8026 self.zoomed.as_ref(),
8027 &PaneRenderContext {
8028 follower_states:
8029 &self.follower_states,
8030 active_call: self.active_call(),
8031 active_pane: &self.active_pane,
8032 app_state: &self.app_state,
8033 project: &self.project,
8034 workspace: &self.weak_self,
8035 },
8036 window,
8037 cx,
8038 ))
8039 .when_some(paddings.1, |this, p| {
8040 this.child(p.border_l_1())
8041 }),
8042 )
8043 .children(self.render_dock(
8044 DockPosition::Bottom,
8045 &self.bottom_dock,
8046 window,
8047 cx,
8048 )),
8049 )
8050
8051 .children(self.render_dock(
8052 DockPosition::Right,
8053 &self.right_dock,
8054 window,
8055 cx,
8056 )),
8057 }
8058 })
8059 .children(self.zoomed.as_ref().and_then(|view| {
8060 let zoomed_view = view.upgrade()?;
8061 let div = div()
8062 .occlude()
8063 .absolute()
8064 .overflow_hidden()
8065 .border_color(colors.border)
8066 .bg(colors.background)
8067 .child(zoomed_view)
8068 .inset_0()
8069 .shadow_lg();
8070
8071 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8072 return Some(div);
8073 }
8074
8075 Some(match self.zoomed_position {
8076 Some(DockPosition::Left) => div.right_2().border_r_1(),
8077 Some(DockPosition::Right) => div.left_2().border_l_1(),
8078 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8079 None => {
8080 div.top_2().bottom_2().left_2().right_2().border_1()
8081 }
8082 })
8083 }))
8084 .children(self.render_notifications(window, cx)),
8085 )
8086 .when(self.status_bar_visible(cx), |parent| {
8087 parent.child(self.status_bar.clone())
8088 })
8089 .child(self.toast_layer.clone()),
8090 )
8091 }
8092}
8093
8094impl WorkspaceStore {
8095 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8096 Self {
8097 workspaces: Default::default(),
8098 _subscriptions: vec![
8099 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8100 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8101 ],
8102 client,
8103 }
8104 }
8105
8106 pub fn update_followers(
8107 &self,
8108 project_id: Option<u64>,
8109 update: proto::update_followers::Variant,
8110 cx: &App,
8111 ) -> Option<()> {
8112 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8113 let room_id = active_call.0.room_id(cx)?;
8114 self.client
8115 .send(proto::UpdateFollowers {
8116 room_id,
8117 project_id,
8118 variant: Some(update),
8119 })
8120 .log_err()
8121 }
8122
8123 pub async fn handle_follow(
8124 this: Entity<Self>,
8125 envelope: TypedEnvelope<proto::Follow>,
8126 mut cx: AsyncApp,
8127 ) -> Result<proto::FollowResponse> {
8128 this.update(&mut cx, |this, cx| {
8129 let follower = Follower {
8130 project_id: envelope.payload.project_id,
8131 peer_id: envelope.original_sender_id()?,
8132 };
8133
8134 let mut response = proto::FollowResponse::default();
8135
8136 this.workspaces.retain(|(window_handle, weak_workspace)| {
8137 let Some(workspace) = weak_workspace.upgrade() else {
8138 return false;
8139 };
8140 window_handle
8141 .update(cx, |_, window, cx| {
8142 workspace.update(cx, |workspace, cx| {
8143 let handler_response =
8144 workspace.handle_follow(follower.project_id, window, cx);
8145 if let Some(active_view) = handler_response.active_view
8146 && workspace.project.read(cx).remote_id() == follower.project_id
8147 {
8148 response.active_view = Some(active_view)
8149 }
8150 });
8151 })
8152 .is_ok()
8153 });
8154
8155 Ok(response)
8156 })
8157 }
8158
8159 async fn handle_update_followers(
8160 this: Entity<Self>,
8161 envelope: TypedEnvelope<proto::UpdateFollowers>,
8162 mut cx: AsyncApp,
8163 ) -> Result<()> {
8164 let leader_id = envelope.original_sender_id()?;
8165 let update = envelope.payload;
8166
8167 this.update(&mut cx, |this, cx| {
8168 this.workspaces.retain(|(window_handle, weak_workspace)| {
8169 let Some(workspace) = weak_workspace.upgrade() else {
8170 return false;
8171 };
8172 window_handle
8173 .update(cx, |_, window, cx| {
8174 workspace.update(cx, |workspace, cx| {
8175 let project_id = workspace.project.read(cx).remote_id();
8176 if update.project_id != project_id && update.project_id.is_some() {
8177 return;
8178 }
8179 workspace.handle_update_followers(
8180 leader_id,
8181 update.clone(),
8182 window,
8183 cx,
8184 );
8185 });
8186 })
8187 .is_ok()
8188 });
8189 Ok(())
8190 })
8191 }
8192
8193 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8194 self.workspaces.iter().map(|(_, weak)| weak)
8195 }
8196
8197 pub fn workspaces_with_windows(
8198 &self,
8199 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8200 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8201 }
8202}
8203
8204impl ViewId {
8205 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8206 Ok(Self {
8207 creator: message
8208 .creator
8209 .map(CollaboratorId::PeerId)
8210 .context("creator is missing")?,
8211 id: message.id,
8212 })
8213 }
8214
8215 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8216 if let CollaboratorId::PeerId(peer_id) = self.creator {
8217 Some(proto::ViewId {
8218 creator: Some(peer_id),
8219 id: self.id,
8220 })
8221 } else {
8222 None
8223 }
8224 }
8225}
8226
8227impl FollowerState {
8228 fn pane(&self) -> &Entity<Pane> {
8229 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8230 }
8231}
8232
8233pub trait WorkspaceHandle {
8234 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8235}
8236
8237impl WorkspaceHandle for Entity<Workspace> {
8238 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8239 self.read(cx)
8240 .worktrees(cx)
8241 .flat_map(|worktree| {
8242 let worktree_id = worktree.read(cx).id();
8243 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8244 worktree_id,
8245 path: f.path.clone(),
8246 })
8247 })
8248 .collect::<Vec<_>>()
8249 }
8250}
8251
8252pub async fn last_opened_workspace_location(
8253 db: &WorkspaceDb,
8254 fs: &dyn fs::Fs,
8255) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8256 db.last_workspace(fs)
8257 .await
8258 .log_err()
8259 .flatten()
8260 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8261}
8262
8263pub async fn last_session_workspace_locations(
8264 db: &WorkspaceDb,
8265 last_session_id: &str,
8266 last_session_window_stack: Option<Vec<WindowId>>,
8267 fs: &dyn fs::Fs,
8268) -> Option<Vec<SessionWorkspace>> {
8269 db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8270 .await
8271 .log_err()
8272}
8273
8274pub struct MultiWorkspaceRestoreResult {
8275 pub window_handle: WindowHandle<MultiWorkspace>,
8276 pub errors: Vec<anyhow::Error>,
8277}
8278
8279pub async fn restore_multiworkspace(
8280 multi_workspace: SerializedMultiWorkspace,
8281 app_state: Arc<AppState>,
8282 cx: &mut AsyncApp,
8283) -> anyhow::Result<MultiWorkspaceRestoreResult> {
8284 let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
8285 let mut group_iter = workspaces.into_iter();
8286 let first = group_iter
8287 .next()
8288 .context("window group must not be empty")?;
8289
8290 let window_handle = if first.paths.is_empty() {
8291 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
8292 .await?
8293 } else {
8294 let OpenResult { window, .. } = cx
8295 .update(|cx| {
8296 Workspace::new_local(
8297 first.paths.paths().to_vec(),
8298 app_state.clone(),
8299 None,
8300 None,
8301 None,
8302 true,
8303 cx,
8304 )
8305 })
8306 .await?;
8307 window
8308 };
8309
8310 let mut errors = Vec::new();
8311
8312 for session_workspace in group_iter {
8313 let error = if session_workspace.paths.is_empty() {
8314 cx.update(|cx| {
8315 open_workspace_by_id(
8316 session_workspace.workspace_id,
8317 app_state.clone(),
8318 Some(window_handle),
8319 cx,
8320 )
8321 })
8322 .await
8323 .err()
8324 } else {
8325 cx.update(|cx| {
8326 Workspace::new_local(
8327 session_workspace.paths.paths().to_vec(),
8328 app_state.clone(),
8329 Some(window_handle),
8330 None,
8331 None,
8332 false,
8333 cx,
8334 )
8335 })
8336 .await
8337 .err()
8338 };
8339
8340 if let Some(error) = error {
8341 errors.push(error);
8342 }
8343 }
8344
8345 if let Some(target_id) = state.active_workspace_id {
8346 window_handle
8347 .update(cx, |multi_workspace, window, cx| {
8348 let target_index = multi_workspace
8349 .workspaces()
8350 .iter()
8351 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8352 if let Some(index) = target_index {
8353 multi_workspace.activate_index(index, window, cx);
8354 } else if !multi_workspace.workspaces().is_empty() {
8355 multi_workspace.activate_index(0, window, cx);
8356 }
8357 })
8358 .ok();
8359 } else {
8360 window_handle
8361 .update(cx, |multi_workspace, window, cx| {
8362 if !multi_workspace.workspaces().is_empty() {
8363 multi_workspace.activate_index(0, window, cx);
8364 }
8365 })
8366 .ok();
8367 }
8368
8369 if state.sidebar_open {
8370 window_handle
8371 .update(cx, |multi_workspace, _, cx| {
8372 multi_workspace.open_sidebar(cx);
8373 })
8374 .ok();
8375 }
8376
8377 window_handle
8378 .update(cx, |_, window, _cx| {
8379 window.activate_window();
8380 })
8381 .ok();
8382
8383 Ok(MultiWorkspaceRestoreResult {
8384 window_handle,
8385 errors,
8386 })
8387}
8388
8389actions!(
8390 collab,
8391 [
8392 /// Opens the channel notes for the current call.
8393 ///
8394 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8395 /// channel in the collab panel.
8396 ///
8397 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8398 /// can be copied via "Copy link to section" in the context menu of the channel notes
8399 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8400 OpenChannelNotes,
8401 /// Mutes your microphone.
8402 Mute,
8403 /// Deafens yourself (mute both microphone and speakers).
8404 Deafen,
8405 /// Leaves the current call.
8406 LeaveCall,
8407 /// Shares the current project with collaborators.
8408 ShareProject,
8409 /// Shares your screen with collaborators.
8410 ScreenShare,
8411 /// Copies the current room name and session id for debugging purposes.
8412 CopyRoomId,
8413 ]
8414);
8415
8416/// Opens the channel notes for a specific channel by its ID.
8417#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8418#[action(namespace = collab)]
8419#[serde(deny_unknown_fields)]
8420pub struct OpenChannelNotesById {
8421 pub channel_id: u64,
8422}
8423
8424actions!(
8425 zed,
8426 [
8427 /// Opens the Zed log file.
8428 OpenLog,
8429 /// Reveals the Zed log file in the system file manager.
8430 RevealLogInFileManager
8431 ]
8432);
8433
8434async fn join_channel_internal(
8435 channel_id: ChannelId,
8436 app_state: &Arc<AppState>,
8437 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8438 requesting_workspace: Option<WeakEntity<Workspace>>,
8439 active_call: &dyn AnyActiveCall,
8440 cx: &mut AsyncApp,
8441) -> Result<bool> {
8442 let (should_prompt, already_in_channel) = cx.update(|cx| {
8443 if !active_call.is_in_room(cx) {
8444 return (false, false);
8445 }
8446
8447 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8448 let should_prompt = active_call.is_sharing_project(cx)
8449 && active_call.has_remote_participants(cx)
8450 && !already_in_channel;
8451 (should_prompt, already_in_channel)
8452 });
8453
8454 if already_in_channel {
8455 let task = cx.update(|cx| {
8456 if let Some((project, host)) = active_call.most_active_project(cx) {
8457 Some(join_in_room_project(project, host, app_state.clone(), cx))
8458 } else {
8459 None
8460 }
8461 });
8462 if let Some(task) = task {
8463 task.await?;
8464 }
8465 return anyhow::Ok(true);
8466 }
8467
8468 if should_prompt {
8469 if let Some(multi_workspace) = requesting_window {
8470 let answer = multi_workspace
8471 .update(cx, |_, window, cx| {
8472 window.prompt(
8473 PromptLevel::Warning,
8474 "Do you want to switch channels?",
8475 Some("Leaving this call will unshare your current project."),
8476 &["Yes, Join Channel", "Cancel"],
8477 cx,
8478 )
8479 })?
8480 .await;
8481
8482 if answer == Ok(1) {
8483 return Ok(false);
8484 }
8485 } else {
8486 return Ok(false);
8487 }
8488 }
8489
8490 let client = cx.update(|cx| active_call.client(cx));
8491
8492 let mut client_status = client.status();
8493
8494 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8495 'outer: loop {
8496 let Some(status) = client_status.recv().await else {
8497 anyhow::bail!("error connecting");
8498 };
8499
8500 match status {
8501 Status::Connecting
8502 | Status::Authenticating
8503 | Status::Authenticated
8504 | Status::Reconnecting
8505 | Status::Reauthenticating
8506 | Status::Reauthenticated => continue,
8507 Status::Connected { .. } => break 'outer,
8508 Status::SignedOut | Status::AuthenticationError => {
8509 return Err(ErrorCode::SignedOut.into());
8510 }
8511 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8512 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8513 return Err(ErrorCode::Disconnected.into());
8514 }
8515 }
8516 }
8517
8518 let joined = cx
8519 .update(|cx| active_call.join_channel(channel_id, cx))
8520 .await?;
8521
8522 if !joined {
8523 return anyhow::Ok(true);
8524 }
8525
8526 cx.update(|cx| active_call.room_update_completed(cx)).await;
8527
8528 let task = cx.update(|cx| {
8529 if let Some((project, host)) = active_call.most_active_project(cx) {
8530 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8531 }
8532
8533 // If you are the first to join a channel, see if you should share your project.
8534 if !active_call.has_remote_participants(cx)
8535 && !active_call.local_participant_is_guest(cx)
8536 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8537 {
8538 let project = workspace.update(cx, |workspace, cx| {
8539 let project = workspace.project.read(cx);
8540
8541 if !active_call.share_on_join(cx) {
8542 return None;
8543 }
8544
8545 if (project.is_local() || project.is_via_remote_server())
8546 && project.visible_worktrees(cx).any(|tree| {
8547 tree.read(cx)
8548 .root_entry()
8549 .is_some_and(|entry| entry.is_dir())
8550 })
8551 {
8552 Some(workspace.project.clone())
8553 } else {
8554 None
8555 }
8556 });
8557 if let Some(project) = project {
8558 let share_task = active_call.share_project(project, cx);
8559 return Some(cx.spawn(async move |_cx| -> Result<()> {
8560 share_task.await?;
8561 Ok(())
8562 }));
8563 }
8564 }
8565
8566 None
8567 });
8568 if let Some(task) = task {
8569 task.await?;
8570 return anyhow::Ok(true);
8571 }
8572 anyhow::Ok(false)
8573}
8574
8575pub fn join_channel(
8576 channel_id: ChannelId,
8577 app_state: Arc<AppState>,
8578 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8579 requesting_workspace: Option<WeakEntity<Workspace>>,
8580 cx: &mut App,
8581) -> Task<Result<()>> {
8582 let active_call = GlobalAnyActiveCall::global(cx).clone();
8583 cx.spawn(async move |cx| {
8584 let result = join_channel_internal(
8585 channel_id,
8586 &app_state,
8587 requesting_window,
8588 requesting_workspace,
8589 &*active_call.0,
8590 cx,
8591 )
8592 .await;
8593
8594 // join channel succeeded, and opened a window
8595 if matches!(result, Ok(true)) {
8596 return anyhow::Ok(());
8597 }
8598
8599 // find an existing workspace to focus and show call controls
8600 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8601 if active_window.is_none() {
8602 // no open workspaces, make one to show the error in (blergh)
8603 let OpenResult {
8604 window: window_handle,
8605 ..
8606 } = cx
8607 .update(|cx| {
8608 Workspace::new_local(
8609 vec![],
8610 app_state.clone(),
8611 requesting_window,
8612 None,
8613 None,
8614 true,
8615 cx,
8616 )
8617 })
8618 .await?;
8619
8620 window_handle
8621 .update(cx, |_, window, _cx| {
8622 window.activate_window();
8623 })
8624 .ok();
8625
8626 if result.is_ok() {
8627 cx.update(|cx| {
8628 cx.dispatch_action(&OpenChannelNotes);
8629 });
8630 }
8631
8632 active_window = Some(window_handle);
8633 }
8634
8635 if let Err(err) = result {
8636 log::error!("failed to join channel: {}", err);
8637 if let Some(active_window) = active_window {
8638 active_window
8639 .update(cx, |_, window, cx| {
8640 let detail: SharedString = match err.error_code() {
8641 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8642 ErrorCode::UpgradeRequired => concat!(
8643 "Your are running an unsupported version of Zed. ",
8644 "Please update to continue."
8645 )
8646 .into(),
8647 ErrorCode::NoSuchChannel => concat!(
8648 "No matching channel was found. ",
8649 "Please check the link and try again."
8650 )
8651 .into(),
8652 ErrorCode::Forbidden => concat!(
8653 "This channel is private, and you do not have access. ",
8654 "Please ask someone to add you and try again."
8655 )
8656 .into(),
8657 ErrorCode::Disconnected => {
8658 "Please check your internet connection and try again.".into()
8659 }
8660 _ => format!("{}\n\nPlease try again.", err).into(),
8661 };
8662 window.prompt(
8663 PromptLevel::Critical,
8664 "Failed to join channel",
8665 Some(&detail),
8666 &["Ok"],
8667 cx,
8668 )
8669 })?
8670 .await
8671 .ok();
8672 }
8673 }
8674
8675 // return ok, we showed the error to the user.
8676 anyhow::Ok(())
8677 })
8678}
8679
8680pub async fn get_any_active_multi_workspace(
8681 app_state: Arc<AppState>,
8682 mut cx: AsyncApp,
8683) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8684 // find an existing workspace to focus and show call controls
8685 let active_window = activate_any_workspace_window(&mut cx);
8686 if active_window.is_none() {
8687 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
8688 .await?;
8689 }
8690 activate_any_workspace_window(&mut cx).context("could not open zed")
8691}
8692
8693fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
8694 cx.update(|cx| {
8695 if let Some(workspace_window) = cx
8696 .active_window()
8697 .and_then(|window| window.downcast::<MultiWorkspace>())
8698 {
8699 return Some(workspace_window);
8700 }
8701
8702 for window in cx.windows() {
8703 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
8704 workspace_window
8705 .update(cx, |_, window, _| window.activate_window())
8706 .ok();
8707 return Some(workspace_window);
8708 }
8709 }
8710 None
8711 })
8712}
8713
8714pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
8715 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
8716}
8717
8718pub fn workspace_windows_for_location(
8719 serialized_location: &SerializedWorkspaceLocation,
8720 cx: &App,
8721) -> Vec<WindowHandle<MultiWorkspace>> {
8722 cx.windows()
8723 .into_iter()
8724 .filter_map(|window| window.downcast::<MultiWorkspace>())
8725 .filter(|multi_workspace| {
8726 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
8727 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
8728 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
8729 }
8730 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
8731 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
8732 a.distro_name == b.distro_name
8733 }
8734 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
8735 a.container_id == b.container_id
8736 }
8737 #[cfg(any(test, feature = "test-support"))]
8738 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
8739 a.id == b.id
8740 }
8741 _ => false,
8742 };
8743
8744 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
8745 multi_workspace.workspaces().iter().any(|workspace| {
8746 match workspace.read(cx).workspace_location(cx) {
8747 WorkspaceLocation::Location(location, _) => {
8748 match (&location, serialized_location) {
8749 (
8750 SerializedWorkspaceLocation::Local,
8751 SerializedWorkspaceLocation::Local,
8752 ) => true,
8753 (
8754 SerializedWorkspaceLocation::Remote(a),
8755 SerializedWorkspaceLocation::Remote(b),
8756 ) => same_host(a, b),
8757 _ => false,
8758 }
8759 }
8760 _ => false,
8761 }
8762 })
8763 })
8764 })
8765 .collect()
8766}
8767
8768pub async fn find_existing_workspace(
8769 abs_paths: &[PathBuf],
8770 open_options: &OpenOptions,
8771 location: &SerializedWorkspaceLocation,
8772 cx: &mut AsyncApp,
8773) -> (
8774 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
8775 OpenVisible,
8776) {
8777 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
8778 let mut open_visible = OpenVisible::All;
8779 let mut best_match = None;
8780
8781 if open_options.open_new_workspace != Some(true) {
8782 cx.update(|cx| {
8783 for window in workspace_windows_for_location(location, cx) {
8784 if let Ok(multi_workspace) = window.read(cx) {
8785 for workspace in multi_workspace.workspaces() {
8786 let project = workspace.read(cx).project.read(cx);
8787 let m = project.visibility_for_paths(
8788 abs_paths,
8789 open_options.open_new_workspace == None,
8790 cx,
8791 );
8792 if m > best_match {
8793 existing = Some((window, workspace.clone()));
8794 best_match = m;
8795 } else if best_match.is_none()
8796 && open_options.open_new_workspace == Some(false)
8797 {
8798 existing = Some((window, workspace.clone()))
8799 }
8800 }
8801 }
8802 }
8803 });
8804
8805 let all_paths_are_files = existing
8806 .as_ref()
8807 .and_then(|(_, target_workspace)| {
8808 cx.update(|cx| {
8809 let workspace = target_workspace.read(cx);
8810 let project = workspace.project.read(cx);
8811 let path_style = workspace.path_style(cx);
8812 Some(!abs_paths.iter().any(|path| {
8813 let path = util::paths::SanitizedPath::new(path);
8814 project.worktrees(cx).any(|worktree| {
8815 let worktree = worktree.read(cx);
8816 let abs_path = worktree.abs_path();
8817 path_style
8818 .strip_prefix(path.as_ref(), abs_path.as_ref())
8819 .and_then(|rel| worktree.entry_for_path(&rel))
8820 .is_some_and(|e| e.is_dir())
8821 })
8822 }))
8823 })
8824 })
8825 .unwrap_or(false);
8826
8827 if open_options.open_new_workspace.is_none()
8828 && existing.is_some()
8829 && open_options.wait
8830 && all_paths_are_files
8831 {
8832 cx.update(|cx| {
8833 let windows = workspace_windows_for_location(location, cx);
8834 let window = cx
8835 .active_window()
8836 .and_then(|window| window.downcast::<MultiWorkspace>())
8837 .filter(|window| windows.contains(window))
8838 .or_else(|| windows.into_iter().next());
8839 if let Some(window) = window {
8840 if let Ok(multi_workspace) = window.read(cx) {
8841 let active_workspace = multi_workspace.workspace().clone();
8842 existing = Some((window, active_workspace));
8843 open_visible = OpenVisible::None;
8844 }
8845 }
8846 });
8847 }
8848 }
8849 (existing, open_visible)
8850}
8851
8852#[derive(Default, Clone)]
8853pub struct OpenOptions {
8854 pub visible: Option<OpenVisible>,
8855 pub focus: Option<bool>,
8856 pub open_new_workspace: Option<bool>,
8857 pub wait: bool,
8858 pub replace_window: Option<WindowHandle<MultiWorkspace>>,
8859 pub env: Option<HashMap<String, String>>,
8860}
8861
8862/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
8863/// or [`Workspace::open_workspace_for_paths`].
8864pub struct OpenResult {
8865 pub window: WindowHandle<MultiWorkspace>,
8866 pub workspace: Entity<Workspace>,
8867 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
8868}
8869
8870/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
8871pub fn open_workspace_by_id(
8872 workspace_id: WorkspaceId,
8873 app_state: Arc<AppState>,
8874 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8875 cx: &mut App,
8876) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
8877 let project_handle = Project::local(
8878 app_state.client.clone(),
8879 app_state.node_runtime.clone(),
8880 app_state.user_store.clone(),
8881 app_state.languages.clone(),
8882 app_state.fs.clone(),
8883 None,
8884 project::LocalProjectFlags {
8885 init_worktree_trust: true,
8886 ..project::LocalProjectFlags::default()
8887 },
8888 cx,
8889 );
8890
8891 let db = WorkspaceDb::global(cx);
8892 let kvp = db::kvp::KeyValueStore::global(cx);
8893 cx.spawn(async move |cx| {
8894 let serialized_workspace = db
8895 .workspace_for_id(workspace_id)
8896 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
8897
8898 let centered_layout = serialized_workspace.centered_layout;
8899
8900 let (window, workspace) = if let Some(window) = requesting_window {
8901 let workspace = window.update(cx, |multi_workspace, window, cx| {
8902 let workspace = cx.new(|cx| {
8903 let mut workspace = Workspace::new(
8904 Some(workspace_id),
8905 project_handle.clone(),
8906 app_state.clone(),
8907 window,
8908 cx,
8909 );
8910 workspace.centered_layout = centered_layout;
8911 workspace
8912 });
8913 multi_workspace.add_workspace(workspace.clone(), cx);
8914 workspace
8915 })?;
8916 (window, workspace)
8917 } else {
8918 let window_bounds_override = window_bounds_env_override();
8919
8920 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
8921 (Some(WindowBounds::Windowed(bounds)), None)
8922 } else if let Some(display) = serialized_workspace.display
8923 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
8924 {
8925 (Some(bounds.0), Some(display))
8926 } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
8927 (Some(bounds), Some(display))
8928 } else {
8929 (None, None)
8930 };
8931
8932 let options = cx.update(|cx| {
8933 let mut options = (app_state.build_window_options)(display, cx);
8934 options.window_bounds = window_bounds;
8935 options
8936 });
8937
8938 let window = cx.open_window(options, {
8939 let app_state = app_state.clone();
8940 let project_handle = project_handle.clone();
8941 move |window, cx| {
8942 let workspace = cx.new(|cx| {
8943 let mut workspace = Workspace::new(
8944 Some(workspace_id),
8945 project_handle,
8946 app_state,
8947 window,
8948 cx,
8949 );
8950 workspace.centered_layout = centered_layout;
8951 workspace
8952 });
8953 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
8954 }
8955 })?;
8956
8957 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
8958 multi_workspace.workspace().clone()
8959 })?;
8960
8961 (window, workspace)
8962 };
8963
8964 notify_if_database_failed(window, cx);
8965
8966 // Restore items from the serialized workspace
8967 window
8968 .update(cx, |_, window, cx| {
8969 workspace.update(cx, |_workspace, cx| {
8970 open_items(Some(serialized_workspace), vec![], window, cx)
8971 })
8972 })?
8973 .await?;
8974
8975 window.update(cx, |_, window, cx| {
8976 workspace.update(cx, |workspace, cx| {
8977 workspace.serialize_workspace(window, cx);
8978 });
8979 })?;
8980
8981 Ok(window)
8982 })
8983}
8984
8985#[allow(clippy::type_complexity)]
8986pub fn open_paths(
8987 abs_paths: &[PathBuf],
8988 app_state: Arc<AppState>,
8989 open_options: OpenOptions,
8990 cx: &mut App,
8991) -> Task<anyhow::Result<OpenResult>> {
8992 let abs_paths = abs_paths.to_vec();
8993 #[cfg(target_os = "windows")]
8994 let wsl_path = abs_paths
8995 .iter()
8996 .find_map(|p| util::paths::WslPath::from_path(p));
8997
8998 cx.spawn(async move |cx| {
8999 let (mut existing, mut open_visible) = find_existing_workspace(
9000 &abs_paths,
9001 &open_options,
9002 &SerializedWorkspaceLocation::Local,
9003 cx,
9004 )
9005 .await;
9006
9007 // Fallback: if no workspace contains the paths and all paths are files,
9008 // prefer an existing local workspace window (active window first).
9009 if open_options.open_new_workspace.is_none() && existing.is_none() {
9010 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9011 let all_metadatas = futures::future::join_all(all_paths)
9012 .await
9013 .into_iter()
9014 .filter_map(|result| result.ok().flatten())
9015 .collect::<Vec<_>>();
9016
9017 if all_metadatas.iter().all(|file| !file.is_dir) {
9018 cx.update(|cx| {
9019 let windows = workspace_windows_for_location(
9020 &SerializedWorkspaceLocation::Local,
9021 cx,
9022 );
9023 let window = cx
9024 .active_window()
9025 .and_then(|window| window.downcast::<MultiWorkspace>())
9026 .filter(|window| windows.contains(window))
9027 .or_else(|| windows.into_iter().next());
9028 if let Some(window) = window {
9029 if let Ok(multi_workspace) = window.read(cx) {
9030 let active_workspace = multi_workspace.workspace().clone();
9031 existing = Some((window, active_workspace));
9032 open_visible = OpenVisible::None;
9033 }
9034 }
9035 });
9036 }
9037 }
9038
9039 let result = if let Some((existing, target_workspace)) = existing {
9040 let open_task = existing
9041 .update(cx, |multi_workspace, window, cx| {
9042 window.activate_window();
9043 multi_workspace.activate(target_workspace.clone(), cx);
9044 target_workspace.update(cx, |workspace, cx| {
9045 workspace.open_paths(
9046 abs_paths,
9047 OpenOptions {
9048 visible: Some(open_visible),
9049 ..Default::default()
9050 },
9051 None,
9052 window,
9053 cx,
9054 )
9055 })
9056 })?
9057 .await;
9058
9059 _ = existing.update(cx, |multi_workspace, _, cx| {
9060 let workspace = multi_workspace.workspace().clone();
9061 workspace.update(cx, |workspace, cx| {
9062 for item in open_task.iter().flatten() {
9063 if let Err(e) = item {
9064 workspace.show_error(&e, cx);
9065 }
9066 }
9067 });
9068 });
9069
9070 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9071 } else {
9072 let result = cx
9073 .update(move |cx| {
9074 Workspace::new_local(
9075 abs_paths,
9076 app_state.clone(),
9077 open_options.replace_window,
9078 open_options.env,
9079 None,
9080 true,
9081 cx,
9082 )
9083 })
9084 .await;
9085
9086 if let Ok(ref result) = result {
9087 result.window
9088 .update(cx, |_, window, _cx| {
9089 window.activate_window();
9090 })
9091 .log_err();
9092 }
9093
9094 result
9095 };
9096
9097 #[cfg(target_os = "windows")]
9098 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9099 && let Ok(ref result) = result
9100 {
9101 result.window
9102 .update(cx, move |multi_workspace, _window, cx| {
9103 struct OpenInWsl;
9104 let workspace = multi_workspace.workspace().clone();
9105 workspace.update(cx, |workspace, cx| {
9106 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9107 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9108 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9109 cx.new(move |cx| {
9110 MessageNotification::new(msg, cx)
9111 .primary_message("Open in WSL")
9112 .primary_icon(IconName::FolderOpen)
9113 .primary_on_click(move |window, cx| {
9114 window.dispatch_action(Box::new(remote::OpenWslPath {
9115 distro: remote::WslConnectionOptions {
9116 distro_name: distro.clone(),
9117 user: None,
9118 },
9119 paths: vec![path.clone().into()],
9120 }), cx)
9121 })
9122 })
9123 });
9124 });
9125 })
9126 .unwrap();
9127 };
9128 result
9129 })
9130}
9131
9132pub fn open_new(
9133 open_options: OpenOptions,
9134 app_state: Arc<AppState>,
9135 cx: &mut App,
9136 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9137) -> Task<anyhow::Result<()>> {
9138 let task = Workspace::new_local(
9139 Vec::new(),
9140 app_state,
9141 open_options.replace_window,
9142 open_options.env,
9143 Some(Box::new(init)),
9144 true,
9145 cx,
9146 );
9147 cx.spawn(async move |cx| {
9148 let OpenResult { window, .. } = task.await?;
9149 window
9150 .update(cx, |_, window, _cx| {
9151 window.activate_window();
9152 })
9153 .ok();
9154 Ok(())
9155 })
9156}
9157
9158pub fn create_and_open_local_file(
9159 path: &'static Path,
9160 window: &mut Window,
9161 cx: &mut Context<Workspace>,
9162 default_content: impl 'static + Send + FnOnce() -> Rope,
9163) -> Task<Result<Box<dyn ItemHandle>>> {
9164 cx.spawn_in(window, async move |workspace, cx| {
9165 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9166 if !fs.is_file(path).await {
9167 fs.create_file(path, Default::default()).await?;
9168 fs.save(path, &default_content(), Default::default())
9169 .await?;
9170 }
9171
9172 workspace
9173 .update_in(cx, |workspace, window, cx| {
9174 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9175 let path = workspace
9176 .project
9177 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9178 cx.spawn_in(window, async move |workspace, cx| {
9179 let path = path.await?;
9180 let mut items = workspace
9181 .update_in(cx, |workspace, window, cx| {
9182 workspace.open_paths(
9183 vec![path.to_path_buf()],
9184 OpenOptions {
9185 visible: Some(OpenVisible::None),
9186 ..Default::default()
9187 },
9188 None,
9189 window,
9190 cx,
9191 )
9192 })?
9193 .await;
9194 let item = items.pop().flatten();
9195 item.with_context(|| format!("path {path:?} is not a file"))?
9196 })
9197 })
9198 })?
9199 .await?
9200 .await
9201 })
9202}
9203
9204pub fn open_remote_project_with_new_connection(
9205 window: WindowHandle<MultiWorkspace>,
9206 remote_connection: Arc<dyn RemoteConnection>,
9207 cancel_rx: oneshot::Receiver<()>,
9208 delegate: Arc<dyn RemoteClientDelegate>,
9209 app_state: Arc<AppState>,
9210 paths: Vec<PathBuf>,
9211 cx: &mut App,
9212) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9213 cx.spawn(async move |cx| {
9214 let (workspace_id, serialized_workspace) =
9215 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9216 .await?;
9217
9218 let session = match cx
9219 .update(|cx| {
9220 remote::RemoteClient::new(
9221 ConnectionIdentifier::Workspace(workspace_id.0),
9222 remote_connection,
9223 cancel_rx,
9224 delegate,
9225 cx,
9226 )
9227 })
9228 .await?
9229 {
9230 Some(result) => result,
9231 None => return Ok(Vec::new()),
9232 };
9233
9234 let project = cx.update(|cx| {
9235 project::Project::remote(
9236 session,
9237 app_state.client.clone(),
9238 app_state.node_runtime.clone(),
9239 app_state.user_store.clone(),
9240 app_state.languages.clone(),
9241 app_state.fs.clone(),
9242 true,
9243 cx,
9244 )
9245 });
9246
9247 open_remote_project_inner(
9248 project,
9249 paths,
9250 workspace_id,
9251 serialized_workspace,
9252 app_state,
9253 window,
9254 cx,
9255 )
9256 .await
9257 })
9258}
9259
9260pub fn open_remote_project_with_existing_connection(
9261 connection_options: RemoteConnectionOptions,
9262 project: Entity<Project>,
9263 paths: Vec<PathBuf>,
9264 app_state: Arc<AppState>,
9265 window: WindowHandle<MultiWorkspace>,
9266 cx: &mut AsyncApp,
9267) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9268 cx.spawn(async move |cx| {
9269 let (workspace_id, serialized_workspace) =
9270 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9271
9272 open_remote_project_inner(
9273 project,
9274 paths,
9275 workspace_id,
9276 serialized_workspace,
9277 app_state,
9278 window,
9279 cx,
9280 )
9281 .await
9282 })
9283}
9284
9285async fn open_remote_project_inner(
9286 project: Entity<Project>,
9287 paths: Vec<PathBuf>,
9288 workspace_id: WorkspaceId,
9289 serialized_workspace: Option<SerializedWorkspace>,
9290 app_state: Arc<AppState>,
9291 window: WindowHandle<MultiWorkspace>,
9292 cx: &mut AsyncApp,
9293) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9294 let db = cx.update(|cx| WorkspaceDb::global(cx));
9295 let toolchains = db.toolchains(workspace_id).await?;
9296 for (toolchain, worktree_path, path) in toolchains {
9297 project
9298 .update(cx, |this, cx| {
9299 let Some(worktree_id) =
9300 this.find_worktree(&worktree_path, cx)
9301 .and_then(|(worktree, rel_path)| {
9302 if rel_path.is_empty() {
9303 Some(worktree.read(cx).id())
9304 } else {
9305 None
9306 }
9307 })
9308 else {
9309 return Task::ready(None);
9310 };
9311
9312 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9313 })
9314 .await;
9315 }
9316 let mut project_paths_to_open = vec![];
9317 let mut project_path_errors = vec![];
9318
9319 for path in paths {
9320 let result = cx
9321 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9322 .await;
9323 match result {
9324 Ok((_, project_path)) => {
9325 project_paths_to_open.push((path.clone(), Some(project_path)));
9326 }
9327 Err(error) => {
9328 project_path_errors.push(error);
9329 }
9330 };
9331 }
9332
9333 if project_paths_to_open.is_empty() {
9334 return Err(project_path_errors.pop().context("no paths given")?);
9335 }
9336
9337 let workspace = window.update(cx, |multi_workspace, window, cx| {
9338 telemetry::event!("SSH Project Opened");
9339
9340 let new_workspace = cx.new(|cx| {
9341 let mut workspace =
9342 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9343 workspace.update_history(cx);
9344
9345 if let Some(ref serialized) = serialized_workspace {
9346 workspace.centered_layout = serialized.centered_layout;
9347 }
9348
9349 workspace
9350 });
9351
9352 multi_workspace.activate(new_workspace.clone(), cx);
9353 new_workspace
9354 })?;
9355
9356 let items = window
9357 .update(cx, |_, window, cx| {
9358 window.activate_window();
9359 workspace.update(cx, |_workspace, cx| {
9360 open_items(serialized_workspace, project_paths_to_open, window, cx)
9361 })
9362 })?
9363 .await?;
9364
9365 workspace.update(cx, |workspace, cx| {
9366 for error in project_path_errors {
9367 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9368 if let Some(path) = error.error_tag("path") {
9369 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9370 }
9371 } else {
9372 workspace.show_error(&error, cx)
9373 }
9374 }
9375 });
9376
9377 Ok(items.into_iter().map(|item| item?.ok()).collect())
9378}
9379
9380fn deserialize_remote_project(
9381 connection_options: RemoteConnectionOptions,
9382 paths: Vec<PathBuf>,
9383 cx: &AsyncApp,
9384) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9385 let db = cx.update(|cx| WorkspaceDb::global(cx));
9386 cx.background_spawn(async move {
9387 let remote_connection_id = db
9388 .get_or_create_remote_connection(connection_options)
9389 .await?;
9390
9391 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9392
9393 let workspace_id = if let Some(workspace_id) =
9394 serialized_workspace.as_ref().map(|workspace| workspace.id)
9395 {
9396 workspace_id
9397 } else {
9398 db.next_id().await?
9399 };
9400
9401 Ok((workspace_id, serialized_workspace))
9402 })
9403}
9404
9405pub fn join_in_room_project(
9406 project_id: u64,
9407 follow_user_id: u64,
9408 app_state: Arc<AppState>,
9409 cx: &mut App,
9410) -> Task<Result<()>> {
9411 let windows = cx.windows();
9412 cx.spawn(async move |cx| {
9413 let existing_window_and_workspace: Option<(
9414 WindowHandle<MultiWorkspace>,
9415 Entity<Workspace>,
9416 )> = windows.into_iter().find_map(|window_handle| {
9417 window_handle
9418 .downcast::<MultiWorkspace>()
9419 .and_then(|window_handle| {
9420 window_handle
9421 .update(cx, |multi_workspace, _window, cx| {
9422 for workspace in multi_workspace.workspaces() {
9423 if workspace.read(cx).project().read(cx).remote_id()
9424 == Some(project_id)
9425 {
9426 return Some((window_handle, workspace.clone()));
9427 }
9428 }
9429 None
9430 })
9431 .unwrap_or(None)
9432 })
9433 });
9434
9435 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9436 existing_window_and_workspace
9437 {
9438 existing_window
9439 .update(cx, |multi_workspace, _, cx| {
9440 multi_workspace.activate(target_workspace, cx);
9441 })
9442 .ok();
9443 existing_window
9444 } else {
9445 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9446 let project = cx
9447 .update(|cx| {
9448 active_call.0.join_project(
9449 project_id,
9450 app_state.languages.clone(),
9451 app_state.fs.clone(),
9452 cx,
9453 )
9454 })
9455 .await?;
9456
9457 let window_bounds_override = window_bounds_env_override();
9458 cx.update(|cx| {
9459 let mut options = (app_state.build_window_options)(None, cx);
9460 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9461 cx.open_window(options, |window, cx| {
9462 let workspace = cx.new(|cx| {
9463 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9464 });
9465 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9466 })
9467 })?
9468 };
9469
9470 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9471 cx.activate(true);
9472 window.activate_window();
9473
9474 // We set the active workspace above, so this is the correct workspace.
9475 let workspace = multi_workspace.workspace().clone();
9476 workspace.update(cx, |workspace, cx| {
9477 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9478 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9479 .or_else(|| {
9480 // If we couldn't follow the given user, follow the host instead.
9481 let collaborator = workspace
9482 .project()
9483 .read(cx)
9484 .collaborators()
9485 .values()
9486 .find(|collaborator| collaborator.is_host)?;
9487 Some(collaborator.peer_id)
9488 });
9489
9490 if let Some(follow_peer_id) = follow_peer_id {
9491 workspace.follow(follow_peer_id, window, cx);
9492 }
9493 });
9494 })?;
9495
9496 anyhow::Ok(())
9497 })
9498}
9499
9500pub fn reload(cx: &mut App) {
9501 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9502 let mut workspace_windows = cx
9503 .windows()
9504 .into_iter()
9505 .filter_map(|window| window.downcast::<MultiWorkspace>())
9506 .collect::<Vec<_>>();
9507
9508 // If multiple windows have unsaved changes, and need a save prompt,
9509 // prompt in the active window before switching to a different window.
9510 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9511
9512 let mut prompt = None;
9513 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9514 prompt = window
9515 .update(cx, |_, window, cx| {
9516 window.prompt(
9517 PromptLevel::Info,
9518 "Are you sure you want to restart?",
9519 None,
9520 &["Restart", "Cancel"],
9521 cx,
9522 )
9523 })
9524 .ok();
9525 }
9526
9527 cx.spawn(async move |cx| {
9528 if let Some(prompt) = prompt {
9529 let answer = prompt.await?;
9530 if answer != 0 {
9531 return anyhow::Ok(());
9532 }
9533 }
9534
9535 // If the user cancels any save prompt, then keep the app open.
9536 for window in workspace_windows {
9537 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9538 let workspace = multi_workspace.workspace().clone();
9539 workspace.update(cx, |workspace, cx| {
9540 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9541 })
9542 }) && !should_close.await?
9543 {
9544 return anyhow::Ok(());
9545 }
9546 }
9547 cx.update(|cx| cx.restart());
9548 anyhow::Ok(())
9549 })
9550 .detach_and_log_err(cx);
9551}
9552
9553fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9554 let mut parts = value.split(',');
9555 let x: usize = parts.next()?.parse().ok()?;
9556 let y: usize = parts.next()?.parse().ok()?;
9557 Some(point(px(x as f32), px(y as f32)))
9558}
9559
9560fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9561 let mut parts = value.split(',');
9562 let width: usize = parts.next()?.parse().ok()?;
9563 let height: usize = parts.next()?.parse().ok()?;
9564 Some(size(px(width as f32), px(height as f32)))
9565}
9566
9567/// Add client-side decorations (rounded corners, shadows, resize handling) when
9568/// appropriate.
9569///
9570/// The `border_radius_tiling` parameter allows overriding which corners get
9571/// rounded, independently of the actual window tiling state. This is used
9572/// specifically for the workspace switcher sidebar: when the sidebar is open,
9573/// we want square corners on the left (so the sidebar appears flush with the
9574/// window edge) but we still need the shadow padding for proper visual
9575/// appearance. Unlike actual window tiling, this only affects border radius -
9576/// not padding or shadows.
9577pub fn client_side_decorations(
9578 element: impl IntoElement,
9579 window: &mut Window,
9580 cx: &mut App,
9581 border_radius_tiling: Tiling,
9582) -> Stateful<Div> {
9583 const BORDER_SIZE: Pixels = px(1.0);
9584 let decorations = window.window_decorations();
9585 let tiling = match decorations {
9586 Decorations::Server => Tiling::default(),
9587 Decorations::Client { tiling } => tiling,
9588 };
9589
9590 match decorations {
9591 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9592 Decorations::Server => window.set_client_inset(px(0.0)),
9593 }
9594
9595 struct GlobalResizeEdge(ResizeEdge);
9596 impl Global for GlobalResizeEdge {}
9597
9598 div()
9599 .id("window-backdrop")
9600 .bg(transparent_black())
9601 .map(|div| match decorations {
9602 Decorations::Server => div,
9603 Decorations::Client { .. } => div
9604 .when(
9605 !(tiling.top
9606 || tiling.right
9607 || border_radius_tiling.top
9608 || border_radius_tiling.right),
9609 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9610 )
9611 .when(
9612 !(tiling.top
9613 || tiling.left
9614 || border_radius_tiling.top
9615 || border_radius_tiling.left),
9616 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9617 )
9618 .when(
9619 !(tiling.bottom
9620 || tiling.right
9621 || border_radius_tiling.bottom
9622 || border_radius_tiling.right),
9623 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9624 )
9625 .when(
9626 !(tiling.bottom
9627 || tiling.left
9628 || border_radius_tiling.bottom
9629 || border_radius_tiling.left),
9630 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9631 )
9632 .when(!tiling.top, |div| {
9633 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9634 })
9635 .when(!tiling.bottom, |div| {
9636 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9637 })
9638 .when(!tiling.left, |div| {
9639 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9640 })
9641 .when(!tiling.right, |div| {
9642 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9643 })
9644 .on_mouse_move(move |e, window, cx| {
9645 let size = window.window_bounds().get_bounds().size;
9646 let pos = e.position;
9647
9648 let new_edge =
9649 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9650
9651 let edge = cx.try_global::<GlobalResizeEdge>();
9652 if new_edge != edge.map(|edge| edge.0) {
9653 window
9654 .window_handle()
9655 .update(cx, |workspace, _, cx| {
9656 cx.notify(workspace.entity_id());
9657 })
9658 .ok();
9659 }
9660 })
9661 .on_mouse_down(MouseButton::Left, move |e, window, _| {
9662 let size = window.window_bounds().get_bounds().size;
9663 let pos = e.position;
9664
9665 let edge = match resize_edge(
9666 pos,
9667 theme::CLIENT_SIDE_DECORATION_SHADOW,
9668 size,
9669 tiling,
9670 ) {
9671 Some(value) => value,
9672 None => return,
9673 };
9674
9675 window.start_window_resize(edge);
9676 }),
9677 })
9678 .size_full()
9679 .child(
9680 div()
9681 .cursor(CursorStyle::Arrow)
9682 .map(|div| match decorations {
9683 Decorations::Server => div,
9684 Decorations::Client { .. } => div
9685 .border_color(cx.theme().colors().border)
9686 .when(
9687 !(tiling.top
9688 || tiling.right
9689 || border_radius_tiling.top
9690 || border_radius_tiling.right),
9691 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9692 )
9693 .when(
9694 !(tiling.top
9695 || tiling.left
9696 || border_radius_tiling.top
9697 || border_radius_tiling.left),
9698 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9699 )
9700 .when(
9701 !(tiling.bottom
9702 || tiling.right
9703 || border_radius_tiling.bottom
9704 || border_radius_tiling.right),
9705 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9706 )
9707 .when(
9708 !(tiling.bottom
9709 || tiling.left
9710 || border_radius_tiling.bottom
9711 || border_radius_tiling.left),
9712 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9713 )
9714 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
9715 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
9716 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
9717 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
9718 .when(!tiling.is_tiled(), |div| {
9719 div.shadow(vec![gpui::BoxShadow {
9720 color: Hsla {
9721 h: 0.,
9722 s: 0.,
9723 l: 0.,
9724 a: 0.4,
9725 },
9726 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
9727 spread_radius: px(0.),
9728 offset: point(px(0.0), px(0.0)),
9729 }])
9730 }),
9731 })
9732 .on_mouse_move(|_e, _, cx| {
9733 cx.stop_propagation();
9734 })
9735 .size_full()
9736 .child(element),
9737 )
9738 .map(|div| match decorations {
9739 Decorations::Server => div,
9740 Decorations::Client { tiling, .. } => div.child(
9741 canvas(
9742 |_bounds, window, _| {
9743 window.insert_hitbox(
9744 Bounds::new(
9745 point(px(0.0), px(0.0)),
9746 window.window_bounds().get_bounds().size,
9747 ),
9748 HitboxBehavior::Normal,
9749 )
9750 },
9751 move |_bounds, hitbox, window, cx| {
9752 let mouse = window.mouse_position();
9753 let size = window.window_bounds().get_bounds().size;
9754 let Some(edge) =
9755 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
9756 else {
9757 return;
9758 };
9759 cx.set_global(GlobalResizeEdge(edge));
9760 window.set_cursor_style(
9761 match edge {
9762 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
9763 ResizeEdge::Left | ResizeEdge::Right => {
9764 CursorStyle::ResizeLeftRight
9765 }
9766 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
9767 CursorStyle::ResizeUpLeftDownRight
9768 }
9769 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
9770 CursorStyle::ResizeUpRightDownLeft
9771 }
9772 },
9773 &hitbox,
9774 );
9775 },
9776 )
9777 .size_full()
9778 .absolute(),
9779 ),
9780 })
9781}
9782
9783fn resize_edge(
9784 pos: Point<Pixels>,
9785 shadow_size: Pixels,
9786 window_size: Size<Pixels>,
9787 tiling: Tiling,
9788) -> Option<ResizeEdge> {
9789 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
9790 if bounds.contains(&pos) {
9791 return None;
9792 }
9793
9794 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
9795 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
9796 if !tiling.top && top_left_bounds.contains(&pos) {
9797 return Some(ResizeEdge::TopLeft);
9798 }
9799
9800 let top_right_bounds = Bounds::new(
9801 Point::new(window_size.width - corner_size.width, px(0.)),
9802 corner_size,
9803 );
9804 if !tiling.top && top_right_bounds.contains(&pos) {
9805 return Some(ResizeEdge::TopRight);
9806 }
9807
9808 let bottom_left_bounds = Bounds::new(
9809 Point::new(px(0.), window_size.height - corner_size.height),
9810 corner_size,
9811 );
9812 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
9813 return Some(ResizeEdge::BottomLeft);
9814 }
9815
9816 let bottom_right_bounds = Bounds::new(
9817 Point::new(
9818 window_size.width - corner_size.width,
9819 window_size.height - corner_size.height,
9820 ),
9821 corner_size,
9822 );
9823 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
9824 return Some(ResizeEdge::BottomRight);
9825 }
9826
9827 if !tiling.top && pos.y < shadow_size {
9828 Some(ResizeEdge::Top)
9829 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
9830 Some(ResizeEdge::Bottom)
9831 } else if !tiling.left && pos.x < shadow_size {
9832 Some(ResizeEdge::Left)
9833 } else if !tiling.right && pos.x > window_size.width - shadow_size {
9834 Some(ResizeEdge::Right)
9835 } else {
9836 None
9837 }
9838}
9839
9840fn join_pane_into_active(
9841 active_pane: &Entity<Pane>,
9842 pane: &Entity<Pane>,
9843 window: &mut Window,
9844 cx: &mut App,
9845) {
9846 if pane == active_pane {
9847 } else if pane.read(cx).items_len() == 0 {
9848 pane.update(cx, |_, cx| {
9849 cx.emit(pane::Event::Remove {
9850 focus_on_pane: None,
9851 });
9852 })
9853 } else {
9854 move_all_items(pane, active_pane, window, cx);
9855 }
9856}
9857
9858fn move_all_items(
9859 from_pane: &Entity<Pane>,
9860 to_pane: &Entity<Pane>,
9861 window: &mut Window,
9862 cx: &mut App,
9863) {
9864 let destination_is_different = from_pane != to_pane;
9865 let mut moved_items = 0;
9866 for (item_ix, item_handle) in from_pane
9867 .read(cx)
9868 .items()
9869 .enumerate()
9870 .map(|(ix, item)| (ix, item.clone()))
9871 .collect::<Vec<_>>()
9872 {
9873 let ix = item_ix - moved_items;
9874 if destination_is_different {
9875 // Close item from previous pane
9876 from_pane.update(cx, |source, cx| {
9877 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
9878 });
9879 moved_items += 1;
9880 }
9881
9882 // This automatically removes duplicate items in the pane
9883 to_pane.update(cx, |destination, cx| {
9884 destination.add_item(item_handle, true, true, None, window, cx);
9885 window.focus(&destination.focus_handle(cx), cx)
9886 });
9887 }
9888}
9889
9890pub fn move_item(
9891 source: &Entity<Pane>,
9892 destination: &Entity<Pane>,
9893 item_id_to_move: EntityId,
9894 destination_index: usize,
9895 activate: bool,
9896 window: &mut Window,
9897 cx: &mut App,
9898) {
9899 let Some((item_ix, item_handle)) = source
9900 .read(cx)
9901 .items()
9902 .enumerate()
9903 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
9904 .map(|(ix, item)| (ix, item.clone()))
9905 else {
9906 // Tab was closed during drag
9907 return;
9908 };
9909
9910 if source != destination {
9911 // Close item from previous pane
9912 source.update(cx, |source, cx| {
9913 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
9914 });
9915 }
9916
9917 // This automatically removes duplicate items in the pane
9918 destination.update(cx, |destination, cx| {
9919 destination.add_item_inner(
9920 item_handle,
9921 activate,
9922 activate,
9923 activate,
9924 Some(destination_index),
9925 window,
9926 cx,
9927 );
9928 if activate {
9929 window.focus(&destination.focus_handle(cx), cx)
9930 }
9931 });
9932}
9933
9934pub fn move_active_item(
9935 source: &Entity<Pane>,
9936 destination: &Entity<Pane>,
9937 focus_destination: bool,
9938 close_if_empty: bool,
9939 window: &mut Window,
9940 cx: &mut App,
9941) {
9942 if source == destination {
9943 return;
9944 }
9945 let Some(active_item) = source.read(cx).active_item() else {
9946 return;
9947 };
9948 source.update(cx, |source_pane, cx| {
9949 let item_id = active_item.item_id();
9950 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
9951 destination.update(cx, |target_pane, cx| {
9952 target_pane.add_item(
9953 active_item,
9954 focus_destination,
9955 focus_destination,
9956 Some(target_pane.items_len()),
9957 window,
9958 cx,
9959 );
9960 });
9961 });
9962}
9963
9964pub fn clone_active_item(
9965 workspace_id: Option<WorkspaceId>,
9966 source: &Entity<Pane>,
9967 destination: &Entity<Pane>,
9968 focus_destination: bool,
9969 window: &mut Window,
9970 cx: &mut App,
9971) {
9972 if source == destination {
9973 return;
9974 }
9975 let Some(active_item) = source.read(cx).active_item() else {
9976 return;
9977 };
9978 if !active_item.can_split(cx) {
9979 return;
9980 }
9981 let destination = destination.downgrade();
9982 let task = active_item.clone_on_split(workspace_id, window, cx);
9983 window
9984 .spawn(cx, async move |cx| {
9985 let Some(clone) = task.await else {
9986 return;
9987 };
9988 destination
9989 .update_in(cx, |target_pane, window, cx| {
9990 target_pane.add_item(
9991 clone,
9992 focus_destination,
9993 focus_destination,
9994 Some(target_pane.items_len()),
9995 window,
9996 cx,
9997 );
9998 })
9999 .log_err();
10000 })
10001 .detach();
10002}
10003
10004#[derive(Debug)]
10005pub struct WorkspacePosition {
10006 pub window_bounds: Option<WindowBounds>,
10007 pub display: Option<Uuid>,
10008 pub centered_layout: bool,
10009}
10010
10011pub fn remote_workspace_position_from_db(
10012 connection_options: RemoteConnectionOptions,
10013 paths_to_open: &[PathBuf],
10014 cx: &App,
10015) -> Task<Result<WorkspacePosition>> {
10016 let paths = paths_to_open.to_vec();
10017 let db = WorkspaceDb::global(cx);
10018 let kvp = db::kvp::KeyValueStore::global(cx);
10019
10020 cx.background_spawn(async move {
10021 let remote_connection_id = db
10022 .get_or_create_remote_connection(connection_options)
10023 .await
10024 .context("fetching serialized ssh project")?;
10025 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10026
10027 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10028 (Some(WindowBounds::Windowed(bounds)), None)
10029 } else {
10030 let restorable_bounds = serialized_workspace
10031 .as_ref()
10032 .and_then(|workspace| {
10033 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10034 })
10035 .or_else(|| persistence::read_default_window_bounds(&kvp));
10036
10037 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10038 (Some(serialized_bounds), Some(serialized_display))
10039 } else {
10040 (None, None)
10041 }
10042 };
10043
10044 let centered_layout = serialized_workspace
10045 .as_ref()
10046 .map(|w| w.centered_layout)
10047 .unwrap_or(false);
10048
10049 Ok(WorkspacePosition {
10050 window_bounds,
10051 display,
10052 centered_layout,
10053 })
10054 })
10055}
10056
10057pub fn with_active_or_new_workspace(
10058 cx: &mut App,
10059 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10060) {
10061 match cx
10062 .active_window()
10063 .and_then(|w| w.downcast::<MultiWorkspace>())
10064 {
10065 Some(multi_workspace) => {
10066 cx.defer(move |cx| {
10067 multi_workspace
10068 .update(cx, |multi_workspace, window, cx| {
10069 let workspace = multi_workspace.workspace().clone();
10070 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10071 })
10072 .log_err();
10073 });
10074 }
10075 None => {
10076 let app_state = AppState::global(cx);
10077 if let Some(app_state) = app_state.upgrade() {
10078 open_new(
10079 OpenOptions::default(),
10080 app_state,
10081 cx,
10082 move |workspace, window, cx| f(workspace, window, cx),
10083 )
10084 .detach_and_log_err(cx);
10085 }
10086 }
10087 }
10088}
10089
10090#[cfg(test)]
10091mod tests {
10092 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10093
10094 use super::*;
10095 use crate::{
10096 dock::{PanelEvent, test::TestPanel},
10097 item::{
10098 ItemBufferKind, ItemEvent,
10099 test::{TestItem, TestProjectItem},
10100 },
10101 };
10102 use fs::FakeFs;
10103 use gpui::{
10104 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10105 UpdateGlobal, VisualTestContext, px,
10106 };
10107 use project::{Project, ProjectEntryId};
10108 use serde_json::json;
10109 use settings::SettingsStore;
10110 use util::path;
10111 use util::rel_path::rel_path;
10112
10113 #[gpui::test]
10114 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10115 init_test(cx);
10116
10117 let fs = FakeFs::new(cx.executor());
10118 let project = Project::test(fs, [], cx).await;
10119 let (workspace, cx) =
10120 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10121
10122 // Adding an item with no ambiguity renders the tab without detail.
10123 let item1 = cx.new(|cx| {
10124 let mut item = TestItem::new(cx);
10125 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10126 item
10127 });
10128 workspace.update_in(cx, |workspace, window, cx| {
10129 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10130 });
10131 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10132
10133 // Adding an item that creates ambiguity increases the level of detail on
10134 // both tabs.
10135 let item2 = cx.new_window_entity(|_window, cx| {
10136 let mut item = TestItem::new(cx);
10137 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10138 item
10139 });
10140 workspace.update_in(cx, |workspace, window, cx| {
10141 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10142 });
10143 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10144 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10145
10146 // Adding an item that creates ambiguity increases the level of detail only
10147 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10148 // we stop at the highest detail available.
10149 let item3 = cx.new(|cx| {
10150 let mut item = TestItem::new(cx);
10151 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10152 item
10153 });
10154 workspace.update_in(cx, |workspace, window, cx| {
10155 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10156 });
10157 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10158 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10159 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10160 }
10161
10162 #[gpui::test]
10163 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10164 init_test(cx);
10165
10166 let fs = FakeFs::new(cx.executor());
10167 fs.insert_tree(
10168 "/root1",
10169 json!({
10170 "one.txt": "",
10171 "two.txt": "",
10172 }),
10173 )
10174 .await;
10175 fs.insert_tree(
10176 "/root2",
10177 json!({
10178 "three.txt": "",
10179 }),
10180 )
10181 .await;
10182
10183 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10184 let (workspace, cx) =
10185 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10186 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10187 let worktree_id = project.update(cx, |project, cx| {
10188 project.worktrees(cx).next().unwrap().read(cx).id()
10189 });
10190
10191 let item1 = cx.new(|cx| {
10192 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10193 });
10194 let item2 = cx.new(|cx| {
10195 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10196 });
10197
10198 // Add an item to an empty pane
10199 workspace.update_in(cx, |workspace, window, cx| {
10200 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10201 });
10202 project.update(cx, |project, cx| {
10203 assert_eq!(
10204 project.active_entry(),
10205 project
10206 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10207 .map(|e| e.id)
10208 );
10209 });
10210 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10211
10212 // Add a second item to a non-empty pane
10213 workspace.update_in(cx, |workspace, window, cx| {
10214 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10215 });
10216 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10217 project.update(cx, |project, cx| {
10218 assert_eq!(
10219 project.active_entry(),
10220 project
10221 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10222 .map(|e| e.id)
10223 );
10224 });
10225
10226 // Close the active item
10227 pane.update_in(cx, |pane, window, cx| {
10228 pane.close_active_item(&Default::default(), window, cx)
10229 })
10230 .await
10231 .unwrap();
10232 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10233 project.update(cx, |project, cx| {
10234 assert_eq!(
10235 project.active_entry(),
10236 project
10237 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10238 .map(|e| e.id)
10239 );
10240 });
10241
10242 // Add a project folder
10243 project
10244 .update(cx, |project, cx| {
10245 project.find_or_create_worktree("root2", true, cx)
10246 })
10247 .await
10248 .unwrap();
10249 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10250
10251 // Remove a project folder
10252 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10253 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10254 }
10255
10256 #[gpui::test]
10257 async fn test_close_window(cx: &mut TestAppContext) {
10258 init_test(cx);
10259
10260 let fs = FakeFs::new(cx.executor());
10261 fs.insert_tree("/root", json!({ "one": "" })).await;
10262
10263 let project = Project::test(fs, ["root".as_ref()], cx).await;
10264 let (workspace, cx) =
10265 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10266
10267 // When there are no dirty items, there's nothing to do.
10268 let item1 = cx.new(TestItem::new);
10269 workspace.update_in(cx, |w, window, cx| {
10270 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10271 });
10272 let task = workspace.update_in(cx, |w, window, cx| {
10273 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10274 });
10275 assert!(task.await.unwrap());
10276
10277 // When there are dirty untitled items, prompt to save each one. If the user
10278 // cancels any prompt, then abort.
10279 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10280 let item3 = cx.new(|cx| {
10281 TestItem::new(cx)
10282 .with_dirty(true)
10283 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10284 });
10285 workspace.update_in(cx, |w, window, cx| {
10286 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10287 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10288 });
10289 let task = workspace.update_in(cx, |w, window, cx| {
10290 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10291 });
10292 cx.executor().run_until_parked();
10293 cx.simulate_prompt_answer("Cancel"); // cancel save all
10294 cx.executor().run_until_parked();
10295 assert!(!cx.has_pending_prompt());
10296 assert!(!task.await.unwrap());
10297 }
10298
10299 #[gpui::test]
10300 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10301 init_test(cx);
10302
10303 let fs = FakeFs::new(cx.executor());
10304 fs.insert_tree("/root", json!({ "one": "" })).await;
10305
10306 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10307 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10308 let multi_workspace_handle =
10309 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10310 cx.run_until_parked();
10311
10312 let workspace_a = multi_workspace_handle
10313 .read_with(cx, |mw, _| mw.workspace().clone())
10314 .unwrap();
10315
10316 let workspace_b = multi_workspace_handle
10317 .update(cx, |mw, window, cx| {
10318 mw.test_add_workspace(project_b, window, cx)
10319 })
10320 .unwrap();
10321
10322 // Activate workspace A
10323 multi_workspace_handle
10324 .update(cx, |mw, window, cx| {
10325 mw.activate_index(0, window, cx);
10326 })
10327 .unwrap();
10328
10329 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10330
10331 // Workspace A has a clean item
10332 let item_a = cx.new(TestItem::new);
10333 workspace_a.update_in(cx, |w, window, cx| {
10334 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10335 });
10336
10337 // Workspace B has a dirty item
10338 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10339 workspace_b.update_in(cx, |w, window, cx| {
10340 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10341 });
10342
10343 // Verify workspace A is active
10344 multi_workspace_handle
10345 .read_with(cx, |mw, _| {
10346 assert_eq!(mw.active_workspace_index(), 0);
10347 })
10348 .unwrap();
10349
10350 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10351 multi_workspace_handle
10352 .update(cx, |mw, window, cx| {
10353 mw.close_window(&CloseWindow, window, cx);
10354 })
10355 .unwrap();
10356 cx.run_until_parked();
10357
10358 // Workspace B should now be active since it has dirty items that need attention
10359 multi_workspace_handle
10360 .read_with(cx, |mw, _| {
10361 assert_eq!(
10362 mw.active_workspace_index(),
10363 1,
10364 "workspace B should be activated when it prompts"
10365 );
10366 })
10367 .unwrap();
10368
10369 // User cancels the save prompt from workspace B
10370 cx.simulate_prompt_answer("Cancel");
10371 cx.run_until_parked();
10372
10373 // Window should still exist because workspace B's close was cancelled
10374 assert!(
10375 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10376 "window should still exist after cancelling one workspace's close"
10377 );
10378 }
10379
10380 #[gpui::test]
10381 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10382 init_test(cx);
10383
10384 // Register TestItem as a serializable item
10385 cx.update(|cx| {
10386 register_serializable_item::<TestItem>(cx);
10387 });
10388
10389 let fs = FakeFs::new(cx.executor());
10390 fs.insert_tree("/root", json!({ "one": "" })).await;
10391
10392 let project = Project::test(fs, ["root".as_ref()], cx).await;
10393 let (workspace, cx) =
10394 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10395
10396 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10397 let item1 = cx.new(|cx| {
10398 TestItem::new(cx)
10399 .with_dirty(true)
10400 .with_serialize(|| Some(Task::ready(Ok(()))))
10401 });
10402 let item2 = cx.new(|cx| {
10403 TestItem::new(cx)
10404 .with_dirty(true)
10405 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10406 .with_serialize(|| Some(Task::ready(Ok(()))))
10407 });
10408 workspace.update_in(cx, |w, window, cx| {
10409 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10410 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10411 });
10412 let task = workspace.update_in(cx, |w, window, cx| {
10413 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10414 });
10415 assert!(task.await.unwrap());
10416 }
10417
10418 #[gpui::test]
10419 async fn test_close_pane_items(cx: &mut TestAppContext) {
10420 init_test(cx);
10421
10422 let fs = FakeFs::new(cx.executor());
10423
10424 let project = Project::test(fs, None, cx).await;
10425 let (workspace, cx) =
10426 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10427
10428 let item1 = cx.new(|cx| {
10429 TestItem::new(cx)
10430 .with_dirty(true)
10431 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10432 });
10433 let item2 = cx.new(|cx| {
10434 TestItem::new(cx)
10435 .with_dirty(true)
10436 .with_conflict(true)
10437 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10438 });
10439 let item3 = cx.new(|cx| {
10440 TestItem::new(cx)
10441 .with_dirty(true)
10442 .with_conflict(true)
10443 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10444 });
10445 let item4 = cx.new(|cx| {
10446 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10447 let project_item = TestProjectItem::new_untitled(cx);
10448 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10449 project_item
10450 }])
10451 });
10452 let pane = workspace.update_in(cx, |workspace, window, cx| {
10453 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10454 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10455 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10456 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10457 workspace.active_pane().clone()
10458 });
10459
10460 let close_items = pane.update_in(cx, |pane, window, cx| {
10461 pane.activate_item(1, true, true, window, cx);
10462 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10463 let item1_id = item1.item_id();
10464 let item3_id = item3.item_id();
10465 let item4_id = item4.item_id();
10466 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10467 [item1_id, item3_id, item4_id].contains(&id)
10468 })
10469 });
10470 cx.executor().run_until_parked();
10471
10472 assert!(cx.has_pending_prompt());
10473 cx.simulate_prompt_answer("Save all");
10474
10475 cx.executor().run_until_parked();
10476
10477 // Item 1 is saved. There's a prompt to save item 3.
10478 pane.update(cx, |pane, cx| {
10479 assert_eq!(item1.read(cx).save_count, 1);
10480 assert_eq!(item1.read(cx).save_as_count, 0);
10481 assert_eq!(item1.read(cx).reload_count, 0);
10482 assert_eq!(pane.items_len(), 3);
10483 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10484 });
10485 assert!(cx.has_pending_prompt());
10486
10487 // Cancel saving item 3.
10488 cx.simulate_prompt_answer("Discard");
10489 cx.executor().run_until_parked();
10490
10491 // Item 3 is reloaded. There's a prompt to save item 4.
10492 pane.update(cx, |pane, cx| {
10493 assert_eq!(item3.read(cx).save_count, 0);
10494 assert_eq!(item3.read(cx).save_as_count, 0);
10495 assert_eq!(item3.read(cx).reload_count, 1);
10496 assert_eq!(pane.items_len(), 2);
10497 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10498 });
10499
10500 // There's a prompt for a path for item 4.
10501 cx.simulate_new_path_selection(|_| Some(Default::default()));
10502 close_items.await.unwrap();
10503
10504 // The requested items are closed.
10505 pane.update(cx, |pane, cx| {
10506 assert_eq!(item4.read(cx).save_count, 0);
10507 assert_eq!(item4.read(cx).save_as_count, 1);
10508 assert_eq!(item4.read(cx).reload_count, 0);
10509 assert_eq!(pane.items_len(), 1);
10510 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10511 });
10512 }
10513
10514 #[gpui::test]
10515 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10516 init_test(cx);
10517
10518 let fs = FakeFs::new(cx.executor());
10519 let project = Project::test(fs, [], cx).await;
10520 let (workspace, cx) =
10521 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10522
10523 // Create several workspace items with single project entries, and two
10524 // workspace items with multiple project entries.
10525 let single_entry_items = (0..=4)
10526 .map(|project_entry_id| {
10527 cx.new(|cx| {
10528 TestItem::new(cx)
10529 .with_dirty(true)
10530 .with_project_items(&[dirty_project_item(
10531 project_entry_id,
10532 &format!("{project_entry_id}.txt"),
10533 cx,
10534 )])
10535 })
10536 })
10537 .collect::<Vec<_>>();
10538 let item_2_3 = cx.new(|cx| {
10539 TestItem::new(cx)
10540 .with_dirty(true)
10541 .with_buffer_kind(ItemBufferKind::Multibuffer)
10542 .with_project_items(&[
10543 single_entry_items[2].read(cx).project_items[0].clone(),
10544 single_entry_items[3].read(cx).project_items[0].clone(),
10545 ])
10546 });
10547 let item_3_4 = cx.new(|cx| {
10548 TestItem::new(cx)
10549 .with_dirty(true)
10550 .with_buffer_kind(ItemBufferKind::Multibuffer)
10551 .with_project_items(&[
10552 single_entry_items[3].read(cx).project_items[0].clone(),
10553 single_entry_items[4].read(cx).project_items[0].clone(),
10554 ])
10555 });
10556
10557 // Create two panes that contain the following project entries:
10558 // left pane:
10559 // multi-entry items: (2, 3)
10560 // single-entry items: 0, 2, 3, 4
10561 // right pane:
10562 // single-entry items: 4, 1
10563 // multi-entry items: (3, 4)
10564 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10565 let left_pane = workspace.active_pane().clone();
10566 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10567 workspace.add_item_to_active_pane(
10568 single_entry_items[0].boxed_clone(),
10569 None,
10570 true,
10571 window,
10572 cx,
10573 );
10574 workspace.add_item_to_active_pane(
10575 single_entry_items[2].boxed_clone(),
10576 None,
10577 true,
10578 window,
10579 cx,
10580 );
10581 workspace.add_item_to_active_pane(
10582 single_entry_items[3].boxed_clone(),
10583 None,
10584 true,
10585 window,
10586 cx,
10587 );
10588 workspace.add_item_to_active_pane(
10589 single_entry_items[4].boxed_clone(),
10590 None,
10591 true,
10592 window,
10593 cx,
10594 );
10595
10596 let right_pane =
10597 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10598
10599 let boxed_clone = single_entry_items[1].boxed_clone();
10600 let right_pane = window.spawn(cx, async move |cx| {
10601 right_pane.await.inspect(|right_pane| {
10602 right_pane
10603 .update_in(cx, |pane, window, cx| {
10604 pane.add_item(boxed_clone, true, true, None, window, cx);
10605 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10606 })
10607 .unwrap();
10608 })
10609 });
10610
10611 (left_pane, right_pane)
10612 });
10613 let right_pane = right_pane.await.unwrap();
10614 cx.focus(&right_pane);
10615
10616 let close = right_pane.update_in(cx, |pane, window, cx| {
10617 pane.close_all_items(&CloseAllItems::default(), window, cx)
10618 .unwrap()
10619 });
10620 cx.executor().run_until_parked();
10621
10622 let msg = cx.pending_prompt().unwrap().0;
10623 assert!(msg.contains("1.txt"));
10624 assert!(!msg.contains("2.txt"));
10625 assert!(!msg.contains("3.txt"));
10626 assert!(!msg.contains("4.txt"));
10627
10628 // With best-effort close, cancelling item 1 keeps it open but items 4
10629 // and (3,4) still close since their entries exist in left pane.
10630 cx.simulate_prompt_answer("Cancel");
10631 close.await;
10632
10633 right_pane.read_with(cx, |pane, _| {
10634 assert_eq!(pane.items_len(), 1);
10635 });
10636
10637 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10638 left_pane
10639 .update_in(cx, |left_pane, window, cx| {
10640 left_pane.close_item_by_id(
10641 single_entry_items[3].entity_id(),
10642 SaveIntent::Skip,
10643 window,
10644 cx,
10645 )
10646 })
10647 .await
10648 .unwrap();
10649
10650 let close = left_pane.update_in(cx, |pane, window, cx| {
10651 pane.close_all_items(&CloseAllItems::default(), window, cx)
10652 .unwrap()
10653 });
10654 cx.executor().run_until_parked();
10655
10656 let details = cx.pending_prompt().unwrap().1;
10657 assert!(details.contains("0.txt"));
10658 assert!(details.contains("3.txt"));
10659 assert!(details.contains("4.txt"));
10660 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10661 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10662 // assert!(!details.contains("2.txt"));
10663
10664 cx.simulate_prompt_answer("Save all");
10665 cx.executor().run_until_parked();
10666 close.await;
10667
10668 left_pane.read_with(cx, |pane, _| {
10669 assert_eq!(pane.items_len(), 0);
10670 });
10671 }
10672
10673 #[gpui::test]
10674 async fn test_autosave(cx: &mut gpui::TestAppContext) {
10675 init_test(cx);
10676
10677 let fs = FakeFs::new(cx.executor());
10678 let project = Project::test(fs, [], cx).await;
10679 let (workspace, cx) =
10680 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10681 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10682
10683 let item = cx.new(|cx| {
10684 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10685 });
10686 let item_id = item.entity_id();
10687 workspace.update_in(cx, |workspace, window, cx| {
10688 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10689 });
10690
10691 // Autosave on window change.
10692 item.update(cx, |item, cx| {
10693 SettingsStore::update_global(cx, |settings, cx| {
10694 settings.update_user_settings(cx, |settings| {
10695 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10696 })
10697 });
10698 item.is_dirty = true;
10699 });
10700
10701 // Deactivating the window saves the file.
10702 cx.deactivate_window();
10703 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10704
10705 // Re-activating the window doesn't save the file.
10706 cx.update(|window, _| window.activate_window());
10707 cx.executor().run_until_parked();
10708 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10709
10710 // Autosave on focus change.
10711 item.update_in(cx, |item, window, cx| {
10712 cx.focus_self(window);
10713 SettingsStore::update_global(cx, |settings, cx| {
10714 settings.update_user_settings(cx, |settings| {
10715 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10716 })
10717 });
10718 item.is_dirty = true;
10719 });
10720 // Blurring the item saves the file.
10721 item.update_in(cx, |_, window, _| window.blur());
10722 cx.executor().run_until_parked();
10723 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10724
10725 // Deactivating the window still saves the file.
10726 item.update_in(cx, |item, window, cx| {
10727 cx.focus_self(window);
10728 item.is_dirty = true;
10729 });
10730 cx.deactivate_window();
10731 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10732
10733 // Autosave after delay.
10734 item.update(cx, |item, cx| {
10735 SettingsStore::update_global(cx, |settings, cx| {
10736 settings.update_user_settings(cx, |settings| {
10737 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10738 milliseconds: 500.into(),
10739 });
10740 })
10741 });
10742 item.is_dirty = true;
10743 cx.emit(ItemEvent::Edit);
10744 });
10745
10746 // Delay hasn't fully expired, so the file is still dirty and unsaved.
10747 cx.executor().advance_clock(Duration::from_millis(250));
10748 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10749
10750 // After delay expires, the file is saved.
10751 cx.executor().advance_clock(Duration::from_millis(250));
10752 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10753
10754 // Autosave after delay, should save earlier than delay if tab is closed
10755 item.update(cx, |item, cx| {
10756 item.is_dirty = true;
10757 cx.emit(ItemEvent::Edit);
10758 });
10759 cx.executor().advance_clock(Duration::from_millis(250));
10760 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10761
10762 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10763 pane.update_in(cx, |pane, window, cx| {
10764 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10765 })
10766 .await
10767 .unwrap();
10768 assert!(!cx.has_pending_prompt());
10769 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10770
10771 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10772 workspace.update_in(cx, |workspace, window, cx| {
10773 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10774 });
10775 item.update_in(cx, |item, _window, cx| {
10776 item.is_dirty = true;
10777 for project_item in &mut item.project_items {
10778 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10779 }
10780 });
10781 cx.run_until_parked();
10782 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10783
10784 // Autosave on focus change, ensuring closing the tab counts as such.
10785 item.update(cx, |item, cx| {
10786 SettingsStore::update_global(cx, |settings, cx| {
10787 settings.update_user_settings(cx, |settings| {
10788 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10789 })
10790 });
10791 item.is_dirty = true;
10792 for project_item in &mut item.project_items {
10793 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10794 }
10795 });
10796
10797 pane.update_in(cx, |pane, window, cx| {
10798 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10799 })
10800 .await
10801 .unwrap();
10802 assert!(!cx.has_pending_prompt());
10803 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10804
10805 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10806 workspace.update_in(cx, |workspace, window, cx| {
10807 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10808 });
10809 item.update_in(cx, |item, window, cx| {
10810 item.project_items[0].update(cx, |item, _| {
10811 item.entry_id = None;
10812 });
10813 item.is_dirty = true;
10814 window.blur();
10815 });
10816 cx.run_until_parked();
10817 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10818
10819 // Ensure autosave is prevented for deleted files also when closing the buffer.
10820 let _close_items = pane.update_in(cx, |pane, window, cx| {
10821 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10822 });
10823 cx.run_until_parked();
10824 assert!(cx.has_pending_prompt());
10825 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10826 }
10827
10828 #[gpui::test]
10829 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
10830 init_test(cx);
10831
10832 let fs = FakeFs::new(cx.executor());
10833 let project = Project::test(fs, [], cx).await;
10834 let (workspace, cx) =
10835 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10836
10837 // Create a multibuffer-like item with two child focus handles,
10838 // simulating individual buffer editors within a multibuffer.
10839 let item = cx.new(|cx| {
10840 TestItem::new(cx)
10841 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10842 .with_child_focus_handles(2, cx)
10843 });
10844 workspace.update_in(cx, |workspace, window, cx| {
10845 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10846 });
10847
10848 // Set autosave to OnFocusChange and focus the first child handle,
10849 // simulating the user's cursor being inside one of the multibuffer's excerpts.
10850 item.update_in(cx, |item, window, cx| {
10851 SettingsStore::update_global(cx, |settings, cx| {
10852 settings.update_user_settings(cx, |settings| {
10853 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10854 })
10855 });
10856 item.is_dirty = true;
10857 window.focus(&item.child_focus_handles[0], cx);
10858 });
10859 cx.executor().run_until_parked();
10860 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
10861
10862 // Moving focus from one child to another within the same item should
10863 // NOT trigger autosave — focus is still within the item's focus hierarchy.
10864 item.update_in(cx, |item, window, cx| {
10865 window.focus(&item.child_focus_handles[1], cx);
10866 });
10867 cx.executor().run_until_parked();
10868 item.read_with(cx, |item, _| {
10869 assert_eq!(
10870 item.save_count, 0,
10871 "Switching focus between children within the same item should not autosave"
10872 );
10873 });
10874
10875 // Blurring the item saves the file. This is the core regression scenario:
10876 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
10877 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
10878 // the leaf is always a child focus handle, so `on_blur` never detected
10879 // focus leaving the item.
10880 item.update_in(cx, |_, window, _| window.blur());
10881 cx.executor().run_until_parked();
10882 item.read_with(cx, |item, _| {
10883 assert_eq!(
10884 item.save_count, 1,
10885 "Blurring should trigger autosave when focus was on a child of the item"
10886 );
10887 });
10888
10889 // Deactivating the window should also trigger autosave when a child of
10890 // the multibuffer item currently owns focus.
10891 item.update_in(cx, |item, window, cx| {
10892 item.is_dirty = true;
10893 window.focus(&item.child_focus_handles[0], cx);
10894 });
10895 cx.executor().run_until_parked();
10896 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10897
10898 cx.deactivate_window();
10899 item.read_with(cx, |item, _| {
10900 assert_eq!(
10901 item.save_count, 2,
10902 "Deactivating window should trigger autosave when focus was on a child"
10903 );
10904 });
10905 }
10906
10907 #[gpui::test]
10908 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10909 init_test(cx);
10910
10911 let fs = FakeFs::new(cx.executor());
10912
10913 let project = Project::test(fs, [], cx).await;
10914 let (workspace, cx) =
10915 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10916
10917 let item = cx.new(|cx| {
10918 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10919 });
10920 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10921 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10922 let toolbar_notify_count = Rc::new(RefCell::new(0));
10923
10924 workspace.update_in(cx, |workspace, window, cx| {
10925 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10926 let toolbar_notification_count = toolbar_notify_count.clone();
10927 cx.observe_in(&toolbar, window, move |_, _, _, _| {
10928 *toolbar_notification_count.borrow_mut() += 1
10929 })
10930 .detach();
10931 });
10932
10933 pane.read_with(cx, |pane, _| {
10934 assert!(!pane.can_navigate_backward());
10935 assert!(!pane.can_navigate_forward());
10936 });
10937
10938 item.update_in(cx, |item, _, cx| {
10939 item.set_state("one".to_string(), cx);
10940 });
10941
10942 // Toolbar must be notified to re-render the navigation buttons
10943 assert_eq!(*toolbar_notify_count.borrow(), 1);
10944
10945 pane.read_with(cx, |pane, _| {
10946 assert!(pane.can_navigate_backward());
10947 assert!(!pane.can_navigate_forward());
10948 });
10949
10950 workspace
10951 .update_in(cx, |workspace, window, cx| {
10952 workspace.go_back(pane.downgrade(), window, cx)
10953 })
10954 .await
10955 .unwrap();
10956
10957 assert_eq!(*toolbar_notify_count.borrow(), 2);
10958 pane.read_with(cx, |pane, _| {
10959 assert!(!pane.can_navigate_backward());
10960 assert!(pane.can_navigate_forward());
10961 });
10962 }
10963
10964 #[gpui::test]
10965 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
10966 init_test(cx);
10967 let fs = FakeFs::new(cx.executor());
10968 let project = Project::test(fs, [], cx).await;
10969 let (multi_workspace, cx) =
10970 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
10971 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
10972
10973 workspace.update_in(cx, |workspace, window, cx| {
10974 let first_item = cx.new(|cx| {
10975 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10976 });
10977 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
10978 workspace.split_pane(
10979 workspace.active_pane().clone(),
10980 SplitDirection::Right,
10981 window,
10982 cx,
10983 );
10984 workspace.split_pane(
10985 workspace.active_pane().clone(),
10986 SplitDirection::Right,
10987 window,
10988 cx,
10989 );
10990 });
10991
10992 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
10993 let panes = workspace.center.panes();
10994 assert!(panes.len() >= 2);
10995 (
10996 panes.first().expect("at least one pane").entity_id(),
10997 panes.last().expect("at least one pane").entity_id(),
10998 )
10999 });
11000
11001 workspace.update_in(cx, |workspace, window, cx| {
11002 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11003 });
11004 workspace.update(cx, |workspace, _| {
11005 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11006 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11007 });
11008
11009 cx.dispatch_action(ActivateLastPane);
11010
11011 workspace.update(cx, |workspace, _| {
11012 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11013 });
11014 }
11015
11016 #[gpui::test]
11017 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11018 init_test(cx);
11019 let fs = FakeFs::new(cx.executor());
11020
11021 let project = Project::test(fs, [], cx).await;
11022 let (workspace, cx) =
11023 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11024
11025 let panel = workspace.update_in(cx, |workspace, window, cx| {
11026 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11027 workspace.add_panel(panel.clone(), window, cx);
11028
11029 workspace
11030 .right_dock()
11031 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11032
11033 panel
11034 });
11035
11036 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11037 pane.update_in(cx, |pane, window, cx| {
11038 let item = cx.new(TestItem::new);
11039 pane.add_item(Box::new(item), true, true, None, window, cx);
11040 });
11041
11042 // Transfer focus from center to panel
11043 workspace.update_in(cx, |workspace, window, cx| {
11044 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11045 });
11046
11047 workspace.update_in(cx, |workspace, window, cx| {
11048 assert!(workspace.right_dock().read(cx).is_open());
11049 assert!(!panel.is_zoomed(window, cx));
11050 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11051 });
11052
11053 // Transfer focus from panel to center
11054 workspace.update_in(cx, |workspace, window, cx| {
11055 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11056 });
11057
11058 workspace.update_in(cx, |workspace, window, cx| {
11059 assert!(workspace.right_dock().read(cx).is_open());
11060 assert!(!panel.is_zoomed(window, cx));
11061 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11062 });
11063
11064 // Close the dock
11065 workspace.update_in(cx, |workspace, window, cx| {
11066 workspace.toggle_dock(DockPosition::Right, window, cx);
11067 });
11068
11069 workspace.update_in(cx, |workspace, window, cx| {
11070 assert!(!workspace.right_dock().read(cx).is_open());
11071 assert!(!panel.is_zoomed(window, cx));
11072 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11073 });
11074
11075 // Open the dock
11076 workspace.update_in(cx, |workspace, window, cx| {
11077 workspace.toggle_dock(DockPosition::Right, window, cx);
11078 });
11079
11080 workspace.update_in(cx, |workspace, window, cx| {
11081 assert!(workspace.right_dock().read(cx).is_open());
11082 assert!(!panel.is_zoomed(window, cx));
11083 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11084 });
11085
11086 // Focus and zoom panel
11087 panel.update_in(cx, |panel, window, cx| {
11088 cx.focus_self(window);
11089 panel.set_zoomed(true, window, cx)
11090 });
11091
11092 workspace.update_in(cx, |workspace, window, cx| {
11093 assert!(workspace.right_dock().read(cx).is_open());
11094 assert!(panel.is_zoomed(window, cx));
11095 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11096 });
11097
11098 // Transfer focus to the center closes the dock
11099 workspace.update_in(cx, |workspace, window, cx| {
11100 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11101 });
11102
11103 workspace.update_in(cx, |workspace, window, cx| {
11104 assert!(!workspace.right_dock().read(cx).is_open());
11105 assert!(panel.is_zoomed(window, cx));
11106 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11107 });
11108
11109 // Transferring focus back to the panel keeps it zoomed
11110 workspace.update_in(cx, |workspace, window, cx| {
11111 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11112 });
11113
11114 workspace.update_in(cx, |workspace, window, cx| {
11115 assert!(workspace.right_dock().read(cx).is_open());
11116 assert!(panel.is_zoomed(window, cx));
11117 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11118 });
11119
11120 // Close the dock while it is zoomed
11121 workspace.update_in(cx, |workspace, window, cx| {
11122 workspace.toggle_dock(DockPosition::Right, window, cx)
11123 });
11124
11125 workspace.update_in(cx, |workspace, window, cx| {
11126 assert!(!workspace.right_dock().read(cx).is_open());
11127 assert!(panel.is_zoomed(window, cx));
11128 assert!(workspace.zoomed.is_none());
11129 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11130 });
11131
11132 // Opening the dock, when it's zoomed, retains focus
11133 workspace.update_in(cx, |workspace, window, cx| {
11134 workspace.toggle_dock(DockPosition::Right, window, cx)
11135 });
11136
11137 workspace.update_in(cx, |workspace, window, cx| {
11138 assert!(workspace.right_dock().read(cx).is_open());
11139 assert!(panel.is_zoomed(window, cx));
11140 assert!(workspace.zoomed.is_some());
11141 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11142 });
11143
11144 // Unzoom and close the panel, zoom the active pane.
11145 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11146 workspace.update_in(cx, |workspace, window, cx| {
11147 workspace.toggle_dock(DockPosition::Right, window, cx)
11148 });
11149 pane.update_in(cx, |pane, window, cx| {
11150 pane.toggle_zoom(&Default::default(), window, cx)
11151 });
11152
11153 // Opening a dock unzooms the pane.
11154 workspace.update_in(cx, |workspace, window, cx| {
11155 workspace.toggle_dock(DockPosition::Right, window, cx)
11156 });
11157 workspace.update_in(cx, |workspace, window, cx| {
11158 let pane = pane.read(cx);
11159 assert!(!pane.is_zoomed());
11160 assert!(!pane.focus_handle(cx).is_focused(window));
11161 assert!(workspace.right_dock().read(cx).is_open());
11162 assert!(workspace.zoomed.is_none());
11163 });
11164 }
11165
11166 #[gpui::test]
11167 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11168 init_test(cx);
11169 let fs = FakeFs::new(cx.executor());
11170
11171 let project = Project::test(fs, [], cx).await;
11172 let (workspace, cx) =
11173 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11174
11175 let panel = workspace.update_in(cx, |workspace, window, cx| {
11176 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11177 workspace.add_panel(panel.clone(), window, cx);
11178 panel
11179 });
11180
11181 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11182 pane.update_in(cx, |pane, window, cx| {
11183 let item = cx.new(TestItem::new);
11184 pane.add_item(Box::new(item), true, true, None, window, cx);
11185 });
11186
11187 // Enable close_panel_on_toggle
11188 cx.update_global(|store: &mut SettingsStore, cx| {
11189 store.update_user_settings(cx, |settings| {
11190 settings.workspace.close_panel_on_toggle = Some(true);
11191 });
11192 });
11193
11194 // Panel starts closed. Toggling should open and focus it.
11195 workspace.update_in(cx, |workspace, window, cx| {
11196 assert!(!workspace.right_dock().read(cx).is_open());
11197 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11198 });
11199
11200 workspace.update_in(cx, |workspace, window, cx| {
11201 assert!(
11202 workspace.right_dock().read(cx).is_open(),
11203 "Dock should be open after toggling from center"
11204 );
11205 assert!(
11206 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11207 "Panel should be focused after toggling from center"
11208 );
11209 });
11210
11211 // Panel is open and focused. Toggling should close the panel and
11212 // return focus to the center.
11213 workspace.update_in(cx, |workspace, window, cx| {
11214 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11215 });
11216
11217 workspace.update_in(cx, |workspace, window, cx| {
11218 assert!(
11219 !workspace.right_dock().read(cx).is_open(),
11220 "Dock should be closed after toggling from focused panel"
11221 );
11222 assert!(
11223 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11224 "Panel should not be focused after toggling from focused panel"
11225 );
11226 });
11227
11228 // Open the dock and focus something else so the panel is open but not
11229 // focused. Toggling should focus the panel (not close it).
11230 workspace.update_in(cx, |workspace, window, cx| {
11231 workspace
11232 .right_dock()
11233 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11234 window.focus(&pane.read(cx).focus_handle(cx), cx);
11235 });
11236
11237 workspace.update_in(cx, |workspace, window, cx| {
11238 assert!(workspace.right_dock().read(cx).is_open());
11239 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11240 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11241 });
11242
11243 workspace.update_in(cx, |workspace, window, cx| {
11244 assert!(
11245 workspace.right_dock().read(cx).is_open(),
11246 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11247 );
11248 assert!(
11249 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11250 "Panel should be focused after toggling an open-but-unfocused panel"
11251 );
11252 });
11253
11254 // Now disable the setting and verify the original behavior: toggling
11255 // from a focused panel moves focus to center but leaves the dock open.
11256 cx.update_global(|store: &mut SettingsStore, cx| {
11257 store.update_user_settings(cx, |settings| {
11258 settings.workspace.close_panel_on_toggle = Some(false);
11259 });
11260 });
11261
11262 workspace.update_in(cx, |workspace, window, cx| {
11263 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11264 });
11265
11266 workspace.update_in(cx, |workspace, window, cx| {
11267 assert!(
11268 workspace.right_dock().read(cx).is_open(),
11269 "Dock should remain open when setting is disabled"
11270 );
11271 assert!(
11272 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11273 "Panel should not be focused after toggling with setting disabled"
11274 );
11275 });
11276 }
11277
11278 #[gpui::test]
11279 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11280 init_test(cx);
11281 let fs = FakeFs::new(cx.executor());
11282
11283 let project = Project::test(fs, [], cx).await;
11284 let (workspace, cx) =
11285 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11286
11287 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11288 workspace.active_pane().clone()
11289 });
11290
11291 // Add an item to the pane so it can be zoomed
11292 workspace.update_in(cx, |workspace, window, cx| {
11293 let item = cx.new(TestItem::new);
11294 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11295 });
11296
11297 // Initially not zoomed
11298 workspace.update_in(cx, |workspace, _window, cx| {
11299 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11300 assert!(
11301 workspace.zoomed.is_none(),
11302 "Workspace should track no zoomed pane"
11303 );
11304 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11305 });
11306
11307 // Zoom In
11308 pane.update_in(cx, |pane, window, cx| {
11309 pane.zoom_in(&crate::ZoomIn, window, cx);
11310 });
11311
11312 workspace.update_in(cx, |workspace, window, cx| {
11313 assert!(
11314 pane.read(cx).is_zoomed(),
11315 "Pane should be zoomed after ZoomIn"
11316 );
11317 assert!(
11318 workspace.zoomed.is_some(),
11319 "Workspace should track the zoomed pane"
11320 );
11321 assert!(
11322 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11323 "ZoomIn should focus the pane"
11324 );
11325 });
11326
11327 // Zoom In again is a no-op
11328 pane.update_in(cx, |pane, window, cx| {
11329 pane.zoom_in(&crate::ZoomIn, window, cx);
11330 });
11331
11332 workspace.update_in(cx, |workspace, window, cx| {
11333 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11334 assert!(
11335 workspace.zoomed.is_some(),
11336 "Workspace still tracks zoomed pane"
11337 );
11338 assert!(
11339 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11340 "Pane remains focused after repeated ZoomIn"
11341 );
11342 });
11343
11344 // Zoom Out
11345 pane.update_in(cx, |pane, window, cx| {
11346 pane.zoom_out(&crate::ZoomOut, window, cx);
11347 });
11348
11349 workspace.update_in(cx, |workspace, _window, cx| {
11350 assert!(
11351 !pane.read(cx).is_zoomed(),
11352 "Pane should unzoom after ZoomOut"
11353 );
11354 assert!(
11355 workspace.zoomed.is_none(),
11356 "Workspace clears zoom tracking after ZoomOut"
11357 );
11358 });
11359
11360 // Zoom Out again is a no-op
11361 pane.update_in(cx, |pane, window, cx| {
11362 pane.zoom_out(&crate::ZoomOut, window, cx);
11363 });
11364
11365 workspace.update_in(cx, |workspace, _window, cx| {
11366 assert!(
11367 !pane.read(cx).is_zoomed(),
11368 "Second ZoomOut keeps pane unzoomed"
11369 );
11370 assert!(
11371 workspace.zoomed.is_none(),
11372 "Workspace remains without zoomed pane"
11373 );
11374 });
11375 }
11376
11377 #[gpui::test]
11378 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11379 init_test(cx);
11380 let fs = FakeFs::new(cx.executor());
11381
11382 let project = Project::test(fs, [], cx).await;
11383 let (workspace, cx) =
11384 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11385 workspace.update_in(cx, |workspace, window, cx| {
11386 // Open two docks
11387 let left_dock = workspace.dock_at_position(DockPosition::Left);
11388 let right_dock = workspace.dock_at_position(DockPosition::Right);
11389
11390 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11391 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11392
11393 assert!(left_dock.read(cx).is_open());
11394 assert!(right_dock.read(cx).is_open());
11395 });
11396
11397 workspace.update_in(cx, |workspace, window, cx| {
11398 // Toggle all docks - should close both
11399 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11400
11401 let left_dock = workspace.dock_at_position(DockPosition::Left);
11402 let right_dock = workspace.dock_at_position(DockPosition::Right);
11403 assert!(!left_dock.read(cx).is_open());
11404 assert!(!right_dock.read(cx).is_open());
11405 });
11406
11407 workspace.update_in(cx, |workspace, window, cx| {
11408 // Toggle again - should reopen both
11409 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11410
11411 let left_dock = workspace.dock_at_position(DockPosition::Left);
11412 let right_dock = workspace.dock_at_position(DockPosition::Right);
11413 assert!(left_dock.read(cx).is_open());
11414 assert!(right_dock.read(cx).is_open());
11415 });
11416 }
11417
11418 #[gpui::test]
11419 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11420 init_test(cx);
11421 let fs = FakeFs::new(cx.executor());
11422
11423 let project = Project::test(fs, [], cx).await;
11424 let (workspace, cx) =
11425 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11426 workspace.update_in(cx, |workspace, window, cx| {
11427 // Open two docks
11428 let left_dock = workspace.dock_at_position(DockPosition::Left);
11429 let right_dock = workspace.dock_at_position(DockPosition::Right);
11430
11431 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11432 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11433
11434 assert!(left_dock.read(cx).is_open());
11435 assert!(right_dock.read(cx).is_open());
11436 });
11437
11438 workspace.update_in(cx, |workspace, window, cx| {
11439 // Close them manually
11440 workspace.toggle_dock(DockPosition::Left, window, cx);
11441 workspace.toggle_dock(DockPosition::Right, window, cx);
11442
11443 let left_dock = workspace.dock_at_position(DockPosition::Left);
11444 let right_dock = workspace.dock_at_position(DockPosition::Right);
11445 assert!(!left_dock.read(cx).is_open());
11446 assert!(!right_dock.read(cx).is_open());
11447 });
11448
11449 workspace.update_in(cx, |workspace, window, cx| {
11450 // Toggle all docks - only last closed (right dock) should reopen
11451 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11452
11453 let left_dock = workspace.dock_at_position(DockPosition::Left);
11454 let right_dock = workspace.dock_at_position(DockPosition::Right);
11455 assert!(!left_dock.read(cx).is_open());
11456 assert!(right_dock.read(cx).is_open());
11457 });
11458 }
11459
11460 #[gpui::test]
11461 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11462 init_test(cx);
11463 let fs = FakeFs::new(cx.executor());
11464 let project = Project::test(fs, [], cx).await;
11465 let (multi_workspace, cx) =
11466 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11467 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11468
11469 // Open two docks (left and right) with one panel each
11470 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11471 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11472 workspace.add_panel(left_panel.clone(), window, cx);
11473
11474 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11475 workspace.add_panel(right_panel.clone(), window, cx);
11476
11477 workspace.toggle_dock(DockPosition::Left, window, cx);
11478 workspace.toggle_dock(DockPosition::Right, window, cx);
11479
11480 // Verify initial state
11481 assert!(
11482 workspace.left_dock().read(cx).is_open(),
11483 "Left dock should be open"
11484 );
11485 assert_eq!(
11486 workspace
11487 .left_dock()
11488 .read(cx)
11489 .visible_panel()
11490 .unwrap()
11491 .panel_id(),
11492 left_panel.panel_id(),
11493 "Left panel should be visible in left dock"
11494 );
11495 assert!(
11496 workspace.right_dock().read(cx).is_open(),
11497 "Right dock should be open"
11498 );
11499 assert_eq!(
11500 workspace
11501 .right_dock()
11502 .read(cx)
11503 .visible_panel()
11504 .unwrap()
11505 .panel_id(),
11506 right_panel.panel_id(),
11507 "Right panel should be visible in right dock"
11508 );
11509 assert!(
11510 !workspace.bottom_dock().read(cx).is_open(),
11511 "Bottom dock should be closed"
11512 );
11513
11514 (left_panel, right_panel)
11515 });
11516
11517 // Focus the left panel and move it to the next position (bottom dock)
11518 workspace.update_in(cx, |workspace, window, cx| {
11519 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11520 assert!(
11521 left_panel.read(cx).focus_handle(cx).is_focused(window),
11522 "Left panel should be focused"
11523 );
11524 });
11525
11526 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11527
11528 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11529 workspace.update(cx, |workspace, cx| {
11530 assert!(
11531 !workspace.left_dock().read(cx).is_open(),
11532 "Left dock should be closed"
11533 );
11534 assert!(
11535 workspace.bottom_dock().read(cx).is_open(),
11536 "Bottom dock should now be open"
11537 );
11538 assert_eq!(
11539 left_panel.read(cx).position,
11540 DockPosition::Bottom,
11541 "Left panel should now be in the bottom dock"
11542 );
11543 assert_eq!(
11544 workspace
11545 .bottom_dock()
11546 .read(cx)
11547 .visible_panel()
11548 .unwrap()
11549 .panel_id(),
11550 left_panel.panel_id(),
11551 "Left panel should be the visible panel in the bottom dock"
11552 );
11553 });
11554
11555 // Toggle all docks off
11556 workspace.update_in(cx, |workspace, window, cx| {
11557 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11558 assert!(
11559 !workspace.left_dock().read(cx).is_open(),
11560 "Left dock should be closed"
11561 );
11562 assert!(
11563 !workspace.right_dock().read(cx).is_open(),
11564 "Right dock should be closed"
11565 );
11566 assert!(
11567 !workspace.bottom_dock().read(cx).is_open(),
11568 "Bottom dock should be closed"
11569 );
11570 });
11571
11572 // Toggle all docks back on and verify positions are restored
11573 workspace.update_in(cx, |workspace, window, cx| {
11574 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11575 assert!(
11576 !workspace.left_dock().read(cx).is_open(),
11577 "Left dock should remain closed"
11578 );
11579 assert!(
11580 workspace.right_dock().read(cx).is_open(),
11581 "Right dock should remain open"
11582 );
11583 assert!(
11584 workspace.bottom_dock().read(cx).is_open(),
11585 "Bottom dock should remain open"
11586 );
11587 assert_eq!(
11588 left_panel.read(cx).position,
11589 DockPosition::Bottom,
11590 "Left panel should remain in the bottom dock"
11591 );
11592 assert_eq!(
11593 right_panel.read(cx).position,
11594 DockPosition::Right,
11595 "Right panel should remain in the right dock"
11596 );
11597 assert_eq!(
11598 workspace
11599 .bottom_dock()
11600 .read(cx)
11601 .visible_panel()
11602 .unwrap()
11603 .panel_id(),
11604 left_panel.panel_id(),
11605 "Left panel should be the visible panel in the right dock"
11606 );
11607 });
11608 }
11609
11610 #[gpui::test]
11611 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11612 init_test(cx);
11613
11614 let fs = FakeFs::new(cx.executor());
11615
11616 let project = Project::test(fs, None, cx).await;
11617 let (workspace, cx) =
11618 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11619
11620 // Let's arrange the panes like this:
11621 //
11622 // +-----------------------+
11623 // | top |
11624 // +------+--------+-------+
11625 // | left | center | right |
11626 // +------+--------+-------+
11627 // | bottom |
11628 // +-----------------------+
11629
11630 let top_item = cx.new(|cx| {
11631 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11632 });
11633 let bottom_item = cx.new(|cx| {
11634 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11635 });
11636 let left_item = cx.new(|cx| {
11637 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11638 });
11639 let right_item = cx.new(|cx| {
11640 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11641 });
11642 let center_item = cx.new(|cx| {
11643 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11644 });
11645
11646 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11647 let top_pane_id = workspace.active_pane().entity_id();
11648 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11649 workspace.split_pane(
11650 workspace.active_pane().clone(),
11651 SplitDirection::Down,
11652 window,
11653 cx,
11654 );
11655 top_pane_id
11656 });
11657 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11658 let bottom_pane_id = workspace.active_pane().entity_id();
11659 workspace.add_item_to_active_pane(
11660 Box::new(bottom_item.clone()),
11661 None,
11662 false,
11663 window,
11664 cx,
11665 );
11666 workspace.split_pane(
11667 workspace.active_pane().clone(),
11668 SplitDirection::Up,
11669 window,
11670 cx,
11671 );
11672 bottom_pane_id
11673 });
11674 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11675 let left_pane_id = workspace.active_pane().entity_id();
11676 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11677 workspace.split_pane(
11678 workspace.active_pane().clone(),
11679 SplitDirection::Right,
11680 window,
11681 cx,
11682 );
11683 left_pane_id
11684 });
11685 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11686 let right_pane_id = workspace.active_pane().entity_id();
11687 workspace.add_item_to_active_pane(
11688 Box::new(right_item.clone()),
11689 None,
11690 false,
11691 window,
11692 cx,
11693 );
11694 workspace.split_pane(
11695 workspace.active_pane().clone(),
11696 SplitDirection::Left,
11697 window,
11698 cx,
11699 );
11700 right_pane_id
11701 });
11702 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11703 let center_pane_id = workspace.active_pane().entity_id();
11704 workspace.add_item_to_active_pane(
11705 Box::new(center_item.clone()),
11706 None,
11707 false,
11708 window,
11709 cx,
11710 );
11711 center_pane_id
11712 });
11713 cx.executor().run_until_parked();
11714
11715 workspace.update_in(cx, |workspace, window, cx| {
11716 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11717
11718 // Join into next from center pane into right
11719 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11720 });
11721
11722 workspace.update_in(cx, |workspace, window, cx| {
11723 let active_pane = workspace.active_pane();
11724 assert_eq!(right_pane_id, active_pane.entity_id());
11725 assert_eq!(2, active_pane.read(cx).items_len());
11726 let item_ids_in_pane =
11727 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11728 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11729 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11730
11731 // Join into next from right pane into bottom
11732 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11733 });
11734
11735 workspace.update_in(cx, |workspace, window, cx| {
11736 let active_pane = workspace.active_pane();
11737 assert_eq!(bottom_pane_id, active_pane.entity_id());
11738 assert_eq!(3, active_pane.read(cx).items_len());
11739 let item_ids_in_pane =
11740 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11741 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11742 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11743 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11744
11745 // Join into next from bottom pane into left
11746 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11747 });
11748
11749 workspace.update_in(cx, |workspace, window, cx| {
11750 let active_pane = workspace.active_pane();
11751 assert_eq!(left_pane_id, active_pane.entity_id());
11752 assert_eq!(4, active_pane.read(cx).items_len());
11753 let item_ids_in_pane =
11754 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11755 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11756 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11757 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11758 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11759
11760 // Join into next from left pane into top
11761 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11762 });
11763
11764 workspace.update_in(cx, |workspace, window, cx| {
11765 let active_pane = workspace.active_pane();
11766 assert_eq!(top_pane_id, active_pane.entity_id());
11767 assert_eq!(5, active_pane.read(cx).items_len());
11768 let item_ids_in_pane =
11769 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11770 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11771 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11772 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11773 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11774 assert!(item_ids_in_pane.contains(&top_item.item_id()));
11775
11776 // Single pane left: no-op
11777 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11778 });
11779
11780 workspace.update(cx, |workspace, _cx| {
11781 let active_pane = workspace.active_pane();
11782 assert_eq!(top_pane_id, active_pane.entity_id());
11783 });
11784 }
11785
11786 fn add_an_item_to_active_pane(
11787 cx: &mut VisualTestContext,
11788 workspace: &Entity<Workspace>,
11789 item_id: u64,
11790 ) -> Entity<TestItem> {
11791 let item = cx.new(|cx| {
11792 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11793 item_id,
11794 "item{item_id}.txt",
11795 cx,
11796 )])
11797 });
11798 workspace.update_in(cx, |workspace, window, cx| {
11799 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11800 });
11801 item
11802 }
11803
11804 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11805 workspace.update_in(cx, |workspace, window, cx| {
11806 workspace.split_pane(
11807 workspace.active_pane().clone(),
11808 SplitDirection::Right,
11809 window,
11810 cx,
11811 )
11812 })
11813 }
11814
11815 #[gpui::test]
11816 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11817 init_test(cx);
11818 let fs = FakeFs::new(cx.executor());
11819 let project = Project::test(fs, None, cx).await;
11820 let (workspace, cx) =
11821 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11822
11823 add_an_item_to_active_pane(cx, &workspace, 1);
11824 split_pane(cx, &workspace);
11825 add_an_item_to_active_pane(cx, &workspace, 2);
11826 split_pane(cx, &workspace); // empty pane
11827 split_pane(cx, &workspace);
11828 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11829
11830 cx.executor().run_until_parked();
11831
11832 workspace.update(cx, |workspace, cx| {
11833 let num_panes = workspace.panes().len();
11834 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11835 let active_item = workspace
11836 .active_pane()
11837 .read(cx)
11838 .active_item()
11839 .expect("item is in focus");
11840
11841 assert_eq!(num_panes, 4);
11842 assert_eq!(num_items_in_current_pane, 1);
11843 assert_eq!(active_item.item_id(), last_item.item_id());
11844 });
11845
11846 workspace.update_in(cx, |workspace, window, cx| {
11847 workspace.join_all_panes(window, cx);
11848 });
11849
11850 workspace.update(cx, |workspace, cx| {
11851 let num_panes = workspace.panes().len();
11852 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11853 let active_item = workspace
11854 .active_pane()
11855 .read(cx)
11856 .active_item()
11857 .expect("item is in focus");
11858
11859 assert_eq!(num_panes, 1);
11860 assert_eq!(num_items_in_current_pane, 3);
11861 assert_eq!(active_item.item_id(), last_item.item_id());
11862 });
11863 }
11864 struct TestModal(FocusHandle);
11865
11866 impl TestModal {
11867 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11868 Self(cx.focus_handle())
11869 }
11870 }
11871
11872 impl EventEmitter<DismissEvent> for TestModal {}
11873
11874 impl Focusable for TestModal {
11875 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11876 self.0.clone()
11877 }
11878 }
11879
11880 impl ModalView for TestModal {}
11881
11882 impl Render for TestModal {
11883 fn render(
11884 &mut self,
11885 _window: &mut Window,
11886 _cx: &mut Context<TestModal>,
11887 ) -> impl IntoElement {
11888 div().track_focus(&self.0)
11889 }
11890 }
11891
11892 #[gpui::test]
11893 async fn test_panels(cx: &mut gpui::TestAppContext) {
11894 init_test(cx);
11895 let fs = FakeFs::new(cx.executor());
11896
11897 let project = Project::test(fs, [], cx).await;
11898 let (multi_workspace, cx) =
11899 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11900 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11901
11902 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11903 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11904 workspace.add_panel(panel_1.clone(), window, cx);
11905 workspace.toggle_dock(DockPosition::Left, window, cx);
11906 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11907 workspace.add_panel(panel_2.clone(), window, cx);
11908 workspace.toggle_dock(DockPosition::Right, window, cx);
11909
11910 let left_dock = workspace.left_dock();
11911 assert_eq!(
11912 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11913 panel_1.panel_id()
11914 );
11915 assert_eq!(
11916 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11917 panel_1.size(window, cx)
11918 );
11919
11920 left_dock.update(cx, |left_dock, cx| {
11921 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11922 });
11923 assert_eq!(
11924 workspace
11925 .right_dock()
11926 .read(cx)
11927 .visible_panel()
11928 .unwrap()
11929 .panel_id(),
11930 panel_2.panel_id(),
11931 );
11932
11933 (panel_1, panel_2)
11934 });
11935
11936 // Move panel_1 to the right
11937 panel_1.update_in(cx, |panel_1, window, cx| {
11938 panel_1.set_position(DockPosition::Right, window, cx)
11939 });
11940
11941 workspace.update_in(cx, |workspace, window, cx| {
11942 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11943 // Since it was the only panel on the left, the left dock should now be closed.
11944 assert!(!workspace.left_dock().read(cx).is_open());
11945 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11946 let right_dock = workspace.right_dock();
11947 assert_eq!(
11948 right_dock.read(cx).visible_panel().unwrap().panel_id(),
11949 panel_1.panel_id()
11950 );
11951 assert_eq!(
11952 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11953 px(1337.)
11954 );
11955
11956 // Now we move panel_2 to the left
11957 panel_2.set_position(DockPosition::Left, window, cx);
11958 });
11959
11960 workspace.update(cx, |workspace, cx| {
11961 // Since panel_2 was not visible on the right, we don't open the left dock.
11962 assert!(!workspace.left_dock().read(cx).is_open());
11963 // And the right dock is unaffected in its displaying of panel_1
11964 assert!(workspace.right_dock().read(cx).is_open());
11965 assert_eq!(
11966 workspace
11967 .right_dock()
11968 .read(cx)
11969 .visible_panel()
11970 .unwrap()
11971 .panel_id(),
11972 panel_1.panel_id(),
11973 );
11974 });
11975
11976 // Move panel_1 back to the left
11977 panel_1.update_in(cx, |panel_1, window, cx| {
11978 panel_1.set_position(DockPosition::Left, window, cx)
11979 });
11980
11981 workspace.update_in(cx, |workspace, window, cx| {
11982 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11983 let left_dock = workspace.left_dock();
11984 assert!(left_dock.read(cx).is_open());
11985 assert_eq!(
11986 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11987 panel_1.panel_id()
11988 );
11989 assert_eq!(
11990 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11991 px(1337.)
11992 );
11993 // And the right dock should be closed as it no longer has any panels.
11994 assert!(!workspace.right_dock().read(cx).is_open());
11995
11996 // Now we move panel_1 to the bottom
11997 panel_1.set_position(DockPosition::Bottom, window, cx);
11998 });
11999
12000 workspace.update_in(cx, |workspace, window, cx| {
12001 // Since panel_1 was visible on the left, we close the left dock.
12002 assert!(!workspace.left_dock().read(cx).is_open());
12003 // The bottom dock is sized based on the panel's default size,
12004 // since the panel orientation changed from vertical to horizontal.
12005 let bottom_dock = workspace.bottom_dock();
12006 assert_eq!(
12007 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
12008 panel_1.size(window, cx),
12009 );
12010 // Close bottom dock and move panel_1 back to the left.
12011 bottom_dock.update(cx, |bottom_dock, cx| {
12012 bottom_dock.set_open(false, window, cx)
12013 });
12014 panel_1.set_position(DockPosition::Left, window, cx);
12015 });
12016
12017 // Emit activated event on panel 1
12018 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12019
12020 // Now the left dock is open and panel_1 is active and focused.
12021 workspace.update_in(cx, |workspace, window, cx| {
12022 let left_dock = workspace.left_dock();
12023 assert!(left_dock.read(cx).is_open());
12024 assert_eq!(
12025 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12026 panel_1.panel_id(),
12027 );
12028 assert!(panel_1.focus_handle(cx).is_focused(window));
12029 });
12030
12031 // Emit closed event on panel 2, which is not active
12032 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12033
12034 // Wo don't close the left dock, because panel_2 wasn't the active panel
12035 workspace.update(cx, |workspace, cx| {
12036 let left_dock = workspace.left_dock();
12037 assert!(left_dock.read(cx).is_open());
12038 assert_eq!(
12039 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12040 panel_1.panel_id(),
12041 );
12042 });
12043
12044 // Emitting a ZoomIn event shows the panel as zoomed.
12045 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12046 workspace.read_with(cx, |workspace, _| {
12047 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12048 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12049 });
12050
12051 // Move panel to another dock while it is zoomed
12052 panel_1.update_in(cx, |panel, window, cx| {
12053 panel.set_position(DockPosition::Right, window, cx)
12054 });
12055 workspace.read_with(cx, |workspace, _| {
12056 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12057
12058 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12059 });
12060
12061 // This is a helper for getting a:
12062 // - valid focus on an element,
12063 // - that isn't a part of the panes and panels system of the Workspace,
12064 // - and doesn't trigger the 'on_focus_lost' API.
12065 let focus_other_view = {
12066 let workspace = workspace.clone();
12067 move |cx: &mut VisualTestContext| {
12068 workspace.update_in(cx, |workspace, window, cx| {
12069 if workspace.active_modal::<TestModal>(cx).is_some() {
12070 workspace.toggle_modal(window, cx, TestModal::new);
12071 workspace.toggle_modal(window, cx, TestModal::new);
12072 } else {
12073 workspace.toggle_modal(window, cx, TestModal::new);
12074 }
12075 })
12076 }
12077 };
12078
12079 // If focus is transferred to another view that's not a panel or another pane, we still show
12080 // the panel as zoomed.
12081 focus_other_view(cx);
12082 workspace.read_with(cx, |workspace, _| {
12083 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12084 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12085 });
12086
12087 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12088 workspace.update_in(cx, |_workspace, window, cx| {
12089 cx.focus_self(window);
12090 });
12091 workspace.read_with(cx, |workspace, _| {
12092 assert_eq!(workspace.zoomed, None);
12093 assert_eq!(workspace.zoomed_position, None);
12094 });
12095
12096 // If focus is transferred again to another view that's not a panel or a pane, we won't
12097 // show the panel as zoomed because it wasn't zoomed before.
12098 focus_other_view(cx);
12099 workspace.read_with(cx, |workspace, _| {
12100 assert_eq!(workspace.zoomed, None);
12101 assert_eq!(workspace.zoomed_position, None);
12102 });
12103
12104 // When the panel is activated, it is zoomed again.
12105 cx.dispatch_action(ToggleRightDock);
12106 workspace.read_with(cx, |workspace, _| {
12107 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12108 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12109 });
12110
12111 // Emitting a ZoomOut event unzooms the panel.
12112 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12113 workspace.read_with(cx, |workspace, _| {
12114 assert_eq!(workspace.zoomed, None);
12115 assert_eq!(workspace.zoomed_position, None);
12116 });
12117
12118 // Emit closed event on panel 1, which is active
12119 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12120
12121 // Now the left dock is closed, because panel_1 was the active panel
12122 workspace.update(cx, |workspace, cx| {
12123 let right_dock = workspace.right_dock();
12124 assert!(!right_dock.read(cx).is_open());
12125 });
12126 }
12127
12128 #[gpui::test]
12129 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12130 init_test(cx);
12131
12132 let fs = FakeFs::new(cx.background_executor.clone());
12133 let project = Project::test(fs, [], cx).await;
12134 let (workspace, cx) =
12135 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12136 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12137
12138 let dirty_regular_buffer = cx.new(|cx| {
12139 TestItem::new(cx)
12140 .with_dirty(true)
12141 .with_label("1.txt")
12142 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12143 });
12144 let dirty_regular_buffer_2 = cx.new(|cx| {
12145 TestItem::new(cx)
12146 .with_dirty(true)
12147 .with_label("2.txt")
12148 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12149 });
12150 let dirty_multi_buffer_with_both = cx.new(|cx| {
12151 TestItem::new(cx)
12152 .with_dirty(true)
12153 .with_buffer_kind(ItemBufferKind::Multibuffer)
12154 .with_label("Fake Project Search")
12155 .with_project_items(&[
12156 dirty_regular_buffer.read(cx).project_items[0].clone(),
12157 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12158 ])
12159 });
12160 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12161 workspace.update_in(cx, |workspace, window, cx| {
12162 workspace.add_item(
12163 pane.clone(),
12164 Box::new(dirty_regular_buffer.clone()),
12165 None,
12166 false,
12167 false,
12168 window,
12169 cx,
12170 );
12171 workspace.add_item(
12172 pane.clone(),
12173 Box::new(dirty_regular_buffer_2.clone()),
12174 None,
12175 false,
12176 false,
12177 window,
12178 cx,
12179 );
12180 workspace.add_item(
12181 pane.clone(),
12182 Box::new(dirty_multi_buffer_with_both.clone()),
12183 None,
12184 false,
12185 false,
12186 window,
12187 cx,
12188 );
12189 });
12190
12191 pane.update_in(cx, |pane, window, cx| {
12192 pane.activate_item(2, true, true, window, cx);
12193 assert_eq!(
12194 pane.active_item().unwrap().item_id(),
12195 multi_buffer_with_both_files_id,
12196 "Should select the multi buffer in the pane"
12197 );
12198 });
12199 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12200 pane.close_other_items(
12201 &CloseOtherItems {
12202 save_intent: Some(SaveIntent::Save),
12203 close_pinned: true,
12204 },
12205 None,
12206 window,
12207 cx,
12208 )
12209 });
12210 cx.background_executor.run_until_parked();
12211 assert!(!cx.has_pending_prompt());
12212 close_all_but_multi_buffer_task
12213 .await
12214 .expect("Closing all buffers but the multi buffer failed");
12215 pane.update(cx, |pane, cx| {
12216 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12217 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12218 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12219 assert_eq!(pane.items_len(), 1);
12220 assert_eq!(
12221 pane.active_item().unwrap().item_id(),
12222 multi_buffer_with_both_files_id,
12223 "Should have only the multi buffer left in the pane"
12224 );
12225 assert!(
12226 dirty_multi_buffer_with_both.read(cx).is_dirty,
12227 "The multi buffer containing the unsaved buffer should still be dirty"
12228 );
12229 });
12230
12231 dirty_regular_buffer.update(cx, |buffer, cx| {
12232 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12233 });
12234
12235 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12236 pane.close_active_item(
12237 &CloseActiveItem {
12238 save_intent: Some(SaveIntent::Close),
12239 close_pinned: false,
12240 },
12241 window,
12242 cx,
12243 )
12244 });
12245 cx.background_executor.run_until_parked();
12246 assert!(
12247 cx.has_pending_prompt(),
12248 "Dirty multi buffer should prompt a save dialog"
12249 );
12250 cx.simulate_prompt_answer("Save");
12251 cx.background_executor.run_until_parked();
12252 close_multi_buffer_task
12253 .await
12254 .expect("Closing the multi buffer failed");
12255 pane.update(cx, |pane, cx| {
12256 assert_eq!(
12257 dirty_multi_buffer_with_both.read(cx).save_count,
12258 1,
12259 "Multi buffer item should get be saved"
12260 );
12261 // Test impl does not save inner items, so we do not assert them
12262 assert_eq!(
12263 pane.items_len(),
12264 0,
12265 "No more items should be left in the pane"
12266 );
12267 assert!(pane.active_item().is_none());
12268 });
12269 }
12270
12271 #[gpui::test]
12272 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
12273 cx: &mut TestAppContext,
12274 ) {
12275 init_test(cx);
12276
12277 let fs = FakeFs::new(cx.background_executor.clone());
12278 let project = Project::test(fs, [], cx).await;
12279 let (workspace, cx) =
12280 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12281 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12282
12283 let dirty_regular_buffer = cx.new(|cx| {
12284 TestItem::new(cx)
12285 .with_dirty(true)
12286 .with_label("1.txt")
12287 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12288 });
12289 let dirty_regular_buffer_2 = cx.new(|cx| {
12290 TestItem::new(cx)
12291 .with_dirty(true)
12292 .with_label("2.txt")
12293 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12294 });
12295 let clear_regular_buffer = cx.new(|cx| {
12296 TestItem::new(cx)
12297 .with_label("3.txt")
12298 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12299 });
12300
12301 let dirty_multi_buffer_with_both = cx.new(|cx| {
12302 TestItem::new(cx)
12303 .with_dirty(true)
12304 .with_buffer_kind(ItemBufferKind::Multibuffer)
12305 .with_label("Fake Project Search")
12306 .with_project_items(&[
12307 dirty_regular_buffer.read(cx).project_items[0].clone(),
12308 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12309 clear_regular_buffer.read(cx).project_items[0].clone(),
12310 ])
12311 });
12312 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12313 workspace.update_in(cx, |workspace, window, cx| {
12314 workspace.add_item(
12315 pane.clone(),
12316 Box::new(dirty_regular_buffer.clone()),
12317 None,
12318 false,
12319 false,
12320 window,
12321 cx,
12322 );
12323 workspace.add_item(
12324 pane.clone(),
12325 Box::new(dirty_multi_buffer_with_both.clone()),
12326 None,
12327 false,
12328 false,
12329 window,
12330 cx,
12331 );
12332 });
12333
12334 pane.update_in(cx, |pane, window, cx| {
12335 pane.activate_item(1, true, true, window, cx);
12336 assert_eq!(
12337 pane.active_item().unwrap().item_id(),
12338 multi_buffer_with_both_files_id,
12339 "Should select the multi buffer in the pane"
12340 );
12341 });
12342 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12343 pane.close_active_item(
12344 &CloseActiveItem {
12345 save_intent: None,
12346 close_pinned: false,
12347 },
12348 window,
12349 cx,
12350 )
12351 });
12352 cx.background_executor.run_until_parked();
12353 assert!(
12354 cx.has_pending_prompt(),
12355 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
12356 );
12357 }
12358
12359 /// Tests that when `close_on_file_delete` is enabled, files are automatically
12360 /// closed when they are deleted from disk.
12361 #[gpui::test]
12362 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
12363 init_test(cx);
12364
12365 // Enable the close_on_disk_deletion setting
12366 cx.update_global(|store: &mut SettingsStore, cx| {
12367 store.update_user_settings(cx, |settings| {
12368 settings.workspace.close_on_file_delete = Some(true);
12369 });
12370 });
12371
12372 let fs = FakeFs::new(cx.background_executor.clone());
12373 let project = Project::test(fs, [], cx).await;
12374 let (workspace, cx) =
12375 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12376 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12377
12378 // Create a test item that simulates a file
12379 let item = cx.new(|cx| {
12380 TestItem::new(cx)
12381 .with_label("test.txt")
12382 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12383 });
12384
12385 // Add item to workspace
12386 workspace.update_in(cx, |workspace, window, cx| {
12387 workspace.add_item(
12388 pane.clone(),
12389 Box::new(item.clone()),
12390 None,
12391 false,
12392 false,
12393 window,
12394 cx,
12395 );
12396 });
12397
12398 // Verify the item is in the pane
12399 pane.read_with(cx, |pane, _| {
12400 assert_eq!(pane.items().count(), 1);
12401 });
12402
12403 // Simulate file deletion by setting the item's deleted state
12404 item.update(cx, |item, _| {
12405 item.set_has_deleted_file(true);
12406 });
12407
12408 // Emit UpdateTab event to trigger the close behavior
12409 cx.run_until_parked();
12410 item.update(cx, |_, cx| {
12411 cx.emit(ItemEvent::UpdateTab);
12412 });
12413
12414 // Allow the close operation to complete
12415 cx.run_until_parked();
12416
12417 // Verify the item was automatically closed
12418 pane.read_with(cx, |pane, _| {
12419 assert_eq!(
12420 pane.items().count(),
12421 0,
12422 "Item should be automatically closed when file is deleted"
12423 );
12424 });
12425 }
12426
12427 /// Tests that when `close_on_file_delete` is disabled (default), files remain
12428 /// open with a strikethrough when they are deleted from disk.
12429 #[gpui::test]
12430 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12431 init_test(cx);
12432
12433 // Ensure close_on_disk_deletion is disabled (default)
12434 cx.update_global(|store: &mut SettingsStore, cx| {
12435 store.update_user_settings(cx, |settings| {
12436 settings.workspace.close_on_file_delete = Some(false);
12437 });
12438 });
12439
12440 let fs = FakeFs::new(cx.background_executor.clone());
12441 let project = Project::test(fs, [], cx).await;
12442 let (workspace, cx) =
12443 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12444 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12445
12446 // Create a test item that simulates a file
12447 let item = cx.new(|cx| {
12448 TestItem::new(cx)
12449 .with_label("test.txt")
12450 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12451 });
12452
12453 // Add item to workspace
12454 workspace.update_in(cx, |workspace, window, cx| {
12455 workspace.add_item(
12456 pane.clone(),
12457 Box::new(item.clone()),
12458 None,
12459 false,
12460 false,
12461 window,
12462 cx,
12463 );
12464 });
12465
12466 // Verify the item is in the pane
12467 pane.read_with(cx, |pane, _| {
12468 assert_eq!(pane.items().count(), 1);
12469 });
12470
12471 // Simulate file deletion
12472 item.update(cx, |item, _| {
12473 item.set_has_deleted_file(true);
12474 });
12475
12476 // Emit UpdateTab event
12477 cx.run_until_parked();
12478 item.update(cx, |_, cx| {
12479 cx.emit(ItemEvent::UpdateTab);
12480 });
12481
12482 // Allow any potential close operation to complete
12483 cx.run_until_parked();
12484
12485 // Verify the item remains open (with strikethrough)
12486 pane.read_with(cx, |pane, _| {
12487 assert_eq!(
12488 pane.items().count(),
12489 1,
12490 "Item should remain open when close_on_disk_deletion is disabled"
12491 );
12492 });
12493
12494 // Verify the item shows as deleted
12495 item.read_with(cx, |item, _| {
12496 assert!(
12497 item.has_deleted_file,
12498 "Item should be marked as having deleted file"
12499 );
12500 });
12501 }
12502
12503 /// Tests that dirty files are not automatically closed when deleted from disk,
12504 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12505 /// unsaved changes without being prompted.
12506 #[gpui::test]
12507 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12508 init_test(cx);
12509
12510 // Enable the close_on_file_delete setting
12511 cx.update_global(|store: &mut SettingsStore, cx| {
12512 store.update_user_settings(cx, |settings| {
12513 settings.workspace.close_on_file_delete = Some(true);
12514 });
12515 });
12516
12517 let fs = FakeFs::new(cx.background_executor.clone());
12518 let project = Project::test(fs, [], cx).await;
12519 let (workspace, cx) =
12520 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12521 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12522
12523 // Create a dirty test item
12524 let item = cx.new(|cx| {
12525 TestItem::new(cx)
12526 .with_dirty(true)
12527 .with_label("test.txt")
12528 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12529 });
12530
12531 // Add item to workspace
12532 workspace.update_in(cx, |workspace, window, cx| {
12533 workspace.add_item(
12534 pane.clone(),
12535 Box::new(item.clone()),
12536 None,
12537 false,
12538 false,
12539 window,
12540 cx,
12541 );
12542 });
12543
12544 // Simulate file deletion
12545 item.update(cx, |item, _| {
12546 item.set_has_deleted_file(true);
12547 });
12548
12549 // Emit UpdateTab event to trigger the close behavior
12550 cx.run_until_parked();
12551 item.update(cx, |_, cx| {
12552 cx.emit(ItemEvent::UpdateTab);
12553 });
12554
12555 // Allow any potential close operation to complete
12556 cx.run_until_parked();
12557
12558 // Verify the item remains open (dirty files are not auto-closed)
12559 pane.read_with(cx, |pane, _| {
12560 assert_eq!(
12561 pane.items().count(),
12562 1,
12563 "Dirty items should not be automatically closed even when file is deleted"
12564 );
12565 });
12566
12567 // Verify the item is marked as deleted and still dirty
12568 item.read_with(cx, |item, _| {
12569 assert!(
12570 item.has_deleted_file,
12571 "Item should be marked as having deleted file"
12572 );
12573 assert!(item.is_dirty, "Item should still be dirty");
12574 });
12575 }
12576
12577 /// Tests that navigation history is cleaned up when files are auto-closed
12578 /// due to deletion from disk.
12579 #[gpui::test]
12580 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12581 init_test(cx);
12582
12583 // Enable the close_on_file_delete setting
12584 cx.update_global(|store: &mut SettingsStore, cx| {
12585 store.update_user_settings(cx, |settings| {
12586 settings.workspace.close_on_file_delete = Some(true);
12587 });
12588 });
12589
12590 let fs = FakeFs::new(cx.background_executor.clone());
12591 let project = Project::test(fs, [], cx).await;
12592 let (workspace, cx) =
12593 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12594 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12595
12596 // Create test items
12597 let item1 = cx.new(|cx| {
12598 TestItem::new(cx)
12599 .with_label("test1.txt")
12600 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12601 });
12602 let item1_id = item1.item_id();
12603
12604 let item2 = cx.new(|cx| {
12605 TestItem::new(cx)
12606 .with_label("test2.txt")
12607 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12608 });
12609
12610 // Add items to workspace
12611 workspace.update_in(cx, |workspace, window, cx| {
12612 workspace.add_item(
12613 pane.clone(),
12614 Box::new(item1.clone()),
12615 None,
12616 false,
12617 false,
12618 window,
12619 cx,
12620 );
12621 workspace.add_item(
12622 pane.clone(),
12623 Box::new(item2.clone()),
12624 None,
12625 false,
12626 false,
12627 window,
12628 cx,
12629 );
12630 });
12631
12632 // Activate item1 to ensure it gets navigation entries
12633 pane.update_in(cx, |pane, window, cx| {
12634 pane.activate_item(0, true, true, window, cx);
12635 });
12636
12637 // Switch to item2 and back to create navigation history
12638 pane.update_in(cx, |pane, window, cx| {
12639 pane.activate_item(1, true, true, window, cx);
12640 });
12641 cx.run_until_parked();
12642
12643 pane.update_in(cx, |pane, window, cx| {
12644 pane.activate_item(0, true, true, window, cx);
12645 });
12646 cx.run_until_parked();
12647
12648 // Simulate file deletion for item1
12649 item1.update(cx, |item, _| {
12650 item.set_has_deleted_file(true);
12651 });
12652
12653 // Emit UpdateTab event to trigger the close behavior
12654 item1.update(cx, |_, cx| {
12655 cx.emit(ItemEvent::UpdateTab);
12656 });
12657 cx.run_until_parked();
12658
12659 // Verify item1 was closed
12660 pane.read_with(cx, |pane, _| {
12661 assert_eq!(
12662 pane.items().count(),
12663 1,
12664 "Should have 1 item remaining after auto-close"
12665 );
12666 });
12667
12668 // Check navigation history after close
12669 let has_item = pane.read_with(cx, |pane, cx| {
12670 let mut has_item = false;
12671 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12672 if entry.item.id() == item1_id {
12673 has_item = true;
12674 }
12675 });
12676 has_item
12677 });
12678
12679 assert!(
12680 !has_item,
12681 "Navigation history should not contain closed item entries"
12682 );
12683 }
12684
12685 #[gpui::test]
12686 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12687 cx: &mut TestAppContext,
12688 ) {
12689 init_test(cx);
12690
12691 let fs = FakeFs::new(cx.background_executor.clone());
12692 let project = Project::test(fs, [], cx).await;
12693 let (workspace, cx) =
12694 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12695 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12696
12697 let dirty_regular_buffer = cx.new(|cx| {
12698 TestItem::new(cx)
12699 .with_dirty(true)
12700 .with_label("1.txt")
12701 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12702 });
12703 let dirty_regular_buffer_2 = cx.new(|cx| {
12704 TestItem::new(cx)
12705 .with_dirty(true)
12706 .with_label("2.txt")
12707 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12708 });
12709 let clear_regular_buffer = cx.new(|cx| {
12710 TestItem::new(cx)
12711 .with_label("3.txt")
12712 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12713 });
12714
12715 let dirty_multi_buffer = cx.new(|cx| {
12716 TestItem::new(cx)
12717 .with_dirty(true)
12718 .with_buffer_kind(ItemBufferKind::Multibuffer)
12719 .with_label("Fake Project Search")
12720 .with_project_items(&[
12721 dirty_regular_buffer.read(cx).project_items[0].clone(),
12722 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12723 clear_regular_buffer.read(cx).project_items[0].clone(),
12724 ])
12725 });
12726 workspace.update_in(cx, |workspace, window, cx| {
12727 workspace.add_item(
12728 pane.clone(),
12729 Box::new(dirty_regular_buffer.clone()),
12730 None,
12731 false,
12732 false,
12733 window,
12734 cx,
12735 );
12736 workspace.add_item(
12737 pane.clone(),
12738 Box::new(dirty_regular_buffer_2.clone()),
12739 None,
12740 false,
12741 false,
12742 window,
12743 cx,
12744 );
12745 workspace.add_item(
12746 pane.clone(),
12747 Box::new(dirty_multi_buffer.clone()),
12748 None,
12749 false,
12750 false,
12751 window,
12752 cx,
12753 );
12754 });
12755
12756 pane.update_in(cx, |pane, window, cx| {
12757 pane.activate_item(2, true, true, window, cx);
12758 assert_eq!(
12759 pane.active_item().unwrap().item_id(),
12760 dirty_multi_buffer.item_id(),
12761 "Should select the multi buffer in the pane"
12762 );
12763 });
12764 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12765 pane.close_active_item(
12766 &CloseActiveItem {
12767 save_intent: None,
12768 close_pinned: false,
12769 },
12770 window,
12771 cx,
12772 )
12773 });
12774 cx.background_executor.run_until_parked();
12775 assert!(
12776 !cx.has_pending_prompt(),
12777 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12778 );
12779 close_multi_buffer_task
12780 .await
12781 .expect("Closing multi buffer failed");
12782 pane.update(cx, |pane, cx| {
12783 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12784 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12785 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12786 assert_eq!(
12787 pane.items()
12788 .map(|item| item.item_id())
12789 .sorted()
12790 .collect::<Vec<_>>(),
12791 vec![
12792 dirty_regular_buffer.item_id(),
12793 dirty_regular_buffer_2.item_id(),
12794 ],
12795 "Should have no multi buffer left in the pane"
12796 );
12797 assert!(dirty_regular_buffer.read(cx).is_dirty);
12798 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12799 });
12800 }
12801
12802 #[gpui::test]
12803 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12804 init_test(cx);
12805 let fs = FakeFs::new(cx.executor());
12806 let project = Project::test(fs, [], cx).await;
12807 let (multi_workspace, cx) =
12808 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12809 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12810
12811 // Add a new panel to the right dock, opening the dock and setting the
12812 // focus to the new panel.
12813 let panel = workspace.update_in(cx, |workspace, window, cx| {
12814 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12815 workspace.add_panel(panel.clone(), window, cx);
12816
12817 workspace
12818 .right_dock()
12819 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12820
12821 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12822
12823 panel
12824 });
12825
12826 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12827 // panel to the next valid position which, in this case, is the left
12828 // dock.
12829 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12830 workspace.update(cx, |workspace, cx| {
12831 assert!(workspace.left_dock().read(cx).is_open());
12832 assert_eq!(panel.read(cx).position, DockPosition::Left);
12833 });
12834
12835 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12836 // panel to the next valid position which, in this case, is the bottom
12837 // dock.
12838 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12839 workspace.update(cx, |workspace, cx| {
12840 assert!(workspace.bottom_dock().read(cx).is_open());
12841 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12842 });
12843
12844 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12845 // around moving the panel to its initial position, the right dock.
12846 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12847 workspace.update(cx, |workspace, cx| {
12848 assert!(workspace.right_dock().read(cx).is_open());
12849 assert_eq!(panel.read(cx).position, DockPosition::Right);
12850 });
12851
12852 // Remove focus from the panel, ensuring that, if the panel is not
12853 // focused, the `MoveFocusedPanelToNextPosition` action does not update
12854 // the panel's position, so the panel is still in the right dock.
12855 workspace.update_in(cx, |workspace, window, cx| {
12856 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12857 });
12858
12859 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12860 workspace.update(cx, |workspace, cx| {
12861 assert!(workspace.right_dock().read(cx).is_open());
12862 assert_eq!(panel.read(cx).position, DockPosition::Right);
12863 });
12864 }
12865
12866 #[gpui::test]
12867 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12868 init_test(cx);
12869
12870 let fs = FakeFs::new(cx.executor());
12871 let project = Project::test(fs, [], cx).await;
12872 let (workspace, cx) =
12873 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12874
12875 let item_1 = cx.new(|cx| {
12876 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12877 });
12878 workspace.update_in(cx, |workspace, window, cx| {
12879 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12880 workspace.move_item_to_pane_in_direction(
12881 &MoveItemToPaneInDirection {
12882 direction: SplitDirection::Right,
12883 focus: true,
12884 clone: false,
12885 },
12886 window,
12887 cx,
12888 );
12889 workspace.move_item_to_pane_at_index(
12890 &MoveItemToPane {
12891 destination: 3,
12892 focus: true,
12893 clone: false,
12894 },
12895 window,
12896 cx,
12897 );
12898
12899 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12900 assert_eq!(
12901 pane_items_paths(&workspace.active_pane, cx),
12902 vec!["first.txt".to_string()],
12903 "Single item was not moved anywhere"
12904 );
12905 });
12906
12907 let item_2 = cx.new(|cx| {
12908 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12909 });
12910 workspace.update_in(cx, |workspace, window, cx| {
12911 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12912 assert_eq!(
12913 pane_items_paths(&workspace.panes[0], cx),
12914 vec!["first.txt".to_string(), "second.txt".to_string()],
12915 );
12916 workspace.move_item_to_pane_in_direction(
12917 &MoveItemToPaneInDirection {
12918 direction: SplitDirection::Right,
12919 focus: true,
12920 clone: false,
12921 },
12922 window,
12923 cx,
12924 );
12925
12926 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12927 assert_eq!(
12928 pane_items_paths(&workspace.panes[0], cx),
12929 vec!["first.txt".to_string()],
12930 "After moving, one item should be left in the original pane"
12931 );
12932 assert_eq!(
12933 pane_items_paths(&workspace.panes[1], cx),
12934 vec!["second.txt".to_string()],
12935 "New item should have been moved to the new pane"
12936 );
12937 });
12938
12939 let item_3 = cx.new(|cx| {
12940 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12941 });
12942 workspace.update_in(cx, |workspace, window, cx| {
12943 let original_pane = workspace.panes[0].clone();
12944 workspace.set_active_pane(&original_pane, window, cx);
12945 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12946 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12947 assert_eq!(
12948 pane_items_paths(&workspace.active_pane, cx),
12949 vec!["first.txt".to_string(), "third.txt".to_string()],
12950 "New pane should be ready to move one item out"
12951 );
12952
12953 workspace.move_item_to_pane_at_index(
12954 &MoveItemToPane {
12955 destination: 3,
12956 focus: true,
12957 clone: false,
12958 },
12959 window,
12960 cx,
12961 );
12962 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12963 assert_eq!(
12964 pane_items_paths(&workspace.active_pane, cx),
12965 vec!["first.txt".to_string()],
12966 "After moving, one item should be left in the original pane"
12967 );
12968 assert_eq!(
12969 pane_items_paths(&workspace.panes[1], cx),
12970 vec!["second.txt".to_string()],
12971 "Previously created pane should be unchanged"
12972 );
12973 assert_eq!(
12974 pane_items_paths(&workspace.panes[2], cx),
12975 vec!["third.txt".to_string()],
12976 "New item should have been moved to the new pane"
12977 );
12978 });
12979 }
12980
12981 #[gpui::test]
12982 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12983 init_test(cx);
12984
12985 let fs = FakeFs::new(cx.executor());
12986 let project = Project::test(fs, [], cx).await;
12987 let (workspace, cx) =
12988 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12989
12990 let item_1 = cx.new(|cx| {
12991 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12992 });
12993 workspace.update_in(cx, |workspace, window, cx| {
12994 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12995 workspace.move_item_to_pane_in_direction(
12996 &MoveItemToPaneInDirection {
12997 direction: SplitDirection::Right,
12998 focus: true,
12999 clone: true,
13000 },
13001 window,
13002 cx,
13003 );
13004 });
13005 cx.run_until_parked();
13006 workspace.update_in(cx, |workspace, window, cx| {
13007 workspace.move_item_to_pane_at_index(
13008 &MoveItemToPane {
13009 destination: 3,
13010 focus: true,
13011 clone: true,
13012 },
13013 window,
13014 cx,
13015 );
13016 });
13017 cx.run_until_parked();
13018
13019 workspace.update(cx, |workspace, cx| {
13020 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13021 for pane in workspace.panes() {
13022 assert_eq!(
13023 pane_items_paths(pane, cx),
13024 vec!["first.txt".to_string()],
13025 "Single item exists in all panes"
13026 );
13027 }
13028 });
13029
13030 // verify that the active pane has been updated after waiting for the
13031 // pane focus event to fire and resolve
13032 workspace.read_with(cx, |workspace, _app| {
13033 assert_eq!(
13034 workspace.active_pane(),
13035 &workspace.panes[2],
13036 "The third pane should be the active one: {:?}",
13037 workspace.panes
13038 );
13039 })
13040 }
13041
13042 #[gpui::test]
13043 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13044 init_test(cx);
13045
13046 let fs = FakeFs::new(cx.executor());
13047 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13048
13049 let project = Project::test(fs, ["root".as_ref()], cx).await;
13050 let (workspace, cx) =
13051 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13052
13053 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13054 // Add item to pane A with project path
13055 let item_a = cx.new(|cx| {
13056 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13057 });
13058 workspace.update_in(cx, |workspace, window, cx| {
13059 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13060 });
13061
13062 // Split to create pane B
13063 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13064 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13065 });
13066
13067 // Add item with SAME project path to pane B, and pin it
13068 let item_b = cx.new(|cx| {
13069 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13070 });
13071 pane_b.update_in(cx, |pane, window, cx| {
13072 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13073 pane.set_pinned_count(1);
13074 });
13075
13076 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13077 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13078
13079 // close_pinned: false should only close the unpinned copy
13080 workspace.update_in(cx, |workspace, window, cx| {
13081 workspace.close_item_in_all_panes(
13082 &CloseItemInAllPanes {
13083 save_intent: Some(SaveIntent::Close),
13084 close_pinned: false,
13085 },
13086 window,
13087 cx,
13088 )
13089 });
13090 cx.executor().run_until_parked();
13091
13092 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13093 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13094 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13095 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13096
13097 // Split again, seeing as closing the previous item also closed its
13098 // pane, so only pane remains, which does not allow us to properly test
13099 // that both items close when `close_pinned: true`.
13100 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13101 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13102 });
13103
13104 // Add an item with the same project path to pane C so that
13105 // close_item_in_all_panes can determine what to close across all panes
13106 // (it reads the active item from the active pane, and split_pane
13107 // creates an empty pane).
13108 let item_c = cx.new(|cx| {
13109 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13110 });
13111 pane_c.update_in(cx, |pane, window, cx| {
13112 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13113 });
13114
13115 // close_pinned: true should close the pinned copy too
13116 workspace.update_in(cx, |workspace, window, cx| {
13117 let panes_count = workspace.panes().len();
13118 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13119
13120 workspace.close_item_in_all_panes(
13121 &CloseItemInAllPanes {
13122 save_intent: Some(SaveIntent::Close),
13123 close_pinned: true,
13124 },
13125 window,
13126 cx,
13127 )
13128 });
13129 cx.executor().run_until_parked();
13130
13131 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13132 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13133 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13134 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13135 }
13136
13137 mod register_project_item_tests {
13138
13139 use super::*;
13140
13141 // View
13142 struct TestPngItemView {
13143 focus_handle: FocusHandle,
13144 }
13145 // Model
13146 struct TestPngItem {}
13147
13148 impl project::ProjectItem for TestPngItem {
13149 fn try_open(
13150 _project: &Entity<Project>,
13151 path: &ProjectPath,
13152 cx: &mut App,
13153 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13154 if path.path.extension().unwrap() == "png" {
13155 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13156 } else {
13157 None
13158 }
13159 }
13160
13161 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13162 None
13163 }
13164
13165 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13166 None
13167 }
13168
13169 fn is_dirty(&self) -> bool {
13170 false
13171 }
13172 }
13173
13174 impl Item for TestPngItemView {
13175 type Event = ();
13176 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13177 "".into()
13178 }
13179 }
13180 impl EventEmitter<()> for TestPngItemView {}
13181 impl Focusable for TestPngItemView {
13182 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13183 self.focus_handle.clone()
13184 }
13185 }
13186
13187 impl Render for TestPngItemView {
13188 fn render(
13189 &mut self,
13190 _window: &mut Window,
13191 _cx: &mut Context<Self>,
13192 ) -> impl IntoElement {
13193 Empty
13194 }
13195 }
13196
13197 impl ProjectItem for TestPngItemView {
13198 type Item = TestPngItem;
13199
13200 fn for_project_item(
13201 _project: Entity<Project>,
13202 _pane: Option<&Pane>,
13203 _item: Entity<Self::Item>,
13204 _: &mut Window,
13205 cx: &mut Context<Self>,
13206 ) -> Self
13207 where
13208 Self: Sized,
13209 {
13210 Self {
13211 focus_handle: cx.focus_handle(),
13212 }
13213 }
13214 }
13215
13216 // View
13217 struct TestIpynbItemView {
13218 focus_handle: FocusHandle,
13219 }
13220 // Model
13221 struct TestIpynbItem {}
13222
13223 impl project::ProjectItem for TestIpynbItem {
13224 fn try_open(
13225 _project: &Entity<Project>,
13226 path: &ProjectPath,
13227 cx: &mut App,
13228 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13229 if path.path.extension().unwrap() == "ipynb" {
13230 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13231 } else {
13232 None
13233 }
13234 }
13235
13236 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13237 None
13238 }
13239
13240 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13241 None
13242 }
13243
13244 fn is_dirty(&self) -> bool {
13245 false
13246 }
13247 }
13248
13249 impl Item for TestIpynbItemView {
13250 type Event = ();
13251 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13252 "".into()
13253 }
13254 }
13255 impl EventEmitter<()> for TestIpynbItemView {}
13256 impl Focusable for TestIpynbItemView {
13257 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13258 self.focus_handle.clone()
13259 }
13260 }
13261
13262 impl Render for TestIpynbItemView {
13263 fn render(
13264 &mut self,
13265 _window: &mut Window,
13266 _cx: &mut Context<Self>,
13267 ) -> impl IntoElement {
13268 Empty
13269 }
13270 }
13271
13272 impl ProjectItem for TestIpynbItemView {
13273 type Item = TestIpynbItem;
13274
13275 fn for_project_item(
13276 _project: Entity<Project>,
13277 _pane: Option<&Pane>,
13278 _item: Entity<Self::Item>,
13279 _: &mut Window,
13280 cx: &mut Context<Self>,
13281 ) -> Self
13282 where
13283 Self: Sized,
13284 {
13285 Self {
13286 focus_handle: cx.focus_handle(),
13287 }
13288 }
13289 }
13290
13291 struct TestAlternatePngItemView {
13292 focus_handle: FocusHandle,
13293 }
13294
13295 impl Item for TestAlternatePngItemView {
13296 type Event = ();
13297 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13298 "".into()
13299 }
13300 }
13301
13302 impl EventEmitter<()> for TestAlternatePngItemView {}
13303 impl Focusable for TestAlternatePngItemView {
13304 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13305 self.focus_handle.clone()
13306 }
13307 }
13308
13309 impl Render for TestAlternatePngItemView {
13310 fn render(
13311 &mut self,
13312 _window: &mut Window,
13313 _cx: &mut Context<Self>,
13314 ) -> impl IntoElement {
13315 Empty
13316 }
13317 }
13318
13319 impl ProjectItem for TestAlternatePngItemView {
13320 type Item = TestPngItem;
13321
13322 fn for_project_item(
13323 _project: Entity<Project>,
13324 _pane: Option<&Pane>,
13325 _item: Entity<Self::Item>,
13326 _: &mut Window,
13327 cx: &mut Context<Self>,
13328 ) -> Self
13329 where
13330 Self: Sized,
13331 {
13332 Self {
13333 focus_handle: cx.focus_handle(),
13334 }
13335 }
13336 }
13337
13338 #[gpui::test]
13339 async fn test_register_project_item(cx: &mut TestAppContext) {
13340 init_test(cx);
13341
13342 cx.update(|cx| {
13343 register_project_item::<TestPngItemView>(cx);
13344 register_project_item::<TestIpynbItemView>(cx);
13345 });
13346
13347 let fs = FakeFs::new(cx.executor());
13348 fs.insert_tree(
13349 "/root1",
13350 json!({
13351 "one.png": "BINARYDATAHERE",
13352 "two.ipynb": "{ totally a notebook }",
13353 "three.txt": "editing text, sure why not?"
13354 }),
13355 )
13356 .await;
13357
13358 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13359 let (workspace, cx) =
13360 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13361
13362 let worktree_id = project.update(cx, |project, cx| {
13363 project.worktrees(cx).next().unwrap().read(cx).id()
13364 });
13365
13366 let handle = workspace
13367 .update_in(cx, |workspace, window, cx| {
13368 let project_path = (worktree_id, rel_path("one.png"));
13369 workspace.open_path(project_path, None, true, window, cx)
13370 })
13371 .await
13372 .unwrap();
13373
13374 // Now we can check if the handle we got back errored or not
13375 assert_eq!(
13376 handle.to_any_view().entity_type(),
13377 TypeId::of::<TestPngItemView>()
13378 );
13379
13380 let handle = workspace
13381 .update_in(cx, |workspace, window, cx| {
13382 let project_path = (worktree_id, rel_path("two.ipynb"));
13383 workspace.open_path(project_path, None, true, window, cx)
13384 })
13385 .await
13386 .unwrap();
13387
13388 assert_eq!(
13389 handle.to_any_view().entity_type(),
13390 TypeId::of::<TestIpynbItemView>()
13391 );
13392
13393 let handle = workspace
13394 .update_in(cx, |workspace, window, cx| {
13395 let project_path = (worktree_id, rel_path("three.txt"));
13396 workspace.open_path(project_path, None, true, window, cx)
13397 })
13398 .await;
13399 assert!(handle.is_err());
13400 }
13401
13402 #[gpui::test]
13403 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
13404 init_test(cx);
13405
13406 cx.update(|cx| {
13407 register_project_item::<TestPngItemView>(cx);
13408 register_project_item::<TestAlternatePngItemView>(cx);
13409 });
13410
13411 let fs = FakeFs::new(cx.executor());
13412 fs.insert_tree(
13413 "/root1",
13414 json!({
13415 "one.png": "BINARYDATAHERE",
13416 "two.ipynb": "{ totally a notebook }",
13417 "three.txt": "editing text, sure why not?"
13418 }),
13419 )
13420 .await;
13421 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13422 let (workspace, cx) =
13423 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13424 let worktree_id = project.update(cx, |project, cx| {
13425 project.worktrees(cx).next().unwrap().read(cx).id()
13426 });
13427
13428 let handle = workspace
13429 .update_in(cx, |workspace, window, cx| {
13430 let project_path = (worktree_id, rel_path("one.png"));
13431 workspace.open_path(project_path, None, true, window, cx)
13432 })
13433 .await
13434 .unwrap();
13435
13436 // This _must_ be the second item registered
13437 assert_eq!(
13438 handle.to_any_view().entity_type(),
13439 TypeId::of::<TestAlternatePngItemView>()
13440 );
13441
13442 let handle = workspace
13443 .update_in(cx, |workspace, window, cx| {
13444 let project_path = (worktree_id, rel_path("three.txt"));
13445 workspace.open_path(project_path, None, true, window, cx)
13446 })
13447 .await;
13448 assert!(handle.is_err());
13449 }
13450 }
13451
13452 #[gpui::test]
13453 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13454 init_test(cx);
13455
13456 let fs = FakeFs::new(cx.executor());
13457 let project = Project::test(fs, [], cx).await;
13458 let (workspace, _cx) =
13459 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13460
13461 // Test with status bar shown (default)
13462 workspace.read_with(cx, |workspace, cx| {
13463 let visible = workspace.status_bar_visible(cx);
13464 assert!(visible, "Status bar should be visible by default");
13465 });
13466
13467 // Test with status bar hidden
13468 cx.update_global(|store: &mut SettingsStore, cx| {
13469 store.update_user_settings(cx, |settings| {
13470 settings.status_bar.get_or_insert_default().show = Some(false);
13471 });
13472 });
13473
13474 workspace.read_with(cx, |workspace, cx| {
13475 let visible = workspace.status_bar_visible(cx);
13476 assert!(!visible, "Status bar should be hidden when show is false");
13477 });
13478
13479 // Test with status bar shown explicitly
13480 cx.update_global(|store: &mut SettingsStore, cx| {
13481 store.update_user_settings(cx, |settings| {
13482 settings.status_bar.get_or_insert_default().show = Some(true);
13483 });
13484 });
13485
13486 workspace.read_with(cx, |workspace, cx| {
13487 let visible = workspace.status_bar_visible(cx);
13488 assert!(visible, "Status bar should be visible when show is true");
13489 });
13490 }
13491
13492 #[gpui::test]
13493 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13494 init_test(cx);
13495
13496 let fs = FakeFs::new(cx.executor());
13497 let project = Project::test(fs, [], cx).await;
13498 let (multi_workspace, cx) =
13499 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13500 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13501 let panel = workspace.update_in(cx, |workspace, window, cx| {
13502 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13503 workspace.add_panel(panel.clone(), window, cx);
13504
13505 workspace
13506 .right_dock()
13507 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13508
13509 panel
13510 });
13511
13512 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13513 let item_a = cx.new(TestItem::new);
13514 let item_b = cx.new(TestItem::new);
13515 let item_a_id = item_a.entity_id();
13516 let item_b_id = item_b.entity_id();
13517
13518 pane.update_in(cx, |pane, window, cx| {
13519 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13520 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13521 });
13522
13523 pane.read_with(cx, |pane, _| {
13524 assert_eq!(pane.items_len(), 2);
13525 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13526 });
13527
13528 workspace.update_in(cx, |workspace, window, cx| {
13529 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13530 });
13531
13532 workspace.update_in(cx, |_, window, cx| {
13533 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13534 });
13535
13536 // Assert that the `pane::CloseActiveItem` action is handled at the
13537 // workspace level when one of the dock panels is focused and, in that
13538 // case, the center pane's active item is closed but the focus is not
13539 // moved.
13540 cx.dispatch_action(pane::CloseActiveItem::default());
13541 cx.run_until_parked();
13542
13543 pane.read_with(cx, |pane, _| {
13544 assert_eq!(pane.items_len(), 1);
13545 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13546 });
13547
13548 workspace.update_in(cx, |workspace, window, cx| {
13549 assert!(workspace.right_dock().read(cx).is_open());
13550 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13551 });
13552 }
13553
13554 #[gpui::test]
13555 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13556 init_test(cx);
13557 let fs = FakeFs::new(cx.executor());
13558
13559 let project_a = Project::test(fs.clone(), [], cx).await;
13560 let project_b = Project::test(fs, [], cx).await;
13561
13562 let multi_workspace_handle =
13563 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13564 cx.run_until_parked();
13565
13566 let workspace_a = multi_workspace_handle
13567 .read_with(cx, |mw, _| mw.workspace().clone())
13568 .unwrap();
13569
13570 let _workspace_b = multi_workspace_handle
13571 .update(cx, |mw, window, cx| {
13572 mw.test_add_workspace(project_b, window, cx)
13573 })
13574 .unwrap();
13575
13576 // Switch to workspace A
13577 multi_workspace_handle
13578 .update(cx, |mw, window, cx| {
13579 mw.activate_index(0, window, cx);
13580 })
13581 .unwrap();
13582
13583 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13584
13585 // Add a panel to workspace A's right dock and open the dock
13586 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13587 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13588 workspace.add_panel(panel.clone(), window, cx);
13589 workspace
13590 .right_dock()
13591 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13592 panel
13593 });
13594
13595 // Focus the panel through the workspace (matching existing test pattern)
13596 workspace_a.update_in(cx, |workspace, window, cx| {
13597 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13598 });
13599
13600 // Zoom the panel
13601 panel.update_in(cx, |panel, window, cx| {
13602 panel.set_zoomed(true, window, cx);
13603 });
13604
13605 // Verify the panel is zoomed and the dock is open
13606 workspace_a.update_in(cx, |workspace, window, cx| {
13607 assert!(
13608 workspace.right_dock().read(cx).is_open(),
13609 "dock should be open before switch"
13610 );
13611 assert!(
13612 panel.is_zoomed(window, cx),
13613 "panel should be zoomed before switch"
13614 );
13615 assert!(
13616 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13617 "panel should be focused before switch"
13618 );
13619 });
13620
13621 // Switch to workspace B
13622 multi_workspace_handle
13623 .update(cx, |mw, window, cx| {
13624 mw.activate_index(1, window, cx);
13625 })
13626 .unwrap();
13627 cx.run_until_parked();
13628
13629 // Switch back to workspace A
13630 multi_workspace_handle
13631 .update(cx, |mw, window, cx| {
13632 mw.activate_index(0, window, cx);
13633 })
13634 .unwrap();
13635 cx.run_until_parked();
13636
13637 // Verify the panel is still zoomed and the dock is still open
13638 workspace_a.update_in(cx, |workspace, window, cx| {
13639 assert!(
13640 workspace.right_dock().read(cx).is_open(),
13641 "dock should still be open after switching back"
13642 );
13643 assert!(
13644 panel.is_zoomed(window, cx),
13645 "panel should still be zoomed after switching back"
13646 );
13647 });
13648 }
13649
13650 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13651 pane.read(cx)
13652 .items()
13653 .flat_map(|item| {
13654 item.project_paths(cx)
13655 .into_iter()
13656 .map(|path| path.path.display(PathStyle::local()).into_owned())
13657 })
13658 .collect()
13659 }
13660
13661 pub fn init_test(cx: &mut TestAppContext) {
13662 cx.update(|cx| {
13663 let settings_store = SettingsStore::test(cx);
13664 cx.set_global(settings_store);
13665 cx.set_global(db::AppDatabase::test_new());
13666 theme::init(theme::LoadThemes::JustBase, cx);
13667 });
13668 }
13669
13670 #[gpui::test]
13671 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
13672 use settings::{ThemeName, ThemeSelection};
13673 use theme::SystemAppearance;
13674 use zed_actions::theme::ToggleMode;
13675
13676 init_test(cx);
13677
13678 let fs = FakeFs::new(cx.executor());
13679 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
13680
13681 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
13682 .await;
13683
13684 // Build a test project and workspace view so the test can invoke
13685 // the workspace action handler the same way the UI would.
13686 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
13687 let (workspace, cx) =
13688 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13689
13690 // Seed the settings file with a plain static light theme so the
13691 // first toggle always starts from a known persisted state.
13692 workspace.update_in(cx, |_workspace, _window, cx| {
13693 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
13694 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
13695 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
13696 });
13697 });
13698 cx.executor().advance_clock(Duration::from_millis(200));
13699 cx.run_until_parked();
13700
13701 // Confirm the initial persisted settings contain the static theme
13702 // we just wrote before any toggling happens.
13703 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13704 assert!(settings_text.contains(r#""theme": "One Light""#));
13705
13706 // Toggle once. This should migrate the persisted theme settings
13707 // into light/dark slots and enable system mode.
13708 workspace.update_in(cx, |workspace, window, cx| {
13709 workspace.toggle_theme_mode(&ToggleMode, window, cx);
13710 });
13711 cx.executor().advance_clock(Duration::from_millis(200));
13712 cx.run_until_parked();
13713
13714 // 1. Static -> Dynamic
13715 // this assertion checks theme changed from static to dynamic.
13716 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13717 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
13718 assert_eq!(
13719 parsed["theme"],
13720 serde_json::json!({
13721 "mode": "system",
13722 "light": "One Light",
13723 "dark": "One Dark"
13724 })
13725 );
13726
13727 // 2. Toggle again, suppose it will change the mode to light
13728 workspace.update_in(cx, |workspace, window, cx| {
13729 workspace.toggle_theme_mode(&ToggleMode, window, cx);
13730 });
13731 cx.executor().advance_clock(Duration::from_millis(200));
13732 cx.run_until_parked();
13733
13734 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13735 assert!(settings_text.contains(r#""mode": "light""#));
13736 }
13737
13738 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13739 let item = TestProjectItem::new(id, path, cx);
13740 item.update(cx, |item, _| {
13741 item.is_dirty = true;
13742 });
13743 item
13744 }
13745
13746 #[gpui::test]
13747 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13748 cx: &mut gpui::TestAppContext,
13749 ) {
13750 init_test(cx);
13751 let fs = FakeFs::new(cx.executor());
13752
13753 let project = Project::test(fs, [], cx).await;
13754 let (workspace, cx) =
13755 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13756
13757 let panel = workspace.update_in(cx, |workspace, window, cx| {
13758 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13759 workspace.add_panel(panel.clone(), window, cx);
13760 workspace
13761 .right_dock()
13762 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13763 panel
13764 });
13765
13766 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13767 pane.update_in(cx, |pane, window, cx| {
13768 let item = cx.new(TestItem::new);
13769 pane.add_item(Box::new(item), true, true, None, window, cx);
13770 });
13771
13772 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13773 // mirrors the real-world flow and avoids side effects from directly
13774 // focusing the panel while the center pane is active.
13775 workspace.update_in(cx, |workspace, window, cx| {
13776 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13777 });
13778
13779 panel.update_in(cx, |panel, window, cx| {
13780 panel.set_zoomed(true, window, cx);
13781 });
13782
13783 workspace.update_in(cx, |workspace, window, cx| {
13784 assert!(workspace.right_dock().read(cx).is_open());
13785 assert!(panel.is_zoomed(window, cx));
13786 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13787 });
13788
13789 // Simulate a spurious pane::Event::Focus on the center pane while the
13790 // panel still has focus. This mirrors what happens during macOS window
13791 // activation: the center pane fires a focus event even though actual
13792 // focus remains on the dock panel.
13793 pane.update_in(cx, |_, _, cx| {
13794 cx.emit(pane::Event::Focus);
13795 });
13796
13797 // The dock must remain open because the panel had focus at the time the
13798 // event was processed. Before the fix, dock_to_preserve was None for
13799 // panels that don't implement pane(), causing the dock to close.
13800 workspace.update_in(cx, |workspace, window, cx| {
13801 assert!(
13802 workspace.right_dock().read(cx).is_open(),
13803 "Dock should stay open when its zoomed panel (without pane()) still has focus"
13804 );
13805 assert!(panel.is_zoomed(window, cx));
13806 });
13807 }
13808}