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::{DB, SerializedWindowBounds, model::SerializedWorkspace};
79pub use persistence::{
80 DB as WORKSPACE_DB, 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}
1344
1345impl EventEmitter<Event> for Workspace {}
1346
1347#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1348pub struct ViewId {
1349 pub creator: CollaboratorId,
1350 pub id: u64,
1351}
1352
1353pub struct FollowerState {
1354 center_pane: Entity<Pane>,
1355 dock_pane: Option<Entity<Pane>>,
1356 active_view_id: Option<ViewId>,
1357 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1358}
1359
1360struct FollowerView {
1361 view: Box<dyn FollowableItemHandle>,
1362 location: Option<proto::PanelId>,
1363}
1364
1365impl Workspace {
1366 pub fn new(
1367 workspace_id: Option<WorkspaceId>,
1368 project: Entity<Project>,
1369 app_state: Arc<AppState>,
1370 window: &mut Window,
1371 cx: &mut Context<Self>,
1372 ) -> Self {
1373 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1374 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1375 if let TrustedWorktreesEvent::Trusted(..) = e {
1376 // Do not persist auto trusted worktrees
1377 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1378 worktrees_store.update(cx, |worktrees_store, cx| {
1379 worktrees_store.schedule_serialization(
1380 cx,
1381 |new_trusted_worktrees, cx| {
1382 let timeout =
1383 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1384 cx.background_spawn(async move {
1385 timeout.await;
1386 persistence::DB
1387 .save_trusted_worktrees(new_trusted_worktrees)
1388 .await
1389 .log_err();
1390 })
1391 },
1392 )
1393 });
1394 }
1395 }
1396 })
1397 .detach();
1398
1399 cx.observe_global::<SettingsStore>(|_, cx| {
1400 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1401 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1402 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1403 trusted_worktrees.auto_trust_all(cx);
1404 })
1405 }
1406 }
1407 })
1408 .detach();
1409 }
1410
1411 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1412 match event {
1413 project::Event::RemoteIdChanged(_) => {
1414 this.update_window_title(window, cx);
1415 }
1416
1417 project::Event::CollaboratorLeft(peer_id) => {
1418 this.collaborator_left(*peer_id, window, cx);
1419 }
1420
1421 &project::Event::WorktreeRemoved(id) | &project::Event::WorktreeAdded(id) => {
1422 this.update_window_title(window, cx);
1423 if this
1424 .project()
1425 .read(cx)
1426 .worktree_for_id(id, cx)
1427 .is_some_and(|wt| wt.read(cx).is_visible())
1428 {
1429 this.serialize_workspace(window, cx);
1430 this.update_history(cx);
1431 }
1432 }
1433 project::Event::WorktreeUpdatedEntries(..) => {
1434 this.update_window_title(window, cx);
1435 this.serialize_workspace(window, cx);
1436 }
1437
1438 project::Event::DisconnectedFromHost => {
1439 this.update_window_edited(window, cx);
1440 let leaders_to_unfollow =
1441 this.follower_states.keys().copied().collect::<Vec<_>>();
1442 for leader_id in leaders_to_unfollow {
1443 this.unfollow(leader_id, window, cx);
1444 }
1445 }
1446
1447 project::Event::DisconnectedFromRemote {
1448 server_not_running: _,
1449 } => {
1450 this.update_window_edited(window, cx);
1451 }
1452
1453 project::Event::Closed => {
1454 window.remove_window();
1455 }
1456
1457 project::Event::DeletedEntry(_, entry_id) => {
1458 for pane in this.panes.iter() {
1459 pane.update(cx, |pane, cx| {
1460 pane.handle_deleted_project_item(*entry_id, window, cx)
1461 });
1462 }
1463 }
1464
1465 project::Event::Toast {
1466 notification_id,
1467 message,
1468 link,
1469 } => this.show_notification(
1470 NotificationId::named(notification_id.clone()),
1471 cx,
1472 |cx| {
1473 let mut notification = MessageNotification::new(message.clone(), cx);
1474 if let Some(link) = link {
1475 notification = notification
1476 .more_info_message(link.label)
1477 .more_info_url(link.url);
1478 }
1479
1480 cx.new(|_| notification)
1481 },
1482 ),
1483
1484 project::Event::HideToast { notification_id } => {
1485 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1486 }
1487
1488 project::Event::LanguageServerPrompt(request) => {
1489 struct LanguageServerPrompt;
1490
1491 this.show_notification(
1492 NotificationId::composite::<LanguageServerPrompt>(request.id),
1493 cx,
1494 |cx| {
1495 cx.new(|cx| {
1496 notifications::LanguageServerPrompt::new(request.clone(), cx)
1497 })
1498 },
1499 );
1500 }
1501
1502 project::Event::AgentLocationChanged => {
1503 this.handle_agent_location_changed(window, cx)
1504 }
1505
1506 _ => {}
1507 }
1508 cx.notify()
1509 })
1510 .detach();
1511
1512 cx.subscribe_in(
1513 &project.read(cx).breakpoint_store(),
1514 window,
1515 |workspace, _, event, window, cx| match event {
1516 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1517 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1518 workspace.serialize_workspace(window, cx);
1519 }
1520 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1521 },
1522 )
1523 .detach();
1524 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1525 cx.subscribe_in(
1526 &toolchain_store,
1527 window,
1528 |workspace, _, event, window, cx| match event {
1529 ToolchainStoreEvent::CustomToolchainsModified => {
1530 workspace.serialize_workspace(window, cx);
1531 }
1532 _ => {}
1533 },
1534 )
1535 .detach();
1536 }
1537
1538 cx.on_focus_lost(window, |this, window, cx| {
1539 let focus_handle = this.focus_handle(cx);
1540 window.focus(&focus_handle, cx);
1541 })
1542 .detach();
1543
1544 let weak_handle = cx.entity().downgrade();
1545 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1546
1547 let center_pane = cx.new(|cx| {
1548 let mut center_pane = Pane::new(
1549 weak_handle.clone(),
1550 project.clone(),
1551 pane_history_timestamp.clone(),
1552 None,
1553 NewFile.boxed_clone(),
1554 true,
1555 window,
1556 cx,
1557 );
1558 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1559 center_pane.set_should_display_welcome_page(true);
1560 center_pane
1561 });
1562 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1563 .detach();
1564
1565 window.focus(¢er_pane.focus_handle(cx), cx);
1566
1567 cx.emit(Event::PaneAdded(center_pane.clone()));
1568
1569 let any_window_handle = window.window_handle();
1570 app_state.workspace_store.update(cx, |store, _| {
1571 store
1572 .workspaces
1573 .insert((any_window_handle, weak_handle.clone()));
1574 });
1575
1576 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1577 let mut connection_status = app_state.client.status();
1578 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1579 current_user.next().await;
1580 connection_status.next().await;
1581 let mut stream =
1582 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1583
1584 while stream.recv().await.is_some() {
1585 this.update(cx, |_, cx| cx.notify())?;
1586 }
1587 anyhow::Ok(())
1588 });
1589
1590 // All leader updates are enqueued and then processed in a single task, so
1591 // that each asynchronous operation can be run in order.
1592 let (leader_updates_tx, mut leader_updates_rx) =
1593 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1594 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1595 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1596 Self::process_leader_update(&this, leader_id, update, cx)
1597 .await
1598 .log_err();
1599 }
1600
1601 Ok(())
1602 });
1603
1604 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1605 let modal_layer = cx.new(|_| ModalLayer::new());
1606 let toast_layer = cx.new(|_| ToastLayer::new());
1607 cx.subscribe(
1608 &modal_layer,
1609 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1610 cx.emit(Event::ModalOpened);
1611 },
1612 )
1613 .detach();
1614
1615 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1616 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1617 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1618 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1619 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1620 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1621 let status_bar = cx.new(|cx| {
1622 let mut status_bar = StatusBar::new(¢er_pane.clone(), window, cx);
1623 status_bar.add_left_item(left_dock_buttons, window, cx);
1624 status_bar.add_right_item(right_dock_buttons, window, cx);
1625 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1626 status_bar
1627 });
1628
1629 let session_id = app_state.session.read(cx).id().to_owned();
1630
1631 let mut active_call = None;
1632 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1633 let subscriptions =
1634 vec![
1635 call.0
1636 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1637 ];
1638 active_call = Some((call, subscriptions));
1639 }
1640
1641 let (serializable_items_tx, serializable_items_rx) =
1642 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1643 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1644 Self::serialize_items(&this, serializable_items_rx, cx).await
1645 });
1646
1647 let subscriptions = vec![
1648 cx.observe_window_activation(window, Self::on_window_activation_changed),
1649 cx.observe_window_bounds(window, move |this, window, cx| {
1650 if this.bounds_save_task_queued.is_some() {
1651 return;
1652 }
1653 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1654 cx.background_executor()
1655 .timer(Duration::from_millis(100))
1656 .await;
1657 this.update_in(cx, |this, window, cx| {
1658 this.save_window_bounds(window, cx).detach();
1659 this.bounds_save_task_queued.take();
1660 })
1661 .ok();
1662 }));
1663 cx.notify();
1664 }),
1665 cx.observe_window_appearance(window, |_, window, cx| {
1666 let window_appearance = window.appearance();
1667
1668 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1669
1670 GlobalTheme::reload_theme(cx);
1671 GlobalTheme::reload_icon_theme(cx);
1672 }),
1673 cx.on_release({
1674 let weak_handle = weak_handle.clone();
1675 move |this, cx| {
1676 this.app_state.workspace_store.update(cx, move |store, _| {
1677 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1678 })
1679 }
1680 }),
1681 ];
1682
1683 cx.defer_in(window, move |this, window, cx| {
1684 this.update_window_title(window, cx);
1685 this.show_initial_notifications(cx);
1686 });
1687
1688 let mut center = PaneGroup::new(center_pane.clone());
1689 center.set_is_center(true);
1690 center.mark_positions(cx);
1691
1692 Workspace {
1693 weak_self: weak_handle.clone(),
1694 zoomed: None,
1695 zoomed_position: None,
1696 previous_dock_drag_coordinates: None,
1697 center,
1698 panes: vec![center_pane.clone()],
1699 panes_by_item: Default::default(),
1700 active_pane: center_pane.clone(),
1701 last_active_center_pane: Some(center_pane.downgrade()),
1702 last_active_view_id: None,
1703 status_bar,
1704 modal_layer,
1705 toast_layer,
1706 titlebar_item: None,
1707 active_worktree_override: None,
1708 notifications: Notifications::default(),
1709 suppressed_notifications: HashSet::default(),
1710 left_dock,
1711 bottom_dock,
1712 right_dock,
1713 _panels_task: None,
1714 project: project.clone(),
1715 follower_states: Default::default(),
1716 last_leaders_by_pane: Default::default(),
1717 dispatching_keystrokes: Default::default(),
1718 window_edited: false,
1719 last_window_title: None,
1720 dirty_items: Default::default(),
1721 active_call,
1722 database_id: workspace_id,
1723 app_state,
1724 _observe_current_user,
1725 _apply_leader_updates,
1726 _schedule_serialize_workspace: None,
1727 _serialize_workspace_task: None,
1728 _schedule_serialize_ssh_paths: None,
1729 leader_updates_tx,
1730 _subscriptions: subscriptions,
1731 pane_history_timestamp,
1732 workspace_actions: Default::default(),
1733 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1734 bounds: Default::default(),
1735 centered_layout: false,
1736 bounds_save_task_queued: None,
1737 on_prompt_for_new_path: None,
1738 on_prompt_for_open_path: None,
1739 terminal_provider: None,
1740 debugger_provider: None,
1741 serializable_items_tx,
1742 _items_serializer,
1743 session_id: Some(session_id),
1744
1745 scheduled_tasks: Vec::new(),
1746 last_open_dock_positions: Vec::new(),
1747 removing: false,
1748 }
1749 }
1750
1751 pub fn new_local(
1752 abs_paths: Vec<PathBuf>,
1753 app_state: Arc<AppState>,
1754 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1755 env: Option<HashMap<String, String>>,
1756 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1757 activate: bool,
1758 cx: &mut App,
1759 ) -> Task<anyhow::Result<OpenResult>> {
1760 let project_handle = Project::local(
1761 app_state.client.clone(),
1762 app_state.node_runtime.clone(),
1763 app_state.user_store.clone(),
1764 app_state.languages.clone(),
1765 app_state.fs.clone(),
1766 env,
1767 Default::default(),
1768 cx,
1769 );
1770
1771 cx.spawn(async move |cx| {
1772 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1773 for path in abs_paths.into_iter() {
1774 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1775 paths_to_open.push(canonical)
1776 } else {
1777 paths_to_open.push(path)
1778 }
1779 }
1780
1781 let serialized_workspace =
1782 persistence::DB.workspace_for_roots(paths_to_open.as_slice());
1783
1784 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1785 paths_to_open = paths.ordered_paths().cloned().collect();
1786 if !paths.is_lexicographically_ordered() {
1787 project_handle.update(cx, |project, cx| {
1788 project.set_worktrees_reordered(true, cx);
1789 });
1790 }
1791 }
1792
1793 // Get project paths for all of the abs_paths
1794 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1795 Vec::with_capacity(paths_to_open.len());
1796
1797 for path in paths_to_open.into_iter() {
1798 if let Some((_, project_entry)) = cx
1799 .update(|cx| {
1800 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1801 })
1802 .await
1803 .log_err()
1804 {
1805 project_paths.push((path, Some(project_entry)));
1806 } else {
1807 project_paths.push((path, None));
1808 }
1809 }
1810
1811 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1812 serialized_workspace.id
1813 } else {
1814 DB.next_id().await.unwrap_or_else(|_| Default::default())
1815 };
1816
1817 let toolchains = DB.toolchains(workspace_id).await?;
1818
1819 for (toolchain, worktree_path, path) in toolchains {
1820 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1821 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1822 this.find_worktree(&worktree_path, cx)
1823 .and_then(|(worktree, rel_path)| {
1824 if rel_path.is_empty() {
1825 Some(worktree.read(cx).id())
1826 } else {
1827 None
1828 }
1829 })
1830 }) else {
1831 // We did not find a worktree with a given path, but that's whatever.
1832 continue;
1833 };
1834 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1835 continue;
1836 }
1837
1838 project_handle
1839 .update(cx, |this, cx| {
1840 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1841 })
1842 .await;
1843 }
1844 if let Some(workspace) = serialized_workspace.as_ref() {
1845 project_handle.update(cx, |this, cx| {
1846 for (scope, toolchains) in &workspace.user_toolchains {
1847 for toolchain in toolchains {
1848 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1849 }
1850 }
1851 });
1852 }
1853
1854 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1855 if let Some(window) = requesting_window {
1856 let centered_layout = serialized_workspace
1857 .as_ref()
1858 .map(|w| w.centered_layout)
1859 .unwrap_or(false);
1860
1861 let workspace = window.update(cx, |multi_workspace, window, cx| {
1862 let workspace = cx.new(|cx| {
1863 let mut workspace = Workspace::new(
1864 Some(workspace_id),
1865 project_handle.clone(),
1866 app_state.clone(),
1867 window,
1868 cx,
1869 );
1870
1871 workspace.centered_layout = centered_layout;
1872
1873 // Call init callback to add items before window renders
1874 if let Some(init) = init {
1875 init(&mut workspace, window, cx);
1876 }
1877
1878 workspace
1879 });
1880 if activate {
1881 multi_workspace.activate(workspace.clone(), cx);
1882 } else {
1883 multi_workspace.add_workspace(workspace.clone(), cx);
1884 }
1885 workspace
1886 })?;
1887 (window, workspace)
1888 } else {
1889 let window_bounds_override = window_bounds_env_override();
1890
1891 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1892 (Some(WindowBounds::Windowed(bounds)), None)
1893 } else if let Some(workspace) = serialized_workspace.as_ref()
1894 && let Some(display) = workspace.display
1895 && let Some(bounds) = workspace.window_bounds.as_ref()
1896 {
1897 // Reopening an existing workspace - restore its saved bounds
1898 (Some(bounds.0), Some(display))
1899 } else if let Some((display, bounds)) =
1900 persistence::read_default_window_bounds()
1901 {
1902 // New or empty workspace - use the last known window bounds
1903 (Some(bounds), Some(display))
1904 } else {
1905 // New window - let GPUI's default_bounds() handle cascading
1906 (None, None)
1907 };
1908
1909 // Use the serialized workspace to construct the new window
1910 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1911 options.window_bounds = window_bounds;
1912 let centered_layout = serialized_workspace
1913 .as_ref()
1914 .map(|w| w.centered_layout)
1915 .unwrap_or(false);
1916 let window = cx.open_window(options, {
1917 let app_state = app_state.clone();
1918 let project_handle = project_handle.clone();
1919 move |window, cx| {
1920 let workspace = cx.new(|cx| {
1921 let mut workspace = Workspace::new(
1922 Some(workspace_id),
1923 project_handle,
1924 app_state,
1925 window,
1926 cx,
1927 );
1928 workspace.centered_layout = centered_layout;
1929
1930 // Call init callback to add items before window renders
1931 if let Some(init) = init {
1932 init(&mut workspace, window, cx);
1933 }
1934
1935 workspace
1936 });
1937 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1938 }
1939 })?;
1940 let workspace =
1941 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
1942 multi_workspace.workspace().clone()
1943 })?;
1944 (window, workspace)
1945 };
1946
1947 notify_if_database_failed(window, cx);
1948 // Check if this is an empty workspace (no paths to open)
1949 // An empty workspace is one where project_paths is empty
1950 let is_empty_workspace = project_paths.is_empty();
1951 // Check if serialized workspace has paths before it's moved
1952 let serialized_workspace_has_paths = serialized_workspace
1953 .as_ref()
1954 .map(|ws| !ws.paths.is_empty())
1955 .unwrap_or(false);
1956
1957 let opened_items = window
1958 .update(cx, |_, window, cx| {
1959 workspace.update(cx, |_workspace: &mut Workspace, cx| {
1960 open_items(serialized_workspace, project_paths, window, cx)
1961 })
1962 })?
1963 .await
1964 .unwrap_or_default();
1965
1966 // Restore default dock state for empty workspaces
1967 // Only restore if:
1968 // 1. This is an empty workspace (no paths), AND
1969 // 2. The serialized workspace either doesn't exist or has no paths
1970 if is_empty_workspace && !serialized_workspace_has_paths {
1971 if let Some(default_docks) = persistence::read_default_dock_state() {
1972 window
1973 .update(cx, |_, window, cx| {
1974 workspace.update(cx, |workspace, cx| {
1975 for (dock, serialized_dock) in [
1976 (&workspace.right_dock, &default_docks.right),
1977 (&workspace.left_dock, &default_docks.left),
1978 (&workspace.bottom_dock, &default_docks.bottom),
1979 ] {
1980 dock.update(cx, |dock, cx| {
1981 dock.serialized_dock = Some(serialized_dock.clone());
1982 dock.restore_state(window, cx);
1983 });
1984 }
1985 cx.notify();
1986 });
1987 })
1988 .log_err();
1989 }
1990 }
1991
1992 window
1993 .update(cx, |_, _window, cx| {
1994 workspace.update(cx, |this: &mut Workspace, cx| {
1995 this.update_history(cx);
1996 });
1997 })
1998 .log_err();
1999 Ok(OpenResult {
2000 window,
2001 workspace,
2002 opened_items,
2003 })
2004 })
2005 }
2006
2007 pub fn weak_handle(&self) -> WeakEntity<Self> {
2008 self.weak_self.clone()
2009 }
2010
2011 pub fn left_dock(&self) -> &Entity<Dock> {
2012 &self.left_dock
2013 }
2014
2015 pub fn bottom_dock(&self) -> &Entity<Dock> {
2016 &self.bottom_dock
2017 }
2018
2019 pub fn set_bottom_dock_layout(
2020 &mut self,
2021 layout: BottomDockLayout,
2022 window: &mut Window,
2023 cx: &mut Context<Self>,
2024 ) {
2025 let fs = self.project().read(cx).fs();
2026 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2027 content.workspace.bottom_dock_layout = Some(layout);
2028 });
2029
2030 cx.notify();
2031 self.serialize_workspace(window, cx);
2032 }
2033
2034 pub fn right_dock(&self) -> &Entity<Dock> {
2035 &self.right_dock
2036 }
2037
2038 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2039 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2040 }
2041
2042 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2043 let left_dock = self.left_dock.read(cx);
2044 let left_visible = left_dock.is_open();
2045 let left_active_panel = left_dock
2046 .active_panel()
2047 .map(|panel| panel.persistent_name().to_string());
2048 // `zoomed_position` is kept in sync with individual panel zoom state
2049 // by the dock code in `Dock::new` and `Dock::add_panel`.
2050 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2051
2052 let right_dock = self.right_dock.read(cx);
2053 let right_visible = right_dock.is_open();
2054 let right_active_panel = right_dock
2055 .active_panel()
2056 .map(|panel| panel.persistent_name().to_string());
2057 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2058
2059 let bottom_dock = self.bottom_dock.read(cx);
2060 let bottom_visible = bottom_dock.is_open();
2061 let bottom_active_panel = bottom_dock
2062 .active_panel()
2063 .map(|panel| panel.persistent_name().to_string());
2064 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2065
2066 DockStructure {
2067 left: DockData {
2068 visible: left_visible,
2069 active_panel: left_active_panel,
2070 zoom: left_dock_zoom,
2071 },
2072 right: DockData {
2073 visible: right_visible,
2074 active_panel: right_active_panel,
2075 zoom: right_dock_zoom,
2076 },
2077 bottom: DockData {
2078 visible: bottom_visible,
2079 active_panel: bottom_active_panel,
2080 zoom: bottom_dock_zoom,
2081 },
2082 }
2083 }
2084
2085 pub fn set_dock_structure(
2086 &self,
2087 docks: DockStructure,
2088 window: &mut Window,
2089 cx: &mut Context<Self>,
2090 ) {
2091 for (dock, data) in [
2092 (&self.left_dock, docks.left),
2093 (&self.bottom_dock, docks.bottom),
2094 (&self.right_dock, docks.right),
2095 ] {
2096 dock.update(cx, |dock, cx| {
2097 dock.serialized_dock = Some(data);
2098 dock.restore_state(window, cx);
2099 });
2100 }
2101 }
2102
2103 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2104 self.items(cx)
2105 .filter_map(|item| {
2106 let project_path = item.project_path(cx)?;
2107 self.project.read(cx).absolute_path(&project_path, cx)
2108 })
2109 .collect()
2110 }
2111
2112 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2113 match position {
2114 DockPosition::Left => &self.left_dock,
2115 DockPosition::Bottom => &self.bottom_dock,
2116 DockPosition::Right => &self.right_dock,
2117 }
2118 }
2119
2120 pub fn is_edited(&self) -> bool {
2121 self.window_edited
2122 }
2123
2124 pub fn add_panel<T: Panel>(
2125 &mut self,
2126 panel: Entity<T>,
2127 window: &mut Window,
2128 cx: &mut Context<Self>,
2129 ) {
2130 let focus_handle = panel.panel_focus_handle(cx);
2131 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2132 .detach();
2133
2134 let dock_position = panel.position(window, cx);
2135 let dock = self.dock_at_position(dock_position);
2136 let any_panel = panel.to_any();
2137
2138 dock.update(cx, |dock, cx| {
2139 dock.add_panel(panel, self.weak_self.clone(), window, cx)
2140 });
2141
2142 cx.emit(Event::PanelAdded(any_panel));
2143 }
2144
2145 pub fn remove_panel<T: Panel>(
2146 &mut self,
2147 panel: &Entity<T>,
2148 window: &mut Window,
2149 cx: &mut Context<Self>,
2150 ) {
2151 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2152 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2153 }
2154 }
2155
2156 pub fn status_bar(&self) -> &Entity<StatusBar> {
2157 &self.status_bar
2158 }
2159
2160 pub fn set_workspace_sidebar_open(&self, open: bool, cx: &mut App) {
2161 self.status_bar.update(cx, |status_bar, cx| {
2162 status_bar.set_workspace_sidebar_open(open, cx);
2163 });
2164 }
2165
2166 pub fn status_bar_visible(&self, cx: &App) -> bool {
2167 StatusBarSettings::get_global(cx).show
2168 }
2169
2170 pub fn app_state(&self) -> &Arc<AppState> {
2171 &self.app_state
2172 }
2173
2174 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2175 self._panels_task = Some(task);
2176 }
2177
2178 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2179 self._panels_task.take()
2180 }
2181
2182 pub fn user_store(&self) -> &Entity<UserStore> {
2183 &self.app_state.user_store
2184 }
2185
2186 pub fn project(&self) -> &Entity<Project> {
2187 &self.project
2188 }
2189
2190 pub fn path_style(&self, cx: &App) -> PathStyle {
2191 self.project.read(cx).path_style(cx)
2192 }
2193
2194 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2195 let mut history: HashMap<EntityId, usize> = HashMap::default();
2196
2197 for pane_handle in &self.panes {
2198 let pane = pane_handle.read(cx);
2199
2200 for entry in pane.activation_history() {
2201 history.insert(
2202 entry.entity_id,
2203 history
2204 .get(&entry.entity_id)
2205 .cloned()
2206 .unwrap_or(0)
2207 .max(entry.timestamp),
2208 );
2209 }
2210 }
2211
2212 history
2213 }
2214
2215 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2216 let mut recent_item: Option<Entity<T>> = None;
2217 let mut recent_timestamp = 0;
2218 for pane_handle in &self.panes {
2219 let pane = pane_handle.read(cx);
2220 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2221 pane.items().map(|item| (item.item_id(), item)).collect();
2222 for entry in pane.activation_history() {
2223 if entry.timestamp > recent_timestamp
2224 && let Some(&item) = item_map.get(&entry.entity_id)
2225 && let Some(typed_item) = item.act_as::<T>(cx)
2226 {
2227 recent_timestamp = entry.timestamp;
2228 recent_item = Some(typed_item);
2229 }
2230 }
2231 }
2232 recent_item
2233 }
2234
2235 pub fn recent_navigation_history_iter(
2236 &self,
2237 cx: &App,
2238 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2239 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2240 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2241
2242 for pane in &self.panes {
2243 let pane = pane.read(cx);
2244
2245 pane.nav_history()
2246 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2247 if let Some(fs_path) = &fs_path {
2248 abs_paths_opened
2249 .entry(fs_path.clone())
2250 .or_default()
2251 .insert(project_path.clone());
2252 }
2253 let timestamp = entry.timestamp;
2254 match history.entry(project_path) {
2255 hash_map::Entry::Occupied(mut entry) => {
2256 let (_, old_timestamp) = entry.get();
2257 if ×tamp > old_timestamp {
2258 entry.insert((fs_path, timestamp));
2259 }
2260 }
2261 hash_map::Entry::Vacant(entry) => {
2262 entry.insert((fs_path, timestamp));
2263 }
2264 }
2265 });
2266
2267 if let Some(item) = pane.active_item()
2268 && let Some(project_path) = item.project_path(cx)
2269 {
2270 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2271
2272 if let Some(fs_path) = &fs_path {
2273 abs_paths_opened
2274 .entry(fs_path.clone())
2275 .or_default()
2276 .insert(project_path.clone());
2277 }
2278
2279 history.insert(project_path, (fs_path, std::usize::MAX));
2280 }
2281 }
2282
2283 history
2284 .into_iter()
2285 .sorted_by_key(|(_, (_, order))| *order)
2286 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2287 .rev()
2288 .filter(move |(history_path, abs_path)| {
2289 let latest_project_path_opened = abs_path
2290 .as_ref()
2291 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2292 .and_then(|project_paths| {
2293 project_paths
2294 .iter()
2295 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2296 });
2297
2298 latest_project_path_opened.is_none_or(|path| path == history_path)
2299 })
2300 }
2301
2302 pub fn recent_navigation_history(
2303 &self,
2304 limit: Option<usize>,
2305 cx: &App,
2306 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2307 self.recent_navigation_history_iter(cx)
2308 .take(limit.unwrap_or(usize::MAX))
2309 .collect()
2310 }
2311
2312 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2313 for pane in &self.panes {
2314 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2315 }
2316 }
2317
2318 fn navigate_history(
2319 &mut self,
2320 pane: WeakEntity<Pane>,
2321 mode: NavigationMode,
2322 window: &mut Window,
2323 cx: &mut Context<Workspace>,
2324 ) -> Task<Result<()>> {
2325 self.navigate_history_impl(
2326 pane,
2327 mode,
2328 window,
2329 &mut |history, cx| history.pop(mode, cx),
2330 cx,
2331 )
2332 }
2333
2334 fn navigate_tag_history(
2335 &mut self,
2336 pane: WeakEntity<Pane>,
2337 mode: TagNavigationMode,
2338 window: &mut Window,
2339 cx: &mut Context<Workspace>,
2340 ) -> Task<Result<()>> {
2341 self.navigate_history_impl(
2342 pane,
2343 NavigationMode::Normal,
2344 window,
2345 &mut |history, _cx| history.pop_tag(mode),
2346 cx,
2347 )
2348 }
2349
2350 fn navigate_history_impl(
2351 &mut self,
2352 pane: WeakEntity<Pane>,
2353 mode: NavigationMode,
2354 window: &mut Window,
2355 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2356 cx: &mut Context<Workspace>,
2357 ) -> Task<Result<()>> {
2358 let to_load = if let Some(pane) = pane.upgrade() {
2359 pane.update(cx, |pane, cx| {
2360 window.focus(&pane.focus_handle(cx), cx);
2361 loop {
2362 // Retrieve the weak item handle from the history.
2363 let entry = cb(pane.nav_history_mut(), cx)?;
2364
2365 // If the item is still present in this pane, then activate it.
2366 if let Some(index) = entry
2367 .item
2368 .upgrade()
2369 .and_then(|v| pane.index_for_item(v.as_ref()))
2370 {
2371 let prev_active_item_index = pane.active_item_index();
2372 pane.nav_history_mut().set_mode(mode);
2373 pane.activate_item(index, true, true, window, cx);
2374 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2375
2376 let mut navigated = prev_active_item_index != pane.active_item_index();
2377 if let Some(data) = entry.data {
2378 navigated |= pane.active_item()?.navigate(data, window, cx);
2379 }
2380
2381 if navigated {
2382 break None;
2383 }
2384 } else {
2385 // If the item is no longer present in this pane, then retrieve its
2386 // path info in order to reopen it.
2387 break pane
2388 .nav_history()
2389 .path_for_item(entry.item.id())
2390 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2391 }
2392 }
2393 })
2394 } else {
2395 None
2396 };
2397
2398 if let Some((project_path, abs_path, entry)) = to_load {
2399 // If the item was no longer present, then load it again from its previous path, first try the local path
2400 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2401
2402 cx.spawn_in(window, async move |workspace, cx| {
2403 let open_by_project_path = open_by_project_path.await;
2404 let mut navigated = false;
2405 match open_by_project_path
2406 .with_context(|| format!("Navigating to {project_path:?}"))
2407 {
2408 Ok((project_entry_id, build_item)) => {
2409 let prev_active_item_id = pane.update(cx, |pane, _| {
2410 pane.nav_history_mut().set_mode(mode);
2411 pane.active_item().map(|p| p.item_id())
2412 })?;
2413
2414 pane.update_in(cx, |pane, window, cx| {
2415 let item = pane.open_item(
2416 project_entry_id,
2417 project_path,
2418 true,
2419 entry.is_preview,
2420 true,
2421 None,
2422 window, cx,
2423 build_item,
2424 );
2425 navigated |= Some(item.item_id()) != prev_active_item_id;
2426 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2427 if let Some(data) = entry.data {
2428 navigated |= item.navigate(data, window, cx);
2429 }
2430 })?;
2431 }
2432 Err(open_by_project_path_e) => {
2433 // Fall back to opening by abs path, in case an external file was opened and closed,
2434 // and its worktree is now dropped
2435 if let Some(abs_path) = abs_path {
2436 let prev_active_item_id = pane.update(cx, |pane, _| {
2437 pane.nav_history_mut().set_mode(mode);
2438 pane.active_item().map(|p| p.item_id())
2439 })?;
2440 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2441 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2442 })?;
2443 match open_by_abs_path
2444 .await
2445 .with_context(|| format!("Navigating to {abs_path:?}"))
2446 {
2447 Ok(item) => {
2448 pane.update_in(cx, |pane, window, cx| {
2449 navigated |= Some(item.item_id()) != prev_active_item_id;
2450 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2451 if let Some(data) = entry.data {
2452 navigated |= item.navigate(data, window, cx);
2453 }
2454 })?;
2455 }
2456 Err(open_by_abs_path_e) => {
2457 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2458 }
2459 }
2460 }
2461 }
2462 }
2463
2464 if !navigated {
2465 workspace
2466 .update_in(cx, |workspace, window, cx| {
2467 Self::navigate_history(workspace, pane, mode, window, cx)
2468 })?
2469 .await?;
2470 }
2471
2472 Ok(())
2473 })
2474 } else {
2475 Task::ready(Ok(()))
2476 }
2477 }
2478
2479 pub fn go_back(
2480 &mut self,
2481 pane: WeakEntity<Pane>,
2482 window: &mut Window,
2483 cx: &mut Context<Workspace>,
2484 ) -> Task<Result<()>> {
2485 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2486 }
2487
2488 pub fn go_forward(
2489 &mut self,
2490 pane: WeakEntity<Pane>,
2491 window: &mut Window,
2492 cx: &mut Context<Workspace>,
2493 ) -> Task<Result<()>> {
2494 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2495 }
2496
2497 pub fn reopen_closed_item(
2498 &mut self,
2499 window: &mut Window,
2500 cx: &mut Context<Workspace>,
2501 ) -> Task<Result<()>> {
2502 self.navigate_history(
2503 self.active_pane().downgrade(),
2504 NavigationMode::ReopeningClosedItem,
2505 window,
2506 cx,
2507 )
2508 }
2509
2510 pub fn client(&self) -> &Arc<Client> {
2511 &self.app_state.client
2512 }
2513
2514 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2515 self.titlebar_item = Some(item);
2516 cx.notify();
2517 }
2518
2519 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2520 self.on_prompt_for_new_path = Some(prompt)
2521 }
2522
2523 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2524 self.on_prompt_for_open_path = Some(prompt)
2525 }
2526
2527 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2528 self.terminal_provider = Some(Box::new(provider));
2529 }
2530
2531 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2532 self.debugger_provider = Some(Arc::new(provider));
2533 }
2534
2535 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2536 self.debugger_provider.clone()
2537 }
2538
2539 pub fn prompt_for_open_path(
2540 &mut self,
2541 path_prompt_options: PathPromptOptions,
2542 lister: DirectoryLister,
2543 window: &mut Window,
2544 cx: &mut Context<Self>,
2545 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2546 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2547 let prompt = self.on_prompt_for_open_path.take().unwrap();
2548 let rx = prompt(self, lister, window, cx);
2549 self.on_prompt_for_open_path = Some(prompt);
2550 rx
2551 } else {
2552 let (tx, rx) = oneshot::channel();
2553 let abs_path = cx.prompt_for_paths(path_prompt_options);
2554
2555 cx.spawn_in(window, async move |workspace, cx| {
2556 let Ok(result) = abs_path.await else {
2557 return Ok(());
2558 };
2559
2560 match result {
2561 Ok(result) => {
2562 tx.send(result).ok();
2563 }
2564 Err(err) => {
2565 let rx = workspace.update_in(cx, |workspace, window, cx| {
2566 workspace.show_portal_error(err.to_string(), cx);
2567 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2568 let rx = prompt(workspace, lister, window, cx);
2569 workspace.on_prompt_for_open_path = Some(prompt);
2570 rx
2571 })?;
2572 if let Ok(path) = rx.await {
2573 tx.send(path).ok();
2574 }
2575 }
2576 };
2577 anyhow::Ok(())
2578 })
2579 .detach();
2580
2581 rx
2582 }
2583 }
2584
2585 pub fn prompt_for_new_path(
2586 &mut self,
2587 lister: DirectoryLister,
2588 suggested_name: Option<String>,
2589 window: &mut Window,
2590 cx: &mut Context<Self>,
2591 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2592 if self.project.read(cx).is_via_collab()
2593 || self.project.read(cx).is_via_remote_server()
2594 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2595 {
2596 let prompt = self.on_prompt_for_new_path.take().unwrap();
2597 let rx = prompt(self, lister, suggested_name, window, cx);
2598 self.on_prompt_for_new_path = Some(prompt);
2599 return rx;
2600 }
2601
2602 let (tx, rx) = oneshot::channel();
2603 cx.spawn_in(window, async move |workspace, cx| {
2604 let abs_path = workspace.update(cx, |workspace, cx| {
2605 let relative_to = workspace
2606 .most_recent_active_path(cx)
2607 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2608 .or_else(|| {
2609 let project = workspace.project.read(cx);
2610 project.visible_worktrees(cx).find_map(|worktree| {
2611 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2612 })
2613 })
2614 .or_else(std::env::home_dir)
2615 .unwrap_or_else(|| PathBuf::from(""));
2616 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2617 })?;
2618 let abs_path = match abs_path.await? {
2619 Ok(path) => path,
2620 Err(err) => {
2621 let rx = workspace.update_in(cx, |workspace, window, cx| {
2622 workspace.show_portal_error(err.to_string(), cx);
2623
2624 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2625 let rx = prompt(workspace, lister, suggested_name, window, cx);
2626 workspace.on_prompt_for_new_path = Some(prompt);
2627 rx
2628 })?;
2629 if let Ok(path) = rx.await {
2630 tx.send(path).ok();
2631 }
2632 return anyhow::Ok(());
2633 }
2634 };
2635
2636 tx.send(abs_path.map(|path| vec![path])).ok();
2637 anyhow::Ok(())
2638 })
2639 .detach();
2640
2641 rx
2642 }
2643
2644 pub fn titlebar_item(&self) -> Option<AnyView> {
2645 self.titlebar_item.clone()
2646 }
2647
2648 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2649 /// When set, git-related operations should use this worktree instead of deriving
2650 /// the active worktree from the focused file.
2651 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2652 self.active_worktree_override
2653 }
2654
2655 pub fn set_active_worktree_override(
2656 &mut self,
2657 worktree_id: Option<WorktreeId>,
2658 cx: &mut Context<Self>,
2659 ) {
2660 self.active_worktree_override = worktree_id;
2661 cx.notify();
2662 }
2663
2664 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2665 self.active_worktree_override = None;
2666 cx.notify();
2667 }
2668
2669 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2670 ///
2671 /// If the given workspace has a local project, then it will be passed
2672 /// to the callback. Otherwise, a new empty window will be created.
2673 pub fn with_local_workspace<T, F>(
2674 &mut self,
2675 window: &mut Window,
2676 cx: &mut Context<Self>,
2677 callback: F,
2678 ) -> Task<Result<T>>
2679 where
2680 T: 'static,
2681 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2682 {
2683 if self.project.read(cx).is_local() {
2684 Task::ready(Ok(callback(self, window, cx)))
2685 } else {
2686 let env = self.project.read(cx).cli_environment(cx);
2687 let task = Self::new_local(
2688 Vec::new(),
2689 self.app_state.clone(),
2690 None,
2691 env,
2692 None,
2693 true,
2694 cx,
2695 );
2696 cx.spawn_in(window, async move |_vh, cx| {
2697 let OpenResult {
2698 window: multi_workspace_window,
2699 ..
2700 } = task.await?;
2701 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2702 let workspace = multi_workspace.workspace().clone();
2703 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2704 })
2705 })
2706 }
2707 }
2708
2709 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2710 ///
2711 /// If the given workspace has a local project, then it will be passed
2712 /// to the callback. Otherwise, a new empty window will be created.
2713 pub fn with_local_or_wsl_workspace<T, F>(
2714 &mut self,
2715 window: &mut Window,
2716 cx: &mut Context<Self>,
2717 callback: F,
2718 ) -> Task<Result<T>>
2719 where
2720 T: 'static,
2721 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2722 {
2723 let project = self.project.read(cx);
2724 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
2725 Task::ready(Ok(callback(self, window, cx)))
2726 } else {
2727 let env = self.project.read(cx).cli_environment(cx);
2728 let task = Self::new_local(
2729 Vec::new(),
2730 self.app_state.clone(),
2731 None,
2732 env,
2733 None,
2734 true,
2735 cx,
2736 );
2737 cx.spawn_in(window, async move |_vh, cx| {
2738 let OpenResult {
2739 window: multi_workspace_window,
2740 ..
2741 } = task.await?;
2742 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2743 let workspace = multi_workspace.workspace().clone();
2744 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2745 })
2746 })
2747 }
2748 }
2749
2750 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2751 self.project.read(cx).worktrees(cx)
2752 }
2753
2754 pub fn visible_worktrees<'a>(
2755 &self,
2756 cx: &'a App,
2757 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2758 self.project.read(cx).visible_worktrees(cx)
2759 }
2760
2761 #[cfg(any(test, feature = "test-support"))]
2762 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
2763 let futures = self
2764 .worktrees(cx)
2765 .filter_map(|worktree| worktree.read(cx).as_local())
2766 .map(|worktree| worktree.scan_complete())
2767 .collect::<Vec<_>>();
2768 async move {
2769 for future in futures {
2770 future.await;
2771 }
2772 }
2773 }
2774
2775 pub fn close_global(cx: &mut App) {
2776 cx.defer(|cx| {
2777 cx.windows().iter().find(|window| {
2778 window
2779 .update(cx, |_, window, _| {
2780 if window.is_window_active() {
2781 //This can only get called when the window's project connection has been lost
2782 //so we don't need to prompt the user for anything and instead just close the window
2783 window.remove_window();
2784 true
2785 } else {
2786 false
2787 }
2788 })
2789 .unwrap_or(false)
2790 });
2791 });
2792 }
2793
2794 pub fn move_focused_panel_to_next_position(
2795 &mut self,
2796 _: &MoveFocusedPanelToNextPosition,
2797 window: &mut Window,
2798 cx: &mut Context<Self>,
2799 ) {
2800 let docks = self.all_docks();
2801 let active_dock = docks
2802 .into_iter()
2803 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
2804
2805 if let Some(dock) = active_dock {
2806 dock.update(cx, |dock, cx| {
2807 let active_panel = dock
2808 .active_panel()
2809 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
2810
2811 if let Some(panel) = active_panel {
2812 panel.move_to_next_position(window, cx);
2813 }
2814 })
2815 }
2816 }
2817
2818 pub fn prepare_to_close(
2819 &mut self,
2820 close_intent: CloseIntent,
2821 window: &mut Window,
2822 cx: &mut Context<Self>,
2823 ) -> Task<Result<bool>> {
2824 let active_call = self.active_global_call();
2825
2826 cx.spawn_in(window, async move |this, cx| {
2827 this.update(cx, |this, _| {
2828 if close_intent == CloseIntent::CloseWindow {
2829 this.removing = true;
2830 }
2831 })?;
2832
2833 let workspace_count = cx.update(|_window, cx| {
2834 cx.windows()
2835 .iter()
2836 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
2837 .count()
2838 })?;
2839
2840 #[cfg(target_os = "macos")]
2841 let save_last_workspace = false;
2842
2843 // On Linux and Windows, closing the last window should restore the last workspace.
2844 #[cfg(not(target_os = "macos"))]
2845 let save_last_workspace = {
2846 let remaining_workspaces = cx.update(|_window, cx| {
2847 cx.windows()
2848 .iter()
2849 .filter_map(|window| window.downcast::<MultiWorkspace>())
2850 .filter_map(|multi_workspace| {
2851 multi_workspace
2852 .update(cx, |multi_workspace, _, cx| {
2853 multi_workspace.workspace().read(cx).removing
2854 })
2855 .ok()
2856 })
2857 .filter(|removing| !removing)
2858 .count()
2859 })?;
2860
2861 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
2862 };
2863
2864 if let Some(active_call) = active_call
2865 && workspace_count == 1
2866 && cx
2867 .update(|_window, cx| active_call.0.is_in_room(cx))
2868 .unwrap_or(false)
2869 {
2870 if close_intent == CloseIntent::CloseWindow {
2871 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
2872 let answer = cx.update(|window, cx| {
2873 window.prompt(
2874 PromptLevel::Warning,
2875 "Do you want to leave the current call?",
2876 None,
2877 &["Close window and hang up", "Cancel"],
2878 cx,
2879 )
2880 })?;
2881
2882 if answer.await.log_err() == Some(1) {
2883 return anyhow::Ok(false);
2884 } else {
2885 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
2886 task.await.log_err();
2887 }
2888 }
2889 }
2890 if close_intent == CloseIntent::ReplaceWindow {
2891 _ = cx.update(|_window, cx| {
2892 let multi_workspace = cx
2893 .windows()
2894 .iter()
2895 .filter_map(|window| window.downcast::<MultiWorkspace>())
2896 .next()
2897 .unwrap();
2898 let project = multi_workspace
2899 .read(cx)?
2900 .workspace()
2901 .read(cx)
2902 .project
2903 .clone();
2904 if project.read(cx).is_shared() {
2905 active_call.0.unshare_project(project, cx)?;
2906 }
2907 Ok::<_, anyhow::Error>(())
2908 });
2909 }
2910 }
2911
2912 let save_result = this
2913 .update_in(cx, |this, window, cx| {
2914 this.save_all_internal(SaveIntent::Close, window, cx)
2915 })?
2916 .await;
2917
2918 // If we're not quitting, but closing, we remove the workspace from
2919 // the current session.
2920 if close_intent != CloseIntent::Quit
2921 && !save_last_workspace
2922 && save_result.as_ref().is_ok_and(|&res| res)
2923 {
2924 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
2925 .await;
2926 }
2927
2928 save_result
2929 })
2930 }
2931
2932 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
2933 self.save_all_internal(
2934 action.save_intent.unwrap_or(SaveIntent::SaveAll),
2935 window,
2936 cx,
2937 )
2938 .detach_and_log_err(cx);
2939 }
2940
2941 fn send_keystrokes(
2942 &mut self,
2943 action: &SendKeystrokes,
2944 window: &mut Window,
2945 cx: &mut Context<Self>,
2946 ) {
2947 let keystrokes: Vec<Keystroke> = action
2948 .0
2949 .split(' ')
2950 .flat_map(|k| Keystroke::parse(k).log_err())
2951 .map(|k| {
2952 cx.keyboard_mapper()
2953 .map_key_equivalent(k, false)
2954 .inner()
2955 .clone()
2956 })
2957 .collect();
2958 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
2959 }
2960
2961 pub fn send_keystrokes_impl(
2962 &mut self,
2963 keystrokes: Vec<Keystroke>,
2964 window: &mut Window,
2965 cx: &mut Context<Self>,
2966 ) -> Shared<Task<()>> {
2967 let mut state = self.dispatching_keystrokes.borrow_mut();
2968 if !state.dispatched.insert(keystrokes.clone()) {
2969 cx.propagate();
2970 return state.task.clone().unwrap();
2971 }
2972
2973 state.queue.extend(keystrokes);
2974
2975 let keystrokes = self.dispatching_keystrokes.clone();
2976 if state.task.is_none() {
2977 state.task = Some(
2978 window
2979 .spawn(cx, async move |cx| {
2980 // limit to 100 keystrokes to avoid infinite recursion.
2981 for _ in 0..100 {
2982 let keystroke = {
2983 let mut state = keystrokes.borrow_mut();
2984 let Some(keystroke) = state.queue.pop_front() else {
2985 state.dispatched.clear();
2986 state.task.take();
2987 return;
2988 };
2989 keystroke
2990 };
2991 cx.update(|window, cx| {
2992 let focused = window.focused(cx);
2993 window.dispatch_keystroke(keystroke.clone(), cx);
2994 if window.focused(cx) != focused {
2995 // dispatch_keystroke may cause the focus to change.
2996 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
2997 // And we need that to happen before the next keystroke to keep vim mode happy...
2998 // (Note that the tests always do this implicitly, so you must manually test with something like:
2999 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
3000 // )
3001 window.draw(cx).clear();
3002 }
3003 })
3004 .ok();
3005
3006 // Yield between synthetic keystrokes so deferred focus and
3007 // other effects can settle before dispatching the next key.
3008 yield_now().await;
3009 }
3010
3011 *keystrokes.borrow_mut() = Default::default();
3012 log::error!("over 100 keystrokes passed to send_keystrokes");
3013 })
3014 .shared(),
3015 );
3016 }
3017 state.task.clone().unwrap()
3018 }
3019
3020 fn save_all_internal(
3021 &mut self,
3022 mut save_intent: SaveIntent,
3023 window: &mut Window,
3024 cx: &mut Context<Self>,
3025 ) -> Task<Result<bool>> {
3026 if self.project.read(cx).is_disconnected(cx) {
3027 return Task::ready(Ok(true));
3028 }
3029 let dirty_items = self
3030 .panes
3031 .iter()
3032 .flat_map(|pane| {
3033 pane.read(cx).items().filter_map(|item| {
3034 if item.is_dirty(cx) {
3035 item.tab_content_text(0, cx);
3036 Some((pane.downgrade(), item.boxed_clone()))
3037 } else {
3038 None
3039 }
3040 })
3041 })
3042 .collect::<Vec<_>>();
3043
3044 let project = self.project.clone();
3045 cx.spawn_in(window, async move |workspace, cx| {
3046 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3047 let (serialize_tasks, remaining_dirty_items) =
3048 workspace.update_in(cx, |workspace, window, cx| {
3049 let mut remaining_dirty_items = Vec::new();
3050 let mut serialize_tasks = Vec::new();
3051 for (pane, item) in dirty_items {
3052 if let Some(task) = item
3053 .to_serializable_item_handle(cx)
3054 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3055 {
3056 serialize_tasks.push(task);
3057 } else {
3058 remaining_dirty_items.push((pane, item));
3059 }
3060 }
3061 (serialize_tasks, remaining_dirty_items)
3062 })?;
3063
3064 futures::future::try_join_all(serialize_tasks).await?;
3065
3066 if !remaining_dirty_items.is_empty() {
3067 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3068 }
3069
3070 if remaining_dirty_items.len() > 1 {
3071 let answer = workspace.update_in(cx, |_, window, cx| {
3072 let detail = Pane::file_names_for_prompt(
3073 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3074 cx,
3075 );
3076 window.prompt(
3077 PromptLevel::Warning,
3078 "Do you want to save all changes in the following files?",
3079 Some(&detail),
3080 &["Save all", "Discard all", "Cancel"],
3081 cx,
3082 )
3083 })?;
3084 match answer.await.log_err() {
3085 Some(0) => save_intent = SaveIntent::SaveAll,
3086 Some(1) => save_intent = SaveIntent::Skip,
3087 Some(2) => return Ok(false),
3088 _ => {}
3089 }
3090 }
3091
3092 remaining_dirty_items
3093 } else {
3094 dirty_items
3095 };
3096
3097 for (pane, item) in dirty_items {
3098 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3099 (
3100 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3101 item.project_entry_ids(cx),
3102 )
3103 })?;
3104 if (singleton || !project_entry_ids.is_empty())
3105 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3106 {
3107 return Ok(false);
3108 }
3109 }
3110 Ok(true)
3111 })
3112 }
3113
3114 pub fn open_workspace_for_paths(
3115 &mut self,
3116 replace_current_window: bool,
3117 paths: Vec<PathBuf>,
3118 window: &mut Window,
3119 cx: &mut Context<Self>,
3120 ) -> Task<Result<Entity<Workspace>>> {
3121 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
3122 let is_remote = self.project.read(cx).is_via_collab();
3123 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3124 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3125
3126 let window_to_replace = if replace_current_window {
3127 window_handle
3128 } else if is_remote || has_worktree || has_dirty_items {
3129 None
3130 } else {
3131 window_handle
3132 };
3133 let app_state = self.app_state.clone();
3134
3135 cx.spawn(async move |_, cx| {
3136 let OpenResult { workspace, .. } = cx
3137 .update(|cx| {
3138 open_paths(
3139 &paths,
3140 app_state,
3141 OpenOptions {
3142 replace_window: window_to_replace,
3143 ..Default::default()
3144 },
3145 cx,
3146 )
3147 })
3148 .await?;
3149 Ok(workspace)
3150 })
3151 }
3152
3153 #[allow(clippy::type_complexity)]
3154 pub fn open_paths(
3155 &mut self,
3156 mut abs_paths: Vec<PathBuf>,
3157 options: OpenOptions,
3158 pane: Option<WeakEntity<Pane>>,
3159 window: &mut Window,
3160 cx: &mut Context<Self>,
3161 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3162 let fs = self.app_state.fs.clone();
3163
3164 let caller_ordered_abs_paths = abs_paths.clone();
3165
3166 // Sort the paths to ensure we add worktrees for parents before their children.
3167 abs_paths.sort_unstable();
3168 cx.spawn_in(window, async move |this, cx| {
3169 let mut tasks = Vec::with_capacity(abs_paths.len());
3170
3171 for abs_path in &abs_paths {
3172 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3173 OpenVisible::All => Some(true),
3174 OpenVisible::None => Some(false),
3175 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3176 Some(Some(metadata)) => Some(!metadata.is_dir),
3177 Some(None) => Some(true),
3178 None => None,
3179 },
3180 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3181 Some(Some(metadata)) => Some(metadata.is_dir),
3182 Some(None) => Some(false),
3183 None => None,
3184 },
3185 };
3186 let project_path = match visible {
3187 Some(visible) => match this
3188 .update(cx, |this, cx| {
3189 Workspace::project_path_for_path(
3190 this.project.clone(),
3191 abs_path,
3192 visible,
3193 cx,
3194 )
3195 })
3196 .log_err()
3197 {
3198 Some(project_path) => project_path.await.log_err(),
3199 None => None,
3200 },
3201 None => None,
3202 };
3203
3204 let this = this.clone();
3205 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3206 let fs = fs.clone();
3207 let pane = pane.clone();
3208 let task = cx.spawn(async move |cx| {
3209 let (_worktree, project_path) = project_path?;
3210 if fs.is_dir(&abs_path).await {
3211 // Opening a directory should not race to update the active entry.
3212 // We'll select/reveal a deterministic final entry after all paths finish opening.
3213 None
3214 } else {
3215 Some(
3216 this.update_in(cx, |this, window, cx| {
3217 this.open_path(
3218 project_path,
3219 pane,
3220 options.focus.unwrap_or(true),
3221 window,
3222 cx,
3223 )
3224 })
3225 .ok()?
3226 .await,
3227 )
3228 }
3229 });
3230 tasks.push(task);
3231 }
3232
3233 let results = futures::future::join_all(tasks).await;
3234
3235 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3236 let mut winner: Option<(PathBuf, bool)> = None;
3237 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3238 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3239 if !metadata.is_dir {
3240 winner = Some((abs_path, false));
3241 break;
3242 }
3243 if winner.is_none() {
3244 winner = Some((abs_path, true));
3245 }
3246 } else if winner.is_none() {
3247 winner = Some((abs_path, false));
3248 }
3249 }
3250
3251 // Compute the winner entry id on the foreground thread and emit once, after all
3252 // paths finish opening. This avoids races between concurrently-opening paths
3253 // (directories in particular) and makes the resulting project panel selection
3254 // deterministic.
3255 if let Some((winner_abs_path, winner_is_dir)) = winner {
3256 'emit_winner: {
3257 let winner_abs_path: Arc<Path> =
3258 SanitizedPath::new(&winner_abs_path).as_path().into();
3259
3260 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3261 OpenVisible::All => true,
3262 OpenVisible::None => false,
3263 OpenVisible::OnlyFiles => !winner_is_dir,
3264 OpenVisible::OnlyDirectories => winner_is_dir,
3265 };
3266
3267 let Some(worktree_task) = this
3268 .update(cx, |workspace, cx| {
3269 workspace.project.update(cx, |project, cx| {
3270 project.find_or_create_worktree(
3271 winner_abs_path.as_ref(),
3272 visible,
3273 cx,
3274 )
3275 })
3276 })
3277 .ok()
3278 else {
3279 break 'emit_winner;
3280 };
3281
3282 let Ok((worktree, _)) = worktree_task.await else {
3283 break 'emit_winner;
3284 };
3285
3286 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3287 let worktree = worktree.read(cx);
3288 let worktree_abs_path = worktree.abs_path();
3289 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3290 worktree.root_entry()
3291 } else {
3292 winner_abs_path
3293 .strip_prefix(worktree_abs_path.as_ref())
3294 .ok()
3295 .and_then(|relative_path| {
3296 let relative_path =
3297 RelPath::new(relative_path, PathStyle::local())
3298 .log_err()?;
3299 worktree.entry_for_path(&relative_path)
3300 })
3301 }?;
3302 Some(entry.id)
3303 }) else {
3304 break 'emit_winner;
3305 };
3306
3307 this.update(cx, |workspace, cx| {
3308 workspace.project.update(cx, |_, cx| {
3309 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3310 });
3311 })
3312 .ok();
3313 }
3314 }
3315
3316 results
3317 })
3318 }
3319
3320 pub fn open_resolved_path(
3321 &mut self,
3322 path: ResolvedPath,
3323 window: &mut Window,
3324 cx: &mut Context<Self>,
3325 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3326 match path {
3327 ResolvedPath::ProjectPath { project_path, .. } => {
3328 self.open_path(project_path, None, true, window, cx)
3329 }
3330 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3331 PathBuf::from(path),
3332 OpenOptions {
3333 visible: Some(OpenVisible::None),
3334 ..Default::default()
3335 },
3336 window,
3337 cx,
3338 ),
3339 }
3340 }
3341
3342 pub fn absolute_path_of_worktree(
3343 &self,
3344 worktree_id: WorktreeId,
3345 cx: &mut Context<Self>,
3346 ) -> Option<PathBuf> {
3347 self.project
3348 .read(cx)
3349 .worktree_for_id(worktree_id, cx)
3350 // TODO: use `abs_path` or `root_dir`
3351 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3352 }
3353
3354 fn add_folder_to_project(
3355 &mut self,
3356 _: &AddFolderToProject,
3357 window: &mut Window,
3358 cx: &mut Context<Self>,
3359 ) {
3360 let project = self.project.read(cx);
3361 if project.is_via_collab() {
3362 self.show_error(
3363 &anyhow!("You cannot add folders to someone else's project"),
3364 cx,
3365 );
3366 return;
3367 }
3368 let paths = self.prompt_for_open_path(
3369 PathPromptOptions {
3370 files: false,
3371 directories: true,
3372 multiple: true,
3373 prompt: None,
3374 },
3375 DirectoryLister::Project(self.project.clone()),
3376 window,
3377 cx,
3378 );
3379 cx.spawn_in(window, async move |this, cx| {
3380 if let Some(paths) = paths.await.log_err().flatten() {
3381 let results = this
3382 .update_in(cx, |this, window, cx| {
3383 this.open_paths(
3384 paths,
3385 OpenOptions {
3386 visible: Some(OpenVisible::All),
3387 ..Default::default()
3388 },
3389 None,
3390 window,
3391 cx,
3392 )
3393 })?
3394 .await;
3395 for result in results.into_iter().flatten() {
3396 result.log_err();
3397 }
3398 }
3399 anyhow::Ok(())
3400 })
3401 .detach_and_log_err(cx);
3402 }
3403
3404 pub fn project_path_for_path(
3405 project: Entity<Project>,
3406 abs_path: &Path,
3407 visible: bool,
3408 cx: &mut App,
3409 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3410 let entry = project.update(cx, |project, cx| {
3411 project.find_or_create_worktree(abs_path, visible, cx)
3412 });
3413 cx.spawn(async move |cx| {
3414 let (worktree, path) = entry.await?;
3415 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3416 Ok((worktree, ProjectPath { worktree_id, path }))
3417 })
3418 }
3419
3420 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3421 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3422 }
3423
3424 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3425 self.items_of_type(cx).max_by_key(|item| item.item_id())
3426 }
3427
3428 pub fn items_of_type<'a, T: Item>(
3429 &'a self,
3430 cx: &'a App,
3431 ) -> impl 'a + Iterator<Item = Entity<T>> {
3432 self.panes
3433 .iter()
3434 .flat_map(|pane| pane.read(cx).items_of_type())
3435 }
3436
3437 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3438 self.active_pane().read(cx).active_item()
3439 }
3440
3441 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3442 let item = self.active_item(cx)?;
3443 item.to_any_view().downcast::<I>().ok()
3444 }
3445
3446 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3447 self.active_item(cx).and_then(|item| item.project_path(cx))
3448 }
3449
3450 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3451 self.recent_navigation_history_iter(cx)
3452 .filter_map(|(path, abs_path)| {
3453 let worktree = self
3454 .project
3455 .read(cx)
3456 .worktree_for_id(path.worktree_id, cx)?;
3457 if worktree.read(cx).is_visible() {
3458 abs_path
3459 } else {
3460 None
3461 }
3462 })
3463 .next()
3464 }
3465
3466 pub fn save_active_item(
3467 &mut self,
3468 save_intent: SaveIntent,
3469 window: &mut Window,
3470 cx: &mut App,
3471 ) -> Task<Result<()>> {
3472 let project = self.project.clone();
3473 let pane = self.active_pane();
3474 let item = pane.read(cx).active_item();
3475 let pane = pane.downgrade();
3476
3477 window.spawn(cx, async move |cx| {
3478 if let Some(item) = item {
3479 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3480 .await
3481 .map(|_| ())
3482 } else {
3483 Ok(())
3484 }
3485 })
3486 }
3487
3488 pub fn close_inactive_items_and_panes(
3489 &mut self,
3490 action: &CloseInactiveTabsAndPanes,
3491 window: &mut Window,
3492 cx: &mut Context<Self>,
3493 ) {
3494 if let Some(task) = self.close_all_internal(
3495 true,
3496 action.save_intent.unwrap_or(SaveIntent::Close),
3497 window,
3498 cx,
3499 ) {
3500 task.detach_and_log_err(cx)
3501 }
3502 }
3503
3504 pub fn close_all_items_and_panes(
3505 &mut self,
3506 action: &CloseAllItemsAndPanes,
3507 window: &mut Window,
3508 cx: &mut Context<Self>,
3509 ) {
3510 if let Some(task) = self.close_all_internal(
3511 false,
3512 action.save_intent.unwrap_or(SaveIntent::Close),
3513 window,
3514 cx,
3515 ) {
3516 task.detach_and_log_err(cx)
3517 }
3518 }
3519
3520 /// Closes the active item across all panes.
3521 pub fn close_item_in_all_panes(
3522 &mut self,
3523 action: &CloseItemInAllPanes,
3524 window: &mut Window,
3525 cx: &mut Context<Self>,
3526 ) {
3527 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3528 return;
3529 };
3530
3531 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3532 let close_pinned = action.close_pinned;
3533
3534 if let Some(project_path) = active_item.project_path(cx) {
3535 self.close_items_with_project_path(
3536 &project_path,
3537 save_intent,
3538 close_pinned,
3539 window,
3540 cx,
3541 );
3542 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3543 let item_id = active_item.item_id();
3544 self.active_pane().update(cx, |pane, cx| {
3545 pane.close_item_by_id(item_id, save_intent, window, cx)
3546 .detach_and_log_err(cx);
3547 });
3548 }
3549 }
3550
3551 /// Closes all items with the given project path across all panes.
3552 pub fn close_items_with_project_path(
3553 &mut self,
3554 project_path: &ProjectPath,
3555 save_intent: SaveIntent,
3556 close_pinned: bool,
3557 window: &mut Window,
3558 cx: &mut Context<Self>,
3559 ) {
3560 let panes = self.panes().to_vec();
3561 for pane in panes {
3562 pane.update(cx, |pane, cx| {
3563 pane.close_items_for_project_path(
3564 project_path,
3565 save_intent,
3566 close_pinned,
3567 window,
3568 cx,
3569 )
3570 .detach_and_log_err(cx);
3571 });
3572 }
3573 }
3574
3575 fn close_all_internal(
3576 &mut self,
3577 retain_active_pane: bool,
3578 save_intent: SaveIntent,
3579 window: &mut Window,
3580 cx: &mut Context<Self>,
3581 ) -> Option<Task<Result<()>>> {
3582 let current_pane = self.active_pane();
3583
3584 let mut tasks = Vec::new();
3585
3586 if retain_active_pane {
3587 let current_pane_close = current_pane.update(cx, |pane, cx| {
3588 pane.close_other_items(
3589 &CloseOtherItems {
3590 save_intent: None,
3591 close_pinned: false,
3592 },
3593 None,
3594 window,
3595 cx,
3596 )
3597 });
3598
3599 tasks.push(current_pane_close);
3600 }
3601
3602 for pane in self.panes() {
3603 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3604 continue;
3605 }
3606
3607 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3608 pane.close_all_items(
3609 &CloseAllItems {
3610 save_intent: Some(save_intent),
3611 close_pinned: false,
3612 },
3613 window,
3614 cx,
3615 )
3616 });
3617
3618 tasks.push(close_pane_items)
3619 }
3620
3621 if tasks.is_empty() {
3622 None
3623 } else {
3624 Some(cx.spawn_in(window, async move |_, _| {
3625 for task in tasks {
3626 task.await?
3627 }
3628 Ok(())
3629 }))
3630 }
3631 }
3632
3633 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3634 self.dock_at_position(position).read(cx).is_open()
3635 }
3636
3637 pub fn toggle_dock(
3638 &mut self,
3639 dock_side: DockPosition,
3640 window: &mut Window,
3641 cx: &mut Context<Self>,
3642 ) {
3643 let mut focus_center = false;
3644 let mut reveal_dock = false;
3645
3646 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3647 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3648
3649 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3650 telemetry::event!(
3651 "Panel Button Clicked",
3652 name = panel.persistent_name(),
3653 toggle_state = !was_visible
3654 );
3655 }
3656 if was_visible {
3657 self.save_open_dock_positions(cx);
3658 }
3659
3660 let dock = self.dock_at_position(dock_side);
3661 dock.update(cx, |dock, cx| {
3662 dock.set_open(!was_visible, window, cx);
3663
3664 if dock.active_panel().is_none() {
3665 let Some(panel_ix) = dock
3666 .first_enabled_panel_idx(cx)
3667 .log_with_level(log::Level::Info)
3668 else {
3669 return;
3670 };
3671 dock.activate_panel(panel_ix, window, cx);
3672 }
3673
3674 if let Some(active_panel) = dock.active_panel() {
3675 if was_visible {
3676 if active_panel
3677 .panel_focus_handle(cx)
3678 .contains_focused(window, cx)
3679 {
3680 focus_center = true;
3681 }
3682 } else {
3683 let focus_handle = &active_panel.panel_focus_handle(cx);
3684 window.focus(focus_handle, cx);
3685 reveal_dock = true;
3686 }
3687 }
3688 });
3689
3690 if reveal_dock {
3691 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3692 }
3693
3694 if focus_center {
3695 self.active_pane
3696 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3697 }
3698
3699 cx.notify();
3700 self.serialize_workspace(window, cx);
3701 }
3702
3703 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3704 self.all_docks().into_iter().find(|&dock| {
3705 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3706 })
3707 }
3708
3709 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3710 if let Some(dock) = self.active_dock(window, cx).cloned() {
3711 self.save_open_dock_positions(cx);
3712 dock.update(cx, |dock, cx| {
3713 dock.set_open(false, window, cx);
3714 });
3715 return true;
3716 }
3717 false
3718 }
3719
3720 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3721 self.save_open_dock_positions(cx);
3722 for dock in self.all_docks() {
3723 dock.update(cx, |dock, cx| {
3724 dock.set_open(false, window, cx);
3725 });
3726 }
3727
3728 cx.focus_self(window);
3729 cx.notify();
3730 self.serialize_workspace(window, cx);
3731 }
3732
3733 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
3734 self.all_docks()
3735 .into_iter()
3736 .filter_map(|dock| {
3737 let dock_ref = dock.read(cx);
3738 if dock_ref.is_open() {
3739 Some(dock_ref.position())
3740 } else {
3741 None
3742 }
3743 })
3744 .collect()
3745 }
3746
3747 /// Saves the positions of currently open docks.
3748 ///
3749 /// Updates `last_open_dock_positions` with positions of all currently open
3750 /// docks, to later be restored by the 'Toggle All Docks' action.
3751 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
3752 let open_dock_positions = self.get_open_dock_positions(cx);
3753 if !open_dock_positions.is_empty() {
3754 self.last_open_dock_positions = open_dock_positions;
3755 }
3756 }
3757
3758 /// Toggles all docks between open and closed states.
3759 ///
3760 /// If any docks are open, closes all and remembers their positions. If all
3761 /// docks are closed, restores the last remembered dock configuration.
3762 fn toggle_all_docks(
3763 &mut self,
3764 _: &ToggleAllDocks,
3765 window: &mut Window,
3766 cx: &mut Context<Self>,
3767 ) {
3768 let open_dock_positions = self.get_open_dock_positions(cx);
3769
3770 if !open_dock_positions.is_empty() {
3771 self.close_all_docks(window, cx);
3772 } else if !self.last_open_dock_positions.is_empty() {
3773 self.restore_last_open_docks(window, cx);
3774 }
3775 }
3776
3777 /// Reopens docks from the most recently remembered configuration.
3778 ///
3779 /// Opens all docks whose positions are stored in `last_open_dock_positions`
3780 /// and clears the stored positions.
3781 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3782 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
3783
3784 for position in positions_to_open {
3785 let dock = self.dock_at_position(position);
3786 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
3787 }
3788
3789 cx.focus_self(window);
3790 cx.notify();
3791 self.serialize_workspace(window, cx);
3792 }
3793
3794 /// Transfer focus to the panel of the given type.
3795 pub fn focus_panel<T: Panel>(
3796 &mut self,
3797 window: &mut Window,
3798 cx: &mut Context<Self>,
3799 ) -> Option<Entity<T>> {
3800 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
3801 panel.to_any().downcast().ok()
3802 }
3803
3804 /// Focus the panel of the given type if it isn't already focused. If it is
3805 /// already focused, then transfer focus back to the workspace center.
3806 /// When the `close_panel_on_toggle` setting is enabled, also closes the
3807 /// panel when transferring focus back to the center.
3808 pub fn toggle_panel_focus<T: Panel>(
3809 &mut self,
3810 window: &mut Window,
3811 cx: &mut Context<Self>,
3812 ) -> bool {
3813 let mut did_focus_panel = false;
3814 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
3815 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
3816 did_focus_panel
3817 });
3818
3819 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
3820 self.close_panel::<T>(window, cx);
3821 }
3822
3823 telemetry::event!(
3824 "Panel Button Clicked",
3825 name = T::persistent_name(),
3826 toggle_state = did_focus_panel
3827 );
3828
3829 did_focus_panel
3830 }
3831
3832 pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3833 if let Some(item) = self.active_item(cx) {
3834 item.item_focus_handle(cx).focus(window, cx);
3835 } else {
3836 log::error!("Could not find a focus target when switching focus to the center panes",);
3837 }
3838 }
3839
3840 pub fn activate_panel_for_proto_id(
3841 &mut self,
3842 panel_id: PanelId,
3843 window: &mut Window,
3844 cx: &mut Context<Self>,
3845 ) -> Option<Arc<dyn PanelHandle>> {
3846 let mut panel = None;
3847 for dock in self.all_docks() {
3848 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
3849 panel = dock.update(cx, |dock, cx| {
3850 dock.activate_panel(panel_index, window, cx);
3851 dock.set_open(true, window, cx);
3852 dock.active_panel().cloned()
3853 });
3854 break;
3855 }
3856 }
3857
3858 if panel.is_some() {
3859 cx.notify();
3860 self.serialize_workspace(window, cx);
3861 }
3862
3863 panel
3864 }
3865
3866 /// Focus or unfocus the given panel type, depending on the given callback.
3867 fn focus_or_unfocus_panel<T: Panel>(
3868 &mut self,
3869 window: &mut Window,
3870 cx: &mut Context<Self>,
3871 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
3872 ) -> Option<Arc<dyn PanelHandle>> {
3873 let mut result_panel = None;
3874 let mut serialize = false;
3875 for dock in self.all_docks() {
3876 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3877 let mut focus_center = false;
3878 let panel = dock.update(cx, |dock, cx| {
3879 dock.activate_panel(panel_index, window, cx);
3880
3881 let panel = dock.active_panel().cloned();
3882 if let Some(panel) = panel.as_ref() {
3883 if should_focus(&**panel, window, cx) {
3884 dock.set_open(true, window, cx);
3885 panel.panel_focus_handle(cx).focus(window, cx);
3886 } else {
3887 focus_center = true;
3888 }
3889 }
3890 panel
3891 });
3892
3893 if focus_center {
3894 self.active_pane
3895 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3896 }
3897
3898 result_panel = panel;
3899 serialize = true;
3900 break;
3901 }
3902 }
3903
3904 if serialize {
3905 self.serialize_workspace(window, cx);
3906 }
3907
3908 cx.notify();
3909 result_panel
3910 }
3911
3912 /// Open the panel of the given type
3913 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3914 for dock in self.all_docks() {
3915 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3916 dock.update(cx, |dock, cx| {
3917 dock.activate_panel(panel_index, window, cx);
3918 dock.set_open(true, window, cx);
3919 });
3920 }
3921 }
3922 }
3923
3924 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
3925 for dock in self.all_docks().iter() {
3926 dock.update(cx, |dock, cx| {
3927 if dock.panel::<T>().is_some() {
3928 dock.set_open(false, window, cx)
3929 }
3930 })
3931 }
3932 }
3933
3934 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
3935 self.all_docks()
3936 .iter()
3937 .find_map(|dock| dock.read(cx).panel::<T>())
3938 }
3939
3940 fn dismiss_zoomed_items_to_reveal(
3941 &mut self,
3942 dock_to_reveal: Option<DockPosition>,
3943 window: &mut Window,
3944 cx: &mut Context<Self>,
3945 ) {
3946 // If a center pane is zoomed, unzoom it.
3947 for pane in &self.panes {
3948 if pane != &self.active_pane || dock_to_reveal.is_some() {
3949 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
3950 }
3951 }
3952
3953 // If another dock is zoomed, hide it.
3954 let mut focus_center = false;
3955 for dock in self.all_docks() {
3956 dock.update(cx, |dock, cx| {
3957 if Some(dock.position()) != dock_to_reveal
3958 && let Some(panel) = dock.active_panel()
3959 && panel.is_zoomed(window, cx)
3960 {
3961 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
3962 dock.set_open(false, window, cx);
3963 }
3964 });
3965 }
3966
3967 if focus_center {
3968 self.active_pane
3969 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3970 }
3971
3972 if self.zoomed_position != dock_to_reveal {
3973 self.zoomed = None;
3974 self.zoomed_position = None;
3975 cx.emit(Event::ZoomChanged);
3976 }
3977
3978 cx.notify();
3979 }
3980
3981 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
3982 let pane = cx.new(|cx| {
3983 let mut pane = Pane::new(
3984 self.weak_handle(),
3985 self.project.clone(),
3986 self.pane_history_timestamp.clone(),
3987 None,
3988 NewFile.boxed_clone(),
3989 true,
3990 window,
3991 cx,
3992 );
3993 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
3994 pane
3995 });
3996 cx.subscribe_in(&pane, window, Self::handle_pane_event)
3997 .detach();
3998 self.panes.push(pane.clone());
3999
4000 window.focus(&pane.focus_handle(cx), cx);
4001
4002 cx.emit(Event::PaneAdded(pane.clone()));
4003 pane
4004 }
4005
4006 pub fn add_item_to_center(
4007 &mut self,
4008 item: Box<dyn ItemHandle>,
4009 window: &mut Window,
4010 cx: &mut Context<Self>,
4011 ) -> bool {
4012 if let Some(center_pane) = self.last_active_center_pane.clone() {
4013 if let Some(center_pane) = center_pane.upgrade() {
4014 center_pane.update(cx, |pane, cx| {
4015 pane.add_item(item, true, true, None, window, cx)
4016 });
4017 true
4018 } else {
4019 false
4020 }
4021 } else {
4022 false
4023 }
4024 }
4025
4026 pub fn add_item_to_active_pane(
4027 &mut self,
4028 item: Box<dyn ItemHandle>,
4029 destination_index: Option<usize>,
4030 focus_item: bool,
4031 window: &mut Window,
4032 cx: &mut App,
4033 ) {
4034 self.add_item(
4035 self.active_pane.clone(),
4036 item,
4037 destination_index,
4038 false,
4039 focus_item,
4040 window,
4041 cx,
4042 )
4043 }
4044
4045 pub fn add_item(
4046 &mut self,
4047 pane: Entity<Pane>,
4048 item: Box<dyn ItemHandle>,
4049 destination_index: Option<usize>,
4050 activate_pane: bool,
4051 focus_item: bool,
4052 window: &mut Window,
4053 cx: &mut App,
4054 ) {
4055 pane.update(cx, |pane, cx| {
4056 pane.add_item(
4057 item,
4058 activate_pane,
4059 focus_item,
4060 destination_index,
4061 window,
4062 cx,
4063 )
4064 });
4065 }
4066
4067 pub fn split_item(
4068 &mut self,
4069 split_direction: SplitDirection,
4070 item: Box<dyn ItemHandle>,
4071 window: &mut Window,
4072 cx: &mut Context<Self>,
4073 ) {
4074 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4075 self.add_item(new_pane, item, None, true, true, window, cx);
4076 }
4077
4078 pub fn open_abs_path(
4079 &mut self,
4080 abs_path: PathBuf,
4081 options: OpenOptions,
4082 window: &mut Window,
4083 cx: &mut Context<Self>,
4084 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4085 cx.spawn_in(window, async move |workspace, cx| {
4086 let open_paths_task_result = workspace
4087 .update_in(cx, |workspace, window, cx| {
4088 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4089 })
4090 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4091 .await;
4092 anyhow::ensure!(
4093 open_paths_task_result.len() == 1,
4094 "open abs path {abs_path:?} task returned incorrect number of results"
4095 );
4096 match open_paths_task_result
4097 .into_iter()
4098 .next()
4099 .expect("ensured single task result")
4100 {
4101 Some(open_result) => {
4102 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4103 }
4104 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4105 }
4106 })
4107 }
4108
4109 pub fn split_abs_path(
4110 &mut self,
4111 abs_path: PathBuf,
4112 visible: bool,
4113 window: &mut Window,
4114 cx: &mut Context<Self>,
4115 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4116 let project_path_task =
4117 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4118 cx.spawn_in(window, async move |this, cx| {
4119 let (_, path) = project_path_task.await?;
4120 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4121 .await
4122 })
4123 }
4124
4125 pub fn open_path(
4126 &mut self,
4127 path: impl Into<ProjectPath>,
4128 pane: Option<WeakEntity<Pane>>,
4129 focus_item: bool,
4130 window: &mut Window,
4131 cx: &mut App,
4132 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4133 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4134 }
4135
4136 pub fn open_path_preview(
4137 &mut self,
4138 path: impl Into<ProjectPath>,
4139 pane: Option<WeakEntity<Pane>>,
4140 focus_item: bool,
4141 allow_preview: bool,
4142 activate: bool,
4143 window: &mut Window,
4144 cx: &mut App,
4145 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4146 let pane = pane.unwrap_or_else(|| {
4147 self.last_active_center_pane.clone().unwrap_or_else(|| {
4148 self.panes
4149 .first()
4150 .expect("There must be an active pane")
4151 .downgrade()
4152 })
4153 });
4154
4155 let project_path = path.into();
4156 let task = self.load_path(project_path.clone(), window, cx);
4157 window.spawn(cx, async move |cx| {
4158 let (project_entry_id, build_item) = task.await?;
4159
4160 pane.update_in(cx, |pane, window, cx| {
4161 pane.open_item(
4162 project_entry_id,
4163 project_path,
4164 focus_item,
4165 allow_preview,
4166 activate,
4167 None,
4168 window,
4169 cx,
4170 build_item,
4171 )
4172 })
4173 })
4174 }
4175
4176 pub fn split_path(
4177 &mut self,
4178 path: impl Into<ProjectPath>,
4179 window: &mut Window,
4180 cx: &mut Context<Self>,
4181 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4182 self.split_path_preview(path, false, None, window, cx)
4183 }
4184
4185 pub fn split_path_preview(
4186 &mut self,
4187 path: impl Into<ProjectPath>,
4188 allow_preview: bool,
4189 split_direction: Option<SplitDirection>,
4190 window: &mut Window,
4191 cx: &mut Context<Self>,
4192 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4193 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4194 self.panes
4195 .first()
4196 .expect("There must be an active pane")
4197 .downgrade()
4198 });
4199
4200 if let Member::Pane(center_pane) = &self.center.root
4201 && center_pane.read(cx).items_len() == 0
4202 {
4203 return self.open_path(path, Some(pane), true, window, cx);
4204 }
4205
4206 let project_path = path.into();
4207 let task = self.load_path(project_path.clone(), window, cx);
4208 cx.spawn_in(window, async move |this, cx| {
4209 let (project_entry_id, build_item) = task.await?;
4210 this.update_in(cx, move |this, window, cx| -> Option<_> {
4211 let pane = pane.upgrade()?;
4212 let new_pane = this.split_pane(
4213 pane,
4214 split_direction.unwrap_or(SplitDirection::Right),
4215 window,
4216 cx,
4217 );
4218 new_pane.update(cx, |new_pane, cx| {
4219 Some(new_pane.open_item(
4220 project_entry_id,
4221 project_path,
4222 true,
4223 allow_preview,
4224 true,
4225 None,
4226 window,
4227 cx,
4228 build_item,
4229 ))
4230 })
4231 })
4232 .map(|option| option.context("pane was dropped"))?
4233 })
4234 }
4235
4236 fn load_path(
4237 &mut self,
4238 path: ProjectPath,
4239 window: &mut Window,
4240 cx: &mut App,
4241 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4242 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4243 registry.open_path(self.project(), &path, window, cx)
4244 }
4245
4246 pub fn find_project_item<T>(
4247 &self,
4248 pane: &Entity<Pane>,
4249 project_item: &Entity<T::Item>,
4250 cx: &App,
4251 ) -> Option<Entity<T>>
4252 where
4253 T: ProjectItem,
4254 {
4255 use project::ProjectItem as _;
4256 let project_item = project_item.read(cx);
4257 let entry_id = project_item.entry_id(cx);
4258 let project_path = project_item.project_path(cx);
4259
4260 let mut item = None;
4261 if let Some(entry_id) = entry_id {
4262 item = pane.read(cx).item_for_entry(entry_id, cx);
4263 }
4264 if item.is_none()
4265 && let Some(project_path) = project_path
4266 {
4267 item = pane.read(cx).item_for_path(project_path, cx);
4268 }
4269
4270 item.and_then(|item| item.downcast::<T>())
4271 }
4272
4273 pub fn is_project_item_open<T>(
4274 &self,
4275 pane: &Entity<Pane>,
4276 project_item: &Entity<T::Item>,
4277 cx: &App,
4278 ) -> bool
4279 where
4280 T: ProjectItem,
4281 {
4282 self.find_project_item::<T>(pane, project_item, cx)
4283 .is_some()
4284 }
4285
4286 pub fn open_project_item<T>(
4287 &mut self,
4288 pane: Entity<Pane>,
4289 project_item: Entity<T::Item>,
4290 activate_pane: bool,
4291 focus_item: bool,
4292 keep_old_preview: bool,
4293 allow_new_preview: bool,
4294 window: &mut Window,
4295 cx: &mut Context<Self>,
4296 ) -> Entity<T>
4297 where
4298 T: ProjectItem,
4299 {
4300 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4301
4302 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4303 if !keep_old_preview
4304 && let Some(old_id) = old_item_id
4305 && old_id != item.item_id()
4306 {
4307 // switching to a different item, so unpreview old active item
4308 pane.update(cx, |pane, _| {
4309 pane.unpreview_item_if_preview(old_id);
4310 });
4311 }
4312
4313 self.activate_item(&item, activate_pane, focus_item, window, cx);
4314 if !allow_new_preview {
4315 pane.update(cx, |pane, _| {
4316 pane.unpreview_item_if_preview(item.item_id());
4317 });
4318 }
4319 return item;
4320 }
4321
4322 let item = pane.update(cx, |pane, cx| {
4323 cx.new(|cx| {
4324 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4325 })
4326 });
4327 let mut destination_index = None;
4328 pane.update(cx, |pane, cx| {
4329 if !keep_old_preview && let Some(old_id) = old_item_id {
4330 pane.unpreview_item_if_preview(old_id);
4331 }
4332 if allow_new_preview {
4333 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4334 }
4335 });
4336
4337 self.add_item(
4338 pane,
4339 Box::new(item.clone()),
4340 destination_index,
4341 activate_pane,
4342 focus_item,
4343 window,
4344 cx,
4345 );
4346 item
4347 }
4348
4349 pub fn open_shared_screen(
4350 &mut self,
4351 peer_id: PeerId,
4352 window: &mut Window,
4353 cx: &mut Context<Self>,
4354 ) {
4355 if let Some(shared_screen) =
4356 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4357 {
4358 self.active_pane.update(cx, |pane, cx| {
4359 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4360 });
4361 }
4362 }
4363
4364 pub fn activate_item(
4365 &mut self,
4366 item: &dyn ItemHandle,
4367 activate_pane: bool,
4368 focus_item: bool,
4369 window: &mut Window,
4370 cx: &mut App,
4371 ) -> bool {
4372 let result = self.panes.iter().find_map(|pane| {
4373 pane.read(cx)
4374 .index_for_item(item)
4375 .map(|ix| (pane.clone(), ix))
4376 });
4377 if let Some((pane, ix)) = result {
4378 pane.update(cx, |pane, cx| {
4379 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4380 });
4381 true
4382 } else {
4383 false
4384 }
4385 }
4386
4387 fn activate_pane_at_index(
4388 &mut self,
4389 action: &ActivatePane,
4390 window: &mut Window,
4391 cx: &mut Context<Self>,
4392 ) {
4393 let panes = self.center.panes();
4394 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4395 window.focus(&pane.focus_handle(cx), cx);
4396 } else {
4397 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4398 .detach();
4399 }
4400 }
4401
4402 fn move_item_to_pane_at_index(
4403 &mut self,
4404 action: &MoveItemToPane,
4405 window: &mut Window,
4406 cx: &mut Context<Self>,
4407 ) {
4408 let panes = self.center.panes();
4409 let destination = match panes.get(action.destination) {
4410 Some(&destination) => destination.clone(),
4411 None => {
4412 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4413 return;
4414 }
4415 let direction = SplitDirection::Right;
4416 let split_off_pane = self
4417 .find_pane_in_direction(direction, cx)
4418 .unwrap_or_else(|| self.active_pane.clone());
4419 let new_pane = self.add_pane(window, cx);
4420 self.center.split(&split_off_pane, &new_pane, direction, cx);
4421 new_pane
4422 }
4423 };
4424
4425 if action.clone {
4426 if self
4427 .active_pane
4428 .read(cx)
4429 .active_item()
4430 .is_some_and(|item| item.can_split(cx))
4431 {
4432 clone_active_item(
4433 self.database_id(),
4434 &self.active_pane,
4435 &destination,
4436 action.focus,
4437 window,
4438 cx,
4439 );
4440 return;
4441 }
4442 }
4443 move_active_item(
4444 &self.active_pane,
4445 &destination,
4446 action.focus,
4447 true,
4448 window,
4449 cx,
4450 )
4451 }
4452
4453 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4454 let panes = self.center.panes();
4455 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4456 let next_ix = (ix + 1) % panes.len();
4457 let next_pane = panes[next_ix].clone();
4458 window.focus(&next_pane.focus_handle(cx), cx);
4459 }
4460 }
4461
4462 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4463 let panes = self.center.panes();
4464 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4465 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4466 let prev_pane = panes[prev_ix].clone();
4467 window.focus(&prev_pane.focus_handle(cx), cx);
4468 }
4469 }
4470
4471 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4472 let last_pane = self.center.last_pane();
4473 window.focus(&last_pane.focus_handle(cx), cx);
4474 }
4475
4476 pub fn activate_pane_in_direction(
4477 &mut self,
4478 direction: SplitDirection,
4479 window: &mut Window,
4480 cx: &mut App,
4481 ) {
4482 use ActivateInDirectionTarget as Target;
4483 enum Origin {
4484 LeftDock,
4485 RightDock,
4486 BottomDock,
4487 Center,
4488 }
4489
4490 let origin: Origin = [
4491 (&self.left_dock, Origin::LeftDock),
4492 (&self.right_dock, Origin::RightDock),
4493 (&self.bottom_dock, Origin::BottomDock),
4494 ]
4495 .into_iter()
4496 .find_map(|(dock, origin)| {
4497 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4498 Some(origin)
4499 } else {
4500 None
4501 }
4502 })
4503 .unwrap_or(Origin::Center);
4504
4505 let get_last_active_pane = || {
4506 let pane = self
4507 .last_active_center_pane
4508 .clone()
4509 .unwrap_or_else(|| {
4510 self.panes
4511 .first()
4512 .expect("There must be an active pane")
4513 .downgrade()
4514 })
4515 .upgrade()?;
4516 (pane.read(cx).items_len() != 0).then_some(pane)
4517 };
4518
4519 let try_dock =
4520 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4521
4522 let target = match (origin, direction) {
4523 // We're in the center, so we first try to go to a different pane,
4524 // otherwise try to go to a dock.
4525 (Origin::Center, direction) => {
4526 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4527 Some(Target::Pane(pane))
4528 } else {
4529 match direction {
4530 SplitDirection::Up => None,
4531 SplitDirection::Down => try_dock(&self.bottom_dock),
4532 SplitDirection::Left => try_dock(&self.left_dock),
4533 SplitDirection::Right => try_dock(&self.right_dock),
4534 }
4535 }
4536 }
4537
4538 (Origin::LeftDock, SplitDirection::Right) => {
4539 if let Some(last_active_pane) = get_last_active_pane() {
4540 Some(Target::Pane(last_active_pane))
4541 } else {
4542 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4543 }
4544 }
4545
4546 (Origin::LeftDock, SplitDirection::Down)
4547 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4548
4549 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4550 (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
4551 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4552
4553 (Origin::RightDock, SplitDirection::Left) => {
4554 if let Some(last_active_pane) = get_last_active_pane() {
4555 Some(Target::Pane(last_active_pane))
4556 } else {
4557 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
4558 }
4559 }
4560
4561 _ => None,
4562 };
4563
4564 match target {
4565 Some(ActivateInDirectionTarget::Pane(pane)) => {
4566 let pane = pane.read(cx);
4567 if let Some(item) = pane.active_item() {
4568 item.item_focus_handle(cx).focus(window, cx);
4569 } else {
4570 log::error!(
4571 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4572 );
4573 }
4574 }
4575 Some(ActivateInDirectionTarget::Dock(dock)) => {
4576 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4577 window.defer(cx, move |window, cx| {
4578 let dock = dock.read(cx);
4579 if let Some(panel) = dock.active_panel() {
4580 panel.panel_focus_handle(cx).focus(window, cx);
4581 } else {
4582 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4583 }
4584 })
4585 }
4586 None => {}
4587 }
4588 }
4589
4590 pub fn move_item_to_pane_in_direction(
4591 &mut self,
4592 action: &MoveItemToPaneInDirection,
4593 window: &mut Window,
4594 cx: &mut Context<Self>,
4595 ) {
4596 let destination = match self.find_pane_in_direction(action.direction, cx) {
4597 Some(destination) => destination,
4598 None => {
4599 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4600 return;
4601 }
4602 let new_pane = self.add_pane(window, cx);
4603 self.center
4604 .split(&self.active_pane, &new_pane, action.direction, cx);
4605 new_pane
4606 }
4607 };
4608
4609 if action.clone {
4610 if self
4611 .active_pane
4612 .read(cx)
4613 .active_item()
4614 .is_some_and(|item| item.can_split(cx))
4615 {
4616 clone_active_item(
4617 self.database_id(),
4618 &self.active_pane,
4619 &destination,
4620 action.focus,
4621 window,
4622 cx,
4623 );
4624 return;
4625 }
4626 }
4627 move_active_item(
4628 &self.active_pane,
4629 &destination,
4630 action.focus,
4631 true,
4632 window,
4633 cx,
4634 );
4635 }
4636
4637 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4638 self.center.bounding_box_for_pane(pane)
4639 }
4640
4641 pub fn find_pane_in_direction(
4642 &mut self,
4643 direction: SplitDirection,
4644 cx: &App,
4645 ) -> Option<Entity<Pane>> {
4646 self.center
4647 .find_pane_in_direction(&self.active_pane, direction, cx)
4648 .cloned()
4649 }
4650
4651 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4652 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4653 self.center.swap(&self.active_pane, &to, cx);
4654 cx.notify();
4655 }
4656 }
4657
4658 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4659 if self
4660 .center
4661 .move_to_border(&self.active_pane, direction, cx)
4662 .unwrap()
4663 {
4664 cx.notify();
4665 }
4666 }
4667
4668 pub fn resize_pane(
4669 &mut self,
4670 axis: gpui::Axis,
4671 amount: Pixels,
4672 window: &mut Window,
4673 cx: &mut Context<Self>,
4674 ) {
4675 let docks = self.all_docks();
4676 let active_dock = docks
4677 .into_iter()
4678 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4679
4680 if let Some(dock) = active_dock {
4681 let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
4682 return;
4683 };
4684 match dock.read(cx).position() {
4685 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4686 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4687 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4688 }
4689 } else {
4690 self.center
4691 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
4692 }
4693 cx.notify();
4694 }
4695
4696 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
4697 self.center.reset_pane_sizes(cx);
4698 cx.notify();
4699 }
4700
4701 fn handle_pane_focused(
4702 &mut self,
4703 pane: Entity<Pane>,
4704 window: &mut Window,
4705 cx: &mut Context<Self>,
4706 ) {
4707 // This is explicitly hoisted out of the following check for pane identity as
4708 // terminal panel panes are not registered as a center panes.
4709 self.status_bar.update(cx, |status_bar, cx| {
4710 status_bar.set_active_pane(&pane, window, cx);
4711 });
4712 if self.active_pane != pane {
4713 self.set_active_pane(&pane, window, cx);
4714 }
4715
4716 if self.last_active_center_pane.is_none() {
4717 self.last_active_center_pane = Some(pane.downgrade());
4718 }
4719
4720 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
4721 // This prevents the dock from closing when focus events fire during window activation.
4722 // We also preserve any dock whose active panel itself has focus — this covers
4723 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
4724 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
4725 let dock_read = dock.read(cx);
4726 if let Some(panel) = dock_read.active_panel() {
4727 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
4728 || panel.panel_focus_handle(cx).contains_focused(window, cx)
4729 {
4730 return Some(dock_read.position());
4731 }
4732 }
4733 None
4734 });
4735
4736 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
4737 if pane.read(cx).is_zoomed() {
4738 self.zoomed = Some(pane.downgrade().into());
4739 } else {
4740 self.zoomed = None;
4741 }
4742 self.zoomed_position = None;
4743 cx.emit(Event::ZoomChanged);
4744 self.update_active_view_for_followers(window, cx);
4745 pane.update(cx, |pane, _| {
4746 pane.track_alternate_file_items();
4747 });
4748
4749 cx.notify();
4750 }
4751
4752 fn set_active_pane(
4753 &mut self,
4754 pane: &Entity<Pane>,
4755 window: &mut Window,
4756 cx: &mut Context<Self>,
4757 ) {
4758 self.active_pane = pane.clone();
4759 self.active_item_path_changed(true, window, cx);
4760 self.last_active_center_pane = Some(pane.downgrade());
4761 }
4762
4763 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4764 self.update_active_view_for_followers(window, cx);
4765 }
4766
4767 fn handle_pane_event(
4768 &mut self,
4769 pane: &Entity<Pane>,
4770 event: &pane::Event,
4771 window: &mut Window,
4772 cx: &mut Context<Self>,
4773 ) {
4774 let mut serialize_workspace = true;
4775 match event {
4776 pane::Event::AddItem { item } => {
4777 item.added_to_pane(self, pane.clone(), window, cx);
4778 cx.emit(Event::ItemAdded {
4779 item: item.boxed_clone(),
4780 });
4781 }
4782 pane::Event::Split { direction, mode } => {
4783 match mode {
4784 SplitMode::ClonePane => {
4785 self.split_and_clone(pane.clone(), *direction, window, cx)
4786 .detach();
4787 }
4788 SplitMode::EmptyPane => {
4789 self.split_pane(pane.clone(), *direction, window, cx);
4790 }
4791 SplitMode::MovePane => {
4792 self.split_and_move(pane.clone(), *direction, window, cx);
4793 }
4794 };
4795 }
4796 pane::Event::JoinIntoNext => {
4797 self.join_pane_into_next(pane.clone(), window, cx);
4798 }
4799 pane::Event::JoinAll => {
4800 self.join_all_panes(window, cx);
4801 }
4802 pane::Event::Remove { focus_on_pane } => {
4803 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
4804 }
4805 pane::Event::ActivateItem {
4806 local,
4807 focus_changed,
4808 } => {
4809 window.invalidate_character_coordinates();
4810
4811 pane.update(cx, |pane, _| {
4812 pane.track_alternate_file_items();
4813 });
4814 if *local {
4815 self.unfollow_in_pane(pane, window, cx);
4816 }
4817 serialize_workspace = *focus_changed || pane != self.active_pane();
4818 if pane == self.active_pane() {
4819 self.active_item_path_changed(*focus_changed, window, cx);
4820 self.update_active_view_for_followers(window, cx);
4821 } else if *local {
4822 self.set_active_pane(pane, window, cx);
4823 }
4824 }
4825 pane::Event::UserSavedItem { item, save_intent } => {
4826 cx.emit(Event::UserSavedItem {
4827 pane: pane.downgrade(),
4828 item: item.boxed_clone(),
4829 save_intent: *save_intent,
4830 });
4831 serialize_workspace = false;
4832 }
4833 pane::Event::ChangeItemTitle => {
4834 if *pane == self.active_pane {
4835 self.active_item_path_changed(false, window, cx);
4836 }
4837 serialize_workspace = false;
4838 }
4839 pane::Event::RemovedItem { item } => {
4840 cx.emit(Event::ActiveItemChanged);
4841 self.update_window_edited(window, cx);
4842 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
4843 && entry.get().entity_id() == pane.entity_id()
4844 {
4845 entry.remove();
4846 }
4847 cx.emit(Event::ItemRemoved {
4848 item_id: item.item_id(),
4849 });
4850 }
4851 pane::Event::Focus => {
4852 window.invalidate_character_coordinates();
4853 self.handle_pane_focused(pane.clone(), window, cx);
4854 }
4855 pane::Event::ZoomIn => {
4856 if *pane == self.active_pane {
4857 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
4858 if pane.read(cx).has_focus(window, cx) {
4859 self.zoomed = Some(pane.downgrade().into());
4860 self.zoomed_position = None;
4861 cx.emit(Event::ZoomChanged);
4862 }
4863 cx.notify();
4864 }
4865 }
4866 pane::Event::ZoomOut => {
4867 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4868 if self.zoomed_position.is_none() {
4869 self.zoomed = None;
4870 cx.emit(Event::ZoomChanged);
4871 }
4872 cx.notify();
4873 }
4874 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
4875 }
4876
4877 if serialize_workspace {
4878 self.serialize_workspace(window, cx);
4879 }
4880 }
4881
4882 pub fn unfollow_in_pane(
4883 &mut self,
4884 pane: &Entity<Pane>,
4885 window: &mut Window,
4886 cx: &mut Context<Workspace>,
4887 ) -> Option<CollaboratorId> {
4888 let leader_id = self.leader_for_pane(pane)?;
4889 self.unfollow(leader_id, window, cx);
4890 Some(leader_id)
4891 }
4892
4893 pub fn split_pane(
4894 &mut self,
4895 pane_to_split: Entity<Pane>,
4896 split_direction: SplitDirection,
4897 window: &mut Window,
4898 cx: &mut Context<Self>,
4899 ) -> Entity<Pane> {
4900 let new_pane = self.add_pane(window, cx);
4901 self.center
4902 .split(&pane_to_split, &new_pane, split_direction, cx);
4903 cx.notify();
4904 new_pane
4905 }
4906
4907 pub fn split_and_move(
4908 &mut self,
4909 pane: Entity<Pane>,
4910 direction: SplitDirection,
4911 window: &mut Window,
4912 cx: &mut Context<Self>,
4913 ) {
4914 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
4915 return;
4916 };
4917 let new_pane = self.add_pane(window, cx);
4918 new_pane.update(cx, |pane, cx| {
4919 pane.add_item(item, true, true, None, window, cx)
4920 });
4921 self.center.split(&pane, &new_pane, direction, cx);
4922 cx.notify();
4923 }
4924
4925 pub fn split_and_clone(
4926 &mut self,
4927 pane: Entity<Pane>,
4928 direction: SplitDirection,
4929 window: &mut Window,
4930 cx: &mut Context<Self>,
4931 ) -> Task<Option<Entity<Pane>>> {
4932 let Some(item) = pane.read(cx).active_item() else {
4933 return Task::ready(None);
4934 };
4935 if !item.can_split(cx) {
4936 return Task::ready(None);
4937 }
4938 let task = item.clone_on_split(self.database_id(), window, cx);
4939 cx.spawn_in(window, async move |this, cx| {
4940 if let Some(clone) = task.await {
4941 this.update_in(cx, |this, window, cx| {
4942 let new_pane = this.add_pane(window, cx);
4943 let nav_history = pane.read(cx).fork_nav_history();
4944 new_pane.update(cx, |pane, cx| {
4945 pane.set_nav_history(nav_history, cx);
4946 pane.add_item(clone, true, true, None, window, cx)
4947 });
4948 this.center.split(&pane, &new_pane, direction, cx);
4949 cx.notify();
4950 new_pane
4951 })
4952 .ok()
4953 } else {
4954 None
4955 }
4956 })
4957 }
4958
4959 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4960 let active_item = self.active_pane.read(cx).active_item();
4961 for pane in &self.panes {
4962 join_pane_into_active(&self.active_pane, pane, window, cx);
4963 }
4964 if let Some(active_item) = active_item {
4965 self.activate_item(active_item.as_ref(), true, true, window, cx);
4966 }
4967 cx.notify();
4968 }
4969
4970 pub fn join_pane_into_next(
4971 &mut self,
4972 pane: Entity<Pane>,
4973 window: &mut Window,
4974 cx: &mut Context<Self>,
4975 ) {
4976 let next_pane = self
4977 .find_pane_in_direction(SplitDirection::Right, cx)
4978 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
4979 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
4980 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
4981 let Some(next_pane) = next_pane else {
4982 return;
4983 };
4984 move_all_items(&pane, &next_pane, window, cx);
4985 cx.notify();
4986 }
4987
4988 fn remove_pane(
4989 &mut self,
4990 pane: Entity<Pane>,
4991 focus_on: Option<Entity<Pane>>,
4992 window: &mut Window,
4993 cx: &mut Context<Self>,
4994 ) {
4995 if self.center.remove(&pane, cx).unwrap() {
4996 self.force_remove_pane(&pane, &focus_on, window, cx);
4997 self.unfollow_in_pane(&pane, window, cx);
4998 self.last_leaders_by_pane.remove(&pane.downgrade());
4999 for removed_item in pane.read(cx).items() {
5000 self.panes_by_item.remove(&removed_item.item_id());
5001 }
5002
5003 cx.notify();
5004 } else {
5005 self.active_item_path_changed(true, window, cx);
5006 }
5007 cx.emit(Event::PaneRemoved);
5008 }
5009
5010 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5011 &mut self.panes
5012 }
5013
5014 pub fn panes(&self) -> &[Entity<Pane>] {
5015 &self.panes
5016 }
5017
5018 pub fn active_pane(&self) -> &Entity<Pane> {
5019 &self.active_pane
5020 }
5021
5022 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5023 for dock in self.all_docks() {
5024 if dock.focus_handle(cx).contains_focused(window, cx)
5025 && let Some(pane) = dock
5026 .read(cx)
5027 .active_panel()
5028 .and_then(|panel| panel.pane(cx))
5029 {
5030 return pane;
5031 }
5032 }
5033 self.active_pane().clone()
5034 }
5035
5036 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5037 self.find_pane_in_direction(SplitDirection::Right, cx)
5038 .unwrap_or_else(|| {
5039 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5040 })
5041 }
5042
5043 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5044 self.pane_for_item_id(handle.item_id())
5045 }
5046
5047 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5048 let weak_pane = self.panes_by_item.get(&item_id)?;
5049 weak_pane.upgrade()
5050 }
5051
5052 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5053 self.panes
5054 .iter()
5055 .find(|pane| pane.entity_id() == entity_id)
5056 .cloned()
5057 }
5058
5059 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5060 self.follower_states.retain(|leader_id, state| {
5061 if *leader_id == CollaboratorId::PeerId(peer_id) {
5062 for item in state.items_by_leader_view_id.values() {
5063 item.view.set_leader_id(None, window, cx);
5064 }
5065 false
5066 } else {
5067 true
5068 }
5069 });
5070 cx.notify();
5071 }
5072
5073 pub fn start_following(
5074 &mut self,
5075 leader_id: impl Into<CollaboratorId>,
5076 window: &mut Window,
5077 cx: &mut Context<Self>,
5078 ) -> Option<Task<Result<()>>> {
5079 let leader_id = leader_id.into();
5080 let pane = self.active_pane().clone();
5081
5082 self.last_leaders_by_pane
5083 .insert(pane.downgrade(), leader_id);
5084 self.unfollow(leader_id, window, cx);
5085 self.unfollow_in_pane(&pane, window, cx);
5086 self.follower_states.insert(
5087 leader_id,
5088 FollowerState {
5089 center_pane: pane.clone(),
5090 dock_pane: None,
5091 active_view_id: None,
5092 items_by_leader_view_id: Default::default(),
5093 },
5094 );
5095 cx.notify();
5096
5097 match leader_id {
5098 CollaboratorId::PeerId(leader_peer_id) => {
5099 let room_id = self.active_call()?.room_id(cx)?;
5100 let project_id = self.project.read(cx).remote_id();
5101 let request = self.app_state.client.request(proto::Follow {
5102 room_id,
5103 project_id,
5104 leader_id: Some(leader_peer_id),
5105 });
5106
5107 Some(cx.spawn_in(window, async move |this, cx| {
5108 let response = request.await?;
5109 this.update(cx, |this, _| {
5110 let state = this
5111 .follower_states
5112 .get_mut(&leader_id)
5113 .context("following interrupted")?;
5114 state.active_view_id = response
5115 .active_view
5116 .as_ref()
5117 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5118 anyhow::Ok(())
5119 })??;
5120 if let Some(view) = response.active_view {
5121 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5122 }
5123 this.update_in(cx, |this, window, cx| {
5124 this.leader_updated(leader_id, window, cx)
5125 })?;
5126 Ok(())
5127 }))
5128 }
5129 CollaboratorId::Agent => {
5130 self.leader_updated(leader_id, window, cx)?;
5131 Some(Task::ready(Ok(())))
5132 }
5133 }
5134 }
5135
5136 pub fn follow_next_collaborator(
5137 &mut self,
5138 _: &FollowNextCollaborator,
5139 window: &mut Window,
5140 cx: &mut Context<Self>,
5141 ) {
5142 let collaborators = self.project.read(cx).collaborators();
5143 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5144 let mut collaborators = collaborators.keys().copied();
5145 for peer_id in collaborators.by_ref() {
5146 if CollaboratorId::PeerId(peer_id) == leader_id {
5147 break;
5148 }
5149 }
5150 collaborators.next().map(CollaboratorId::PeerId)
5151 } else if let Some(last_leader_id) =
5152 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5153 {
5154 match last_leader_id {
5155 CollaboratorId::PeerId(peer_id) => {
5156 if collaborators.contains_key(peer_id) {
5157 Some(*last_leader_id)
5158 } else {
5159 None
5160 }
5161 }
5162 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5163 }
5164 } else {
5165 None
5166 };
5167
5168 let pane = self.active_pane.clone();
5169 let Some(leader_id) = next_leader_id.or_else(|| {
5170 Some(CollaboratorId::PeerId(
5171 collaborators.keys().copied().next()?,
5172 ))
5173 }) else {
5174 return;
5175 };
5176 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5177 return;
5178 }
5179 if let Some(task) = self.start_following(leader_id, window, cx) {
5180 task.detach_and_log_err(cx)
5181 }
5182 }
5183
5184 pub fn follow(
5185 &mut self,
5186 leader_id: impl Into<CollaboratorId>,
5187 window: &mut Window,
5188 cx: &mut Context<Self>,
5189 ) {
5190 let leader_id = leader_id.into();
5191
5192 if let CollaboratorId::PeerId(peer_id) = leader_id {
5193 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5194 return;
5195 };
5196 let Some(remote_participant) =
5197 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5198 else {
5199 return;
5200 };
5201
5202 let project = self.project.read(cx);
5203
5204 let other_project_id = match remote_participant.location {
5205 ParticipantLocation::External => None,
5206 ParticipantLocation::UnsharedProject => None,
5207 ParticipantLocation::SharedProject { project_id } => {
5208 if Some(project_id) == project.remote_id() {
5209 None
5210 } else {
5211 Some(project_id)
5212 }
5213 }
5214 };
5215
5216 // if they are active in another project, follow there.
5217 if let Some(project_id) = other_project_id {
5218 let app_state = self.app_state.clone();
5219 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5220 .detach_and_log_err(cx);
5221 }
5222 }
5223
5224 // if you're already following, find the right pane and focus it.
5225 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5226 window.focus(&follower_state.pane().focus_handle(cx), cx);
5227
5228 return;
5229 }
5230
5231 // Otherwise, follow.
5232 if let Some(task) = self.start_following(leader_id, window, cx) {
5233 task.detach_and_log_err(cx)
5234 }
5235 }
5236
5237 pub fn unfollow(
5238 &mut self,
5239 leader_id: impl Into<CollaboratorId>,
5240 window: &mut Window,
5241 cx: &mut Context<Self>,
5242 ) -> Option<()> {
5243 cx.notify();
5244
5245 let leader_id = leader_id.into();
5246 let state = self.follower_states.remove(&leader_id)?;
5247 for (_, item) in state.items_by_leader_view_id {
5248 item.view.set_leader_id(None, window, cx);
5249 }
5250
5251 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5252 let project_id = self.project.read(cx).remote_id();
5253 let room_id = self.active_call()?.room_id(cx)?;
5254 self.app_state
5255 .client
5256 .send(proto::Unfollow {
5257 room_id,
5258 project_id,
5259 leader_id: Some(leader_peer_id),
5260 })
5261 .log_err();
5262 }
5263
5264 Some(())
5265 }
5266
5267 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5268 self.follower_states.contains_key(&id.into())
5269 }
5270
5271 fn active_item_path_changed(
5272 &mut self,
5273 focus_changed: bool,
5274 window: &mut Window,
5275 cx: &mut Context<Self>,
5276 ) {
5277 cx.emit(Event::ActiveItemChanged);
5278 let active_entry = self.active_project_path(cx);
5279 self.project.update(cx, |project, cx| {
5280 project.set_active_path(active_entry.clone(), cx)
5281 });
5282
5283 if focus_changed && let Some(project_path) = &active_entry {
5284 let git_store_entity = self.project.read(cx).git_store().clone();
5285 git_store_entity.update(cx, |git_store, cx| {
5286 git_store.set_active_repo_for_path(project_path, cx);
5287 });
5288 }
5289
5290 self.update_window_title(window, cx);
5291 }
5292
5293 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5294 let project = self.project().read(cx);
5295 let mut title = String::new();
5296
5297 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5298 let name = {
5299 let settings_location = SettingsLocation {
5300 worktree_id: worktree.read(cx).id(),
5301 path: RelPath::empty(),
5302 };
5303
5304 let settings = WorktreeSettings::get(Some(settings_location), cx);
5305 match &settings.project_name {
5306 Some(name) => name.as_str(),
5307 None => worktree.read(cx).root_name_str(),
5308 }
5309 };
5310 if i > 0 {
5311 title.push_str(", ");
5312 }
5313 title.push_str(name);
5314 }
5315
5316 if title.is_empty() {
5317 title = "empty project".to_string();
5318 }
5319
5320 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5321 let filename = path.path.file_name().or_else(|| {
5322 Some(
5323 project
5324 .worktree_for_id(path.worktree_id, cx)?
5325 .read(cx)
5326 .root_name_str(),
5327 )
5328 });
5329
5330 if let Some(filename) = filename {
5331 title.push_str(" — ");
5332 title.push_str(filename.as_ref());
5333 }
5334 }
5335
5336 if project.is_via_collab() {
5337 title.push_str(" ↙");
5338 } else if project.is_shared() {
5339 title.push_str(" ↗");
5340 }
5341
5342 if let Some(last_title) = self.last_window_title.as_ref()
5343 && &title == last_title
5344 {
5345 return;
5346 }
5347 window.set_window_title(&title);
5348 SystemWindowTabController::update_tab_title(
5349 cx,
5350 window.window_handle().window_id(),
5351 SharedString::from(&title),
5352 );
5353 self.last_window_title = Some(title);
5354 }
5355
5356 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5357 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5358 if is_edited != self.window_edited {
5359 self.window_edited = is_edited;
5360 window.set_window_edited(self.window_edited)
5361 }
5362 }
5363
5364 fn update_item_dirty_state(
5365 &mut self,
5366 item: &dyn ItemHandle,
5367 window: &mut Window,
5368 cx: &mut App,
5369 ) {
5370 let is_dirty = item.is_dirty(cx);
5371 let item_id = item.item_id();
5372 let was_dirty = self.dirty_items.contains_key(&item_id);
5373 if is_dirty == was_dirty {
5374 return;
5375 }
5376 if was_dirty {
5377 self.dirty_items.remove(&item_id);
5378 self.update_window_edited(window, cx);
5379 return;
5380 }
5381
5382 let workspace = self.weak_handle();
5383 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5384 return;
5385 };
5386 let on_release_callback = Box::new(move |cx: &mut App| {
5387 window_handle
5388 .update(cx, |_, window, cx| {
5389 workspace
5390 .update(cx, |workspace, cx| {
5391 workspace.dirty_items.remove(&item_id);
5392 workspace.update_window_edited(window, cx)
5393 })
5394 .ok();
5395 })
5396 .ok();
5397 });
5398
5399 let s = item.on_release(cx, on_release_callback);
5400 self.dirty_items.insert(item_id, s);
5401 self.update_window_edited(window, cx);
5402 }
5403
5404 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5405 if self.notifications.is_empty() {
5406 None
5407 } else {
5408 Some(
5409 div()
5410 .absolute()
5411 .right_3()
5412 .bottom_3()
5413 .w_112()
5414 .h_full()
5415 .flex()
5416 .flex_col()
5417 .justify_end()
5418 .gap_2()
5419 .children(
5420 self.notifications
5421 .iter()
5422 .map(|(_, notification)| notification.clone().into_any()),
5423 ),
5424 )
5425 }
5426 }
5427
5428 // RPC handlers
5429
5430 fn active_view_for_follower(
5431 &self,
5432 follower_project_id: Option<u64>,
5433 window: &mut Window,
5434 cx: &mut Context<Self>,
5435 ) -> Option<proto::View> {
5436 let (item, panel_id) = self.active_item_for_followers(window, cx);
5437 let item = item?;
5438 let leader_id = self
5439 .pane_for(&*item)
5440 .and_then(|pane| self.leader_for_pane(&pane));
5441 let leader_peer_id = match leader_id {
5442 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5443 Some(CollaboratorId::Agent) | None => None,
5444 };
5445
5446 let item_handle = item.to_followable_item_handle(cx)?;
5447 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5448 let variant = item_handle.to_state_proto(window, cx)?;
5449
5450 if item_handle.is_project_item(window, cx)
5451 && (follower_project_id.is_none()
5452 || follower_project_id != self.project.read(cx).remote_id())
5453 {
5454 return None;
5455 }
5456
5457 Some(proto::View {
5458 id: id.to_proto(),
5459 leader_id: leader_peer_id,
5460 variant: Some(variant),
5461 panel_id: panel_id.map(|id| id as i32),
5462 })
5463 }
5464
5465 fn handle_follow(
5466 &mut self,
5467 follower_project_id: Option<u64>,
5468 window: &mut Window,
5469 cx: &mut Context<Self>,
5470 ) -> proto::FollowResponse {
5471 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5472
5473 cx.notify();
5474 proto::FollowResponse {
5475 views: active_view.iter().cloned().collect(),
5476 active_view,
5477 }
5478 }
5479
5480 fn handle_update_followers(
5481 &mut self,
5482 leader_id: PeerId,
5483 message: proto::UpdateFollowers,
5484 _window: &mut Window,
5485 _cx: &mut Context<Self>,
5486 ) {
5487 self.leader_updates_tx
5488 .unbounded_send((leader_id, message))
5489 .ok();
5490 }
5491
5492 async fn process_leader_update(
5493 this: &WeakEntity<Self>,
5494 leader_id: PeerId,
5495 update: proto::UpdateFollowers,
5496 cx: &mut AsyncWindowContext,
5497 ) -> Result<()> {
5498 match update.variant.context("invalid update")? {
5499 proto::update_followers::Variant::CreateView(view) => {
5500 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5501 let should_add_view = this.update(cx, |this, _| {
5502 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5503 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5504 } else {
5505 anyhow::Ok(false)
5506 }
5507 })??;
5508
5509 if should_add_view {
5510 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5511 }
5512 }
5513 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5514 let should_add_view = this.update(cx, |this, _| {
5515 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5516 state.active_view_id = update_active_view
5517 .view
5518 .as_ref()
5519 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5520
5521 if state.active_view_id.is_some_and(|view_id| {
5522 !state.items_by_leader_view_id.contains_key(&view_id)
5523 }) {
5524 anyhow::Ok(true)
5525 } else {
5526 anyhow::Ok(false)
5527 }
5528 } else {
5529 anyhow::Ok(false)
5530 }
5531 })??;
5532
5533 if should_add_view && let Some(view) = update_active_view.view {
5534 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5535 }
5536 }
5537 proto::update_followers::Variant::UpdateView(update_view) => {
5538 let variant = update_view.variant.context("missing update view variant")?;
5539 let id = update_view.id.context("missing update view id")?;
5540 let mut tasks = Vec::new();
5541 this.update_in(cx, |this, window, cx| {
5542 let project = this.project.clone();
5543 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5544 let view_id = ViewId::from_proto(id.clone())?;
5545 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5546 tasks.push(item.view.apply_update_proto(
5547 &project,
5548 variant.clone(),
5549 window,
5550 cx,
5551 ));
5552 }
5553 }
5554 anyhow::Ok(())
5555 })??;
5556 try_join_all(tasks).await.log_err();
5557 }
5558 }
5559 this.update_in(cx, |this, window, cx| {
5560 this.leader_updated(leader_id, window, cx)
5561 })?;
5562 Ok(())
5563 }
5564
5565 async fn add_view_from_leader(
5566 this: WeakEntity<Self>,
5567 leader_id: PeerId,
5568 view: &proto::View,
5569 cx: &mut AsyncWindowContext,
5570 ) -> Result<()> {
5571 let this = this.upgrade().context("workspace dropped")?;
5572
5573 let Some(id) = view.id.clone() else {
5574 anyhow::bail!("no id for view");
5575 };
5576 let id = ViewId::from_proto(id)?;
5577 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5578
5579 let pane = this.update(cx, |this, _cx| {
5580 let state = this
5581 .follower_states
5582 .get(&leader_id.into())
5583 .context("stopped following")?;
5584 anyhow::Ok(state.pane().clone())
5585 })?;
5586 let existing_item = pane.update_in(cx, |pane, window, cx| {
5587 let client = this.read(cx).client().clone();
5588 pane.items().find_map(|item| {
5589 let item = item.to_followable_item_handle(cx)?;
5590 if item.remote_id(&client, window, cx) == Some(id) {
5591 Some(item)
5592 } else {
5593 None
5594 }
5595 })
5596 })?;
5597 let item = if let Some(existing_item) = existing_item {
5598 existing_item
5599 } else {
5600 let variant = view.variant.clone();
5601 anyhow::ensure!(variant.is_some(), "missing view variant");
5602
5603 let task = cx.update(|window, cx| {
5604 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5605 })?;
5606
5607 let Some(task) = task else {
5608 anyhow::bail!(
5609 "failed to construct view from leader (maybe from a different version of zed?)"
5610 );
5611 };
5612
5613 let mut new_item = task.await?;
5614 pane.update_in(cx, |pane, window, cx| {
5615 let mut item_to_remove = None;
5616 for (ix, item) in pane.items().enumerate() {
5617 if let Some(item) = item.to_followable_item_handle(cx) {
5618 match new_item.dedup(item.as_ref(), window, cx) {
5619 Some(item::Dedup::KeepExisting) => {
5620 new_item =
5621 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5622 break;
5623 }
5624 Some(item::Dedup::ReplaceExisting) => {
5625 item_to_remove = Some((ix, item.item_id()));
5626 break;
5627 }
5628 None => {}
5629 }
5630 }
5631 }
5632
5633 if let Some((ix, id)) = item_to_remove {
5634 pane.remove_item(id, false, false, window, cx);
5635 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5636 }
5637 })?;
5638
5639 new_item
5640 };
5641
5642 this.update_in(cx, |this, window, cx| {
5643 let state = this.follower_states.get_mut(&leader_id.into())?;
5644 item.set_leader_id(Some(leader_id.into()), window, cx);
5645 state.items_by_leader_view_id.insert(
5646 id,
5647 FollowerView {
5648 view: item,
5649 location: panel_id,
5650 },
5651 );
5652
5653 Some(())
5654 })
5655 .context("no follower state")?;
5656
5657 Ok(())
5658 }
5659
5660 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5661 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5662 return;
5663 };
5664
5665 if let Some(agent_location) = self.project.read(cx).agent_location() {
5666 let buffer_entity_id = agent_location.buffer.entity_id();
5667 let view_id = ViewId {
5668 creator: CollaboratorId::Agent,
5669 id: buffer_entity_id.as_u64(),
5670 };
5671 follower_state.active_view_id = Some(view_id);
5672
5673 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5674 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5675 hash_map::Entry::Vacant(entry) => {
5676 let existing_view =
5677 follower_state
5678 .center_pane
5679 .read(cx)
5680 .items()
5681 .find_map(|item| {
5682 let item = item.to_followable_item_handle(cx)?;
5683 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5684 && item.project_item_model_ids(cx).as_slice()
5685 == [buffer_entity_id]
5686 {
5687 Some(item)
5688 } else {
5689 None
5690 }
5691 });
5692 let view = existing_view.or_else(|| {
5693 agent_location.buffer.upgrade().and_then(|buffer| {
5694 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
5695 registry.build_item(buffer, self.project.clone(), None, window, cx)
5696 })?
5697 .to_followable_item_handle(cx)
5698 })
5699 });
5700
5701 view.map(|view| {
5702 entry.insert(FollowerView {
5703 view,
5704 location: None,
5705 })
5706 })
5707 }
5708 };
5709
5710 if let Some(item) = item {
5711 item.view
5712 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
5713 item.view
5714 .update_agent_location(agent_location.position, window, cx);
5715 }
5716 } else {
5717 follower_state.active_view_id = None;
5718 }
5719
5720 self.leader_updated(CollaboratorId::Agent, window, cx);
5721 }
5722
5723 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
5724 let mut is_project_item = true;
5725 let mut update = proto::UpdateActiveView::default();
5726 if window.is_window_active() {
5727 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
5728
5729 if let Some(item) = active_item
5730 && item.item_focus_handle(cx).contains_focused(window, cx)
5731 {
5732 let leader_id = self
5733 .pane_for(&*item)
5734 .and_then(|pane| self.leader_for_pane(&pane));
5735 let leader_peer_id = match leader_id {
5736 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5737 Some(CollaboratorId::Agent) | None => None,
5738 };
5739
5740 if let Some(item) = item.to_followable_item_handle(cx) {
5741 let id = item
5742 .remote_id(&self.app_state.client, window, cx)
5743 .map(|id| id.to_proto());
5744
5745 if let Some(id) = id
5746 && let Some(variant) = item.to_state_proto(window, cx)
5747 {
5748 let view = Some(proto::View {
5749 id,
5750 leader_id: leader_peer_id,
5751 variant: Some(variant),
5752 panel_id: panel_id.map(|id| id as i32),
5753 });
5754
5755 is_project_item = item.is_project_item(window, cx);
5756 update = proto::UpdateActiveView { view };
5757 };
5758 }
5759 }
5760 }
5761
5762 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
5763 if active_view_id != self.last_active_view_id.as_ref() {
5764 self.last_active_view_id = active_view_id.cloned();
5765 self.update_followers(
5766 is_project_item,
5767 proto::update_followers::Variant::UpdateActiveView(update),
5768 window,
5769 cx,
5770 );
5771 }
5772 }
5773
5774 fn active_item_for_followers(
5775 &self,
5776 window: &mut Window,
5777 cx: &mut App,
5778 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
5779 let mut active_item = None;
5780 let mut panel_id = None;
5781 for dock in self.all_docks() {
5782 if dock.focus_handle(cx).contains_focused(window, cx)
5783 && let Some(panel) = dock.read(cx).active_panel()
5784 && let Some(pane) = panel.pane(cx)
5785 && let Some(item) = pane.read(cx).active_item()
5786 {
5787 active_item = Some(item);
5788 panel_id = panel.remote_id();
5789 break;
5790 }
5791 }
5792
5793 if active_item.is_none() {
5794 active_item = self.active_pane().read(cx).active_item();
5795 }
5796 (active_item, panel_id)
5797 }
5798
5799 fn update_followers(
5800 &self,
5801 project_only: bool,
5802 update: proto::update_followers::Variant,
5803 _: &mut Window,
5804 cx: &mut App,
5805 ) -> Option<()> {
5806 // If this update only applies to for followers in the current project,
5807 // then skip it unless this project is shared. If it applies to all
5808 // followers, regardless of project, then set `project_id` to none,
5809 // indicating that it goes to all followers.
5810 let project_id = if project_only {
5811 Some(self.project.read(cx).remote_id()?)
5812 } else {
5813 None
5814 };
5815 self.app_state().workspace_store.update(cx, |store, cx| {
5816 store.update_followers(project_id, update, cx)
5817 })
5818 }
5819
5820 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
5821 self.follower_states.iter().find_map(|(leader_id, state)| {
5822 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
5823 Some(*leader_id)
5824 } else {
5825 None
5826 }
5827 })
5828 }
5829
5830 fn leader_updated(
5831 &mut self,
5832 leader_id: impl Into<CollaboratorId>,
5833 window: &mut Window,
5834 cx: &mut Context<Self>,
5835 ) -> Option<Box<dyn ItemHandle>> {
5836 cx.notify();
5837
5838 let leader_id = leader_id.into();
5839 let (panel_id, item) = match leader_id {
5840 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
5841 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
5842 };
5843
5844 let state = self.follower_states.get(&leader_id)?;
5845 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
5846 let pane;
5847 if let Some(panel_id) = panel_id {
5848 pane = self
5849 .activate_panel_for_proto_id(panel_id, window, cx)?
5850 .pane(cx)?;
5851 let state = self.follower_states.get_mut(&leader_id)?;
5852 state.dock_pane = Some(pane.clone());
5853 } else {
5854 pane = state.center_pane.clone();
5855 let state = self.follower_states.get_mut(&leader_id)?;
5856 if let Some(dock_pane) = state.dock_pane.take() {
5857 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
5858 }
5859 }
5860
5861 pane.update(cx, |pane, cx| {
5862 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
5863 if let Some(index) = pane.index_for_item(item.as_ref()) {
5864 pane.activate_item(index, false, false, window, cx);
5865 } else {
5866 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
5867 }
5868
5869 if focus_active_item {
5870 pane.focus_active_item(window, cx)
5871 }
5872 });
5873
5874 Some(item)
5875 }
5876
5877 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
5878 let state = self.follower_states.get(&CollaboratorId::Agent)?;
5879 let active_view_id = state.active_view_id?;
5880 Some(
5881 state
5882 .items_by_leader_view_id
5883 .get(&active_view_id)?
5884 .view
5885 .boxed_clone(),
5886 )
5887 }
5888
5889 fn active_item_for_peer(
5890 &self,
5891 peer_id: PeerId,
5892 window: &mut Window,
5893 cx: &mut Context<Self>,
5894 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
5895 let call = self.active_call()?;
5896 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
5897 let leader_in_this_app;
5898 let leader_in_this_project;
5899 match participant.location {
5900 ParticipantLocation::SharedProject { project_id } => {
5901 leader_in_this_app = true;
5902 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
5903 }
5904 ParticipantLocation::UnsharedProject => {
5905 leader_in_this_app = true;
5906 leader_in_this_project = false;
5907 }
5908 ParticipantLocation::External => {
5909 leader_in_this_app = false;
5910 leader_in_this_project = false;
5911 }
5912 };
5913 let state = self.follower_states.get(&peer_id.into())?;
5914 let mut item_to_activate = None;
5915 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
5916 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
5917 && (leader_in_this_project || !item.view.is_project_item(window, cx))
5918 {
5919 item_to_activate = Some((item.location, item.view.boxed_clone()));
5920 }
5921 } else if let Some(shared_screen) =
5922 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
5923 {
5924 item_to_activate = Some((None, Box::new(shared_screen)));
5925 }
5926 item_to_activate
5927 }
5928
5929 fn shared_screen_for_peer(
5930 &self,
5931 peer_id: PeerId,
5932 pane: &Entity<Pane>,
5933 window: &mut Window,
5934 cx: &mut App,
5935 ) -> Option<Entity<SharedScreen>> {
5936 self.active_call()?
5937 .create_shared_screen(peer_id, pane, window, cx)
5938 }
5939
5940 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5941 if window.is_window_active() {
5942 self.update_active_view_for_followers(window, cx);
5943
5944 if let Some(database_id) = self.database_id {
5945 cx.background_spawn(persistence::DB.update_timestamp(database_id))
5946 .detach();
5947 }
5948 } else {
5949 for pane in &self.panes {
5950 pane.update(cx, |pane, cx| {
5951 if let Some(item) = pane.active_item() {
5952 item.workspace_deactivated(window, cx);
5953 }
5954 for item in pane.items() {
5955 if matches!(
5956 item.workspace_settings(cx).autosave,
5957 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
5958 ) {
5959 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
5960 .detach_and_log_err(cx);
5961 }
5962 }
5963 });
5964 }
5965 }
5966 }
5967
5968 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
5969 self.active_call.as_ref().map(|(call, _)| &*call.0)
5970 }
5971
5972 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
5973 self.active_call.as_ref().map(|(call, _)| call.clone())
5974 }
5975
5976 fn on_active_call_event(
5977 &mut self,
5978 event: &ActiveCallEvent,
5979 window: &mut Window,
5980 cx: &mut Context<Self>,
5981 ) {
5982 match event {
5983 ActiveCallEvent::ParticipantLocationChanged { participant_id }
5984 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
5985 self.leader_updated(participant_id, window, cx);
5986 }
5987 }
5988 }
5989
5990 pub fn database_id(&self) -> Option<WorkspaceId> {
5991 self.database_id
5992 }
5993
5994 #[cfg(any(test, feature = "test-support"))]
5995 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
5996 self.database_id = Some(id);
5997 }
5998
5999 pub fn session_id(&self) -> Option<String> {
6000 self.session_id.clone()
6001 }
6002
6003 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6004 let Some(display) = window.display(cx) else {
6005 return Task::ready(());
6006 };
6007 let Ok(display_uuid) = display.uuid() else {
6008 return Task::ready(());
6009 };
6010
6011 let window_bounds = window.inner_window_bounds();
6012 let database_id = self.database_id;
6013 let has_paths = !self.root_paths(cx).is_empty();
6014
6015 cx.background_executor().spawn(async move {
6016 if !has_paths {
6017 persistence::write_default_window_bounds(window_bounds, display_uuid)
6018 .await
6019 .log_err();
6020 }
6021 if let Some(database_id) = database_id {
6022 DB.set_window_open_status(
6023 database_id,
6024 SerializedWindowBounds(window_bounds),
6025 display_uuid,
6026 )
6027 .await
6028 .log_err();
6029 } else {
6030 persistence::write_default_window_bounds(window_bounds, display_uuid)
6031 .await
6032 .log_err();
6033 }
6034 })
6035 }
6036
6037 /// Bypass the 200ms serialization throttle and write workspace state to
6038 /// the DB immediately. Returns a task the caller can await to ensure the
6039 /// write completes. Used by the quit handler so the most recent state
6040 /// isn't lost to a pending throttle timer when the process exits.
6041 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6042 self._schedule_serialize_workspace.take();
6043 self._serialize_workspace_task.take();
6044 self.bounds_save_task_queued.take();
6045
6046 let bounds_task = self.save_window_bounds(window, cx);
6047 let serialize_task = self.serialize_workspace_internal(window, cx);
6048 cx.spawn(async move |_| {
6049 bounds_task.await;
6050 serialize_task.await;
6051 })
6052 }
6053
6054 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6055 let project = self.project().read(cx);
6056 project
6057 .visible_worktrees(cx)
6058 .map(|worktree| worktree.read(cx).abs_path())
6059 .collect::<Vec<_>>()
6060 }
6061
6062 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6063 match member {
6064 Member::Axis(PaneAxis { members, .. }) => {
6065 for child in members.iter() {
6066 self.remove_panes(child.clone(), window, cx)
6067 }
6068 }
6069 Member::Pane(pane) => {
6070 self.force_remove_pane(&pane, &None, window, cx);
6071 }
6072 }
6073 }
6074
6075 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6076 self.session_id.take();
6077 self.serialize_workspace_internal(window, cx)
6078 }
6079
6080 fn force_remove_pane(
6081 &mut self,
6082 pane: &Entity<Pane>,
6083 focus_on: &Option<Entity<Pane>>,
6084 window: &mut Window,
6085 cx: &mut Context<Workspace>,
6086 ) {
6087 self.panes.retain(|p| p != pane);
6088 if let Some(focus_on) = focus_on {
6089 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6090 } else if self.active_pane() == pane {
6091 self.panes
6092 .last()
6093 .unwrap()
6094 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6095 }
6096 if self.last_active_center_pane == Some(pane.downgrade()) {
6097 self.last_active_center_pane = None;
6098 }
6099 cx.notify();
6100 }
6101
6102 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6103 if self._schedule_serialize_workspace.is_none() {
6104 self._schedule_serialize_workspace =
6105 Some(cx.spawn_in(window, async move |this, cx| {
6106 cx.background_executor()
6107 .timer(SERIALIZATION_THROTTLE_TIME)
6108 .await;
6109 this.update_in(cx, |this, window, cx| {
6110 this._serialize_workspace_task =
6111 Some(this.serialize_workspace_internal(window, cx));
6112 this._schedule_serialize_workspace.take();
6113 })
6114 .log_err();
6115 }));
6116 }
6117 }
6118
6119 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6120 let Some(database_id) = self.database_id() else {
6121 return Task::ready(());
6122 };
6123
6124 fn serialize_pane_handle(
6125 pane_handle: &Entity<Pane>,
6126 window: &mut Window,
6127 cx: &mut App,
6128 ) -> SerializedPane {
6129 let (items, active, pinned_count) = {
6130 let pane = pane_handle.read(cx);
6131 let active_item_id = pane.active_item().map(|item| item.item_id());
6132 (
6133 pane.items()
6134 .filter_map(|handle| {
6135 let handle = handle.to_serializable_item_handle(cx)?;
6136
6137 Some(SerializedItem {
6138 kind: Arc::from(handle.serialized_item_kind()),
6139 item_id: handle.item_id().as_u64(),
6140 active: Some(handle.item_id()) == active_item_id,
6141 preview: pane.is_active_preview_item(handle.item_id()),
6142 })
6143 })
6144 .collect::<Vec<_>>(),
6145 pane.has_focus(window, cx),
6146 pane.pinned_count(),
6147 )
6148 };
6149
6150 SerializedPane::new(items, active, pinned_count)
6151 }
6152
6153 fn build_serialized_pane_group(
6154 pane_group: &Member,
6155 window: &mut Window,
6156 cx: &mut App,
6157 ) -> SerializedPaneGroup {
6158 match pane_group {
6159 Member::Axis(PaneAxis {
6160 axis,
6161 members,
6162 flexes,
6163 bounding_boxes: _,
6164 }) => SerializedPaneGroup::Group {
6165 axis: SerializedAxis(*axis),
6166 children: members
6167 .iter()
6168 .map(|member| build_serialized_pane_group(member, window, cx))
6169 .collect::<Vec<_>>(),
6170 flexes: Some(flexes.lock().clone()),
6171 },
6172 Member::Pane(pane_handle) => {
6173 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6174 }
6175 }
6176 }
6177
6178 fn build_serialized_docks(
6179 this: &Workspace,
6180 window: &mut Window,
6181 cx: &mut App,
6182 ) -> DockStructure {
6183 this.capture_dock_state(window, cx)
6184 }
6185
6186 match self.workspace_location(cx) {
6187 WorkspaceLocation::Location(location, paths) => {
6188 let breakpoints = self.project.update(cx, |project, cx| {
6189 project
6190 .breakpoint_store()
6191 .read(cx)
6192 .all_source_breakpoints(cx)
6193 });
6194 let user_toolchains = self
6195 .project
6196 .read(cx)
6197 .user_toolchains(cx)
6198 .unwrap_or_default();
6199
6200 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6201 let docks = build_serialized_docks(self, window, cx);
6202 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6203
6204 let serialized_workspace = SerializedWorkspace {
6205 id: database_id,
6206 location,
6207 paths,
6208 center_group,
6209 window_bounds,
6210 display: Default::default(),
6211 docks,
6212 centered_layout: self.centered_layout,
6213 session_id: self.session_id.clone(),
6214 breakpoints,
6215 window_id: Some(window.window_handle().window_id().as_u64()),
6216 user_toolchains,
6217 };
6218
6219 window.spawn(cx, async move |_| {
6220 persistence::DB.save_workspace(serialized_workspace).await;
6221 })
6222 }
6223 WorkspaceLocation::DetachFromSession => {
6224 let window_bounds = SerializedWindowBounds(window.window_bounds());
6225 let display = window.display(cx).and_then(|d| d.uuid().ok());
6226 // Save dock state for empty local workspaces
6227 let docks = build_serialized_docks(self, window, cx);
6228 window.spawn(cx, async move |_| {
6229 persistence::DB
6230 .set_window_open_status(
6231 database_id,
6232 window_bounds,
6233 display.unwrap_or_default(),
6234 )
6235 .await
6236 .log_err();
6237 persistence::DB
6238 .set_session_id(database_id, None)
6239 .await
6240 .log_err();
6241 persistence::write_default_dock_state(docks).await.log_err();
6242 })
6243 }
6244 WorkspaceLocation::None => {
6245 // Save dock state for empty non-local workspaces
6246 let docks = build_serialized_docks(self, window, cx);
6247 window.spawn(cx, async move |_| {
6248 persistence::write_default_dock_state(docks).await.log_err();
6249 })
6250 }
6251 }
6252 }
6253
6254 fn has_any_items_open(&self, cx: &App) -> bool {
6255 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6256 }
6257
6258 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6259 let paths = PathList::new(&self.root_paths(cx));
6260 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6261 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6262 } else if self.project.read(cx).is_local() {
6263 if !paths.is_empty() || self.has_any_items_open(cx) {
6264 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6265 } else {
6266 WorkspaceLocation::DetachFromSession
6267 }
6268 } else {
6269 WorkspaceLocation::None
6270 }
6271 }
6272
6273 fn update_history(&self, cx: &mut App) {
6274 let Some(id) = self.database_id() else {
6275 return;
6276 };
6277 if !self.project.read(cx).is_local() {
6278 return;
6279 }
6280 if let Some(manager) = HistoryManager::global(cx) {
6281 let paths = PathList::new(&self.root_paths(cx));
6282 manager.update(cx, |this, cx| {
6283 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6284 });
6285 }
6286 }
6287
6288 async fn serialize_items(
6289 this: &WeakEntity<Self>,
6290 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6291 cx: &mut AsyncWindowContext,
6292 ) -> Result<()> {
6293 const CHUNK_SIZE: usize = 200;
6294
6295 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6296
6297 while let Some(items_received) = serializable_items.next().await {
6298 let unique_items =
6299 items_received
6300 .into_iter()
6301 .fold(HashMap::default(), |mut acc, item| {
6302 acc.entry(item.item_id()).or_insert(item);
6303 acc
6304 });
6305
6306 // We use into_iter() here so that the references to the items are moved into
6307 // the tasks and not kept alive while we're sleeping.
6308 for (_, item) in unique_items.into_iter() {
6309 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6310 item.serialize(workspace, false, window, cx)
6311 }) {
6312 cx.background_spawn(async move { task.await.log_err() })
6313 .detach();
6314 }
6315 }
6316
6317 cx.background_executor()
6318 .timer(SERIALIZATION_THROTTLE_TIME)
6319 .await;
6320 }
6321
6322 Ok(())
6323 }
6324
6325 pub(crate) fn enqueue_item_serialization(
6326 &mut self,
6327 item: Box<dyn SerializableItemHandle>,
6328 ) -> Result<()> {
6329 self.serializable_items_tx
6330 .unbounded_send(item)
6331 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6332 }
6333
6334 pub(crate) fn load_workspace(
6335 serialized_workspace: SerializedWorkspace,
6336 paths_to_open: Vec<Option<ProjectPath>>,
6337 window: &mut Window,
6338 cx: &mut Context<Workspace>,
6339 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6340 cx.spawn_in(window, async move |workspace, cx| {
6341 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6342
6343 let mut center_group = None;
6344 let mut center_items = None;
6345
6346 // Traverse the splits tree and add to things
6347 if let Some((group, active_pane, items)) = serialized_workspace
6348 .center_group
6349 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6350 .await
6351 {
6352 center_items = Some(items);
6353 center_group = Some((group, active_pane))
6354 }
6355
6356 let mut items_by_project_path = HashMap::default();
6357 let mut item_ids_by_kind = HashMap::default();
6358 let mut all_deserialized_items = Vec::default();
6359 cx.update(|_, cx| {
6360 for item in center_items.unwrap_or_default().into_iter().flatten() {
6361 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6362 item_ids_by_kind
6363 .entry(serializable_item_handle.serialized_item_kind())
6364 .or_insert(Vec::new())
6365 .push(item.item_id().as_u64() as ItemId);
6366 }
6367
6368 if let Some(project_path) = item.project_path(cx) {
6369 items_by_project_path.insert(project_path, item.clone());
6370 }
6371 all_deserialized_items.push(item);
6372 }
6373 })?;
6374
6375 let opened_items = paths_to_open
6376 .into_iter()
6377 .map(|path_to_open| {
6378 path_to_open
6379 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6380 })
6381 .collect::<Vec<_>>();
6382
6383 // Remove old panes from workspace panes list
6384 workspace.update_in(cx, |workspace, window, cx| {
6385 if let Some((center_group, active_pane)) = center_group {
6386 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6387
6388 // Swap workspace center group
6389 workspace.center = PaneGroup::with_root(center_group);
6390 workspace.center.set_is_center(true);
6391 workspace.center.mark_positions(cx);
6392
6393 if let Some(active_pane) = active_pane {
6394 workspace.set_active_pane(&active_pane, window, cx);
6395 cx.focus_self(window);
6396 } else {
6397 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6398 }
6399 }
6400
6401 let docks = serialized_workspace.docks;
6402
6403 for (dock, serialized_dock) in [
6404 (&mut workspace.right_dock, docks.right),
6405 (&mut workspace.left_dock, docks.left),
6406 (&mut workspace.bottom_dock, docks.bottom),
6407 ]
6408 .iter_mut()
6409 {
6410 dock.update(cx, |dock, cx| {
6411 dock.serialized_dock = Some(serialized_dock.clone());
6412 dock.restore_state(window, cx);
6413 });
6414 }
6415
6416 cx.notify();
6417 })?;
6418
6419 let _ = project
6420 .update(cx, |project, cx| {
6421 project
6422 .breakpoint_store()
6423 .update(cx, |breakpoint_store, cx| {
6424 breakpoint_store
6425 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6426 })
6427 })
6428 .await;
6429
6430 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6431 // after loading the items, we might have different items and in order to avoid
6432 // the database filling up, we delete items that haven't been loaded now.
6433 //
6434 // The items that have been loaded, have been saved after they've been added to the workspace.
6435 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6436 item_ids_by_kind
6437 .into_iter()
6438 .map(|(item_kind, loaded_items)| {
6439 SerializableItemRegistry::cleanup(
6440 item_kind,
6441 serialized_workspace.id,
6442 loaded_items,
6443 window,
6444 cx,
6445 )
6446 .log_err()
6447 })
6448 .collect::<Vec<_>>()
6449 })?;
6450
6451 futures::future::join_all(clean_up_tasks).await;
6452
6453 workspace
6454 .update_in(cx, |workspace, window, cx| {
6455 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6456 workspace.serialize_workspace_internal(window, cx).detach();
6457
6458 // Ensure that we mark the window as edited if we did load dirty items
6459 workspace.update_window_edited(window, cx);
6460 })
6461 .ok();
6462
6463 Ok(opened_items)
6464 })
6465 }
6466
6467 pub fn key_context(&self, cx: &App) -> KeyContext {
6468 let mut context = KeyContext::new_with_defaults();
6469 context.add("Workspace");
6470 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6471 if let Some(status) = self
6472 .debugger_provider
6473 .as_ref()
6474 .and_then(|provider| provider.active_thread_state(cx))
6475 {
6476 match status {
6477 ThreadStatus::Running | ThreadStatus::Stepping => {
6478 context.add("debugger_running");
6479 }
6480 ThreadStatus::Stopped => context.add("debugger_stopped"),
6481 ThreadStatus::Exited | ThreadStatus::Ended => {}
6482 }
6483 }
6484
6485 if self.left_dock.read(cx).is_open() {
6486 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6487 context.set("left_dock", active_panel.panel_key());
6488 }
6489 }
6490
6491 if self.right_dock.read(cx).is_open() {
6492 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6493 context.set("right_dock", active_panel.panel_key());
6494 }
6495 }
6496
6497 if self.bottom_dock.read(cx).is_open() {
6498 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6499 context.set("bottom_dock", active_panel.panel_key());
6500 }
6501 }
6502
6503 context
6504 }
6505
6506 /// Multiworkspace uses this to add workspace action handling to itself
6507 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6508 self.add_workspace_actions_listeners(div, window, cx)
6509 .on_action(cx.listener(
6510 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6511 for action in &action_sequence.0 {
6512 window.dispatch_action(action.boxed_clone(), cx);
6513 }
6514 },
6515 ))
6516 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6517 .on_action(cx.listener(Self::close_all_items_and_panes))
6518 .on_action(cx.listener(Self::close_item_in_all_panes))
6519 .on_action(cx.listener(Self::save_all))
6520 .on_action(cx.listener(Self::send_keystrokes))
6521 .on_action(cx.listener(Self::add_folder_to_project))
6522 .on_action(cx.listener(Self::follow_next_collaborator))
6523 .on_action(cx.listener(Self::activate_pane_at_index))
6524 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6525 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6526 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6527 .on_action(cx.listener(Self::toggle_theme_mode))
6528 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6529 let pane = workspace.active_pane().clone();
6530 workspace.unfollow_in_pane(&pane, window, cx);
6531 }))
6532 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6533 workspace
6534 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6535 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6536 }))
6537 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6538 workspace
6539 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6540 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6541 }))
6542 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6543 workspace
6544 .save_active_item(SaveIntent::SaveAs, window, cx)
6545 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6546 }))
6547 .on_action(
6548 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6549 workspace.activate_previous_pane(window, cx)
6550 }),
6551 )
6552 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6553 workspace.activate_next_pane(window, cx)
6554 }))
6555 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6556 workspace.activate_last_pane(window, cx)
6557 }))
6558 .on_action(
6559 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6560 workspace.activate_next_window(cx)
6561 }),
6562 )
6563 .on_action(
6564 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6565 workspace.activate_previous_window(cx)
6566 }),
6567 )
6568 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6569 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6570 }))
6571 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6572 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6573 }))
6574 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6575 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6576 }))
6577 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6578 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6579 }))
6580 .on_action(cx.listener(
6581 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6582 workspace.move_item_to_pane_in_direction(action, window, cx)
6583 },
6584 ))
6585 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6586 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6587 }))
6588 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6589 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6590 }))
6591 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6592 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6593 }))
6594 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6595 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6596 }))
6597 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6598 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6599 SplitDirection::Down,
6600 SplitDirection::Up,
6601 SplitDirection::Right,
6602 SplitDirection::Left,
6603 ];
6604 for dir in DIRECTION_PRIORITY {
6605 if workspace.find_pane_in_direction(dir, cx).is_some() {
6606 workspace.swap_pane_in_direction(dir, cx);
6607 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6608 break;
6609 }
6610 }
6611 }))
6612 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6613 workspace.move_pane_to_border(SplitDirection::Left, cx)
6614 }))
6615 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6616 workspace.move_pane_to_border(SplitDirection::Right, cx)
6617 }))
6618 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6619 workspace.move_pane_to_border(SplitDirection::Up, cx)
6620 }))
6621 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6622 workspace.move_pane_to_border(SplitDirection::Down, cx)
6623 }))
6624 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6625 this.toggle_dock(DockPosition::Left, window, cx);
6626 }))
6627 .on_action(cx.listener(
6628 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6629 workspace.toggle_dock(DockPosition::Right, window, cx);
6630 },
6631 ))
6632 .on_action(cx.listener(
6633 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6634 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6635 },
6636 ))
6637 .on_action(cx.listener(
6638 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6639 if !workspace.close_active_dock(window, cx) {
6640 cx.propagate();
6641 }
6642 },
6643 ))
6644 .on_action(
6645 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6646 workspace.close_all_docks(window, cx);
6647 }),
6648 )
6649 .on_action(cx.listener(Self::toggle_all_docks))
6650 .on_action(cx.listener(
6651 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6652 workspace.clear_all_notifications(cx);
6653 },
6654 ))
6655 .on_action(cx.listener(
6656 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6657 workspace.clear_navigation_history(window, cx);
6658 },
6659 ))
6660 .on_action(cx.listener(
6661 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6662 if let Some((notification_id, _)) = workspace.notifications.pop() {
6663 workspace.suppress_notification(¬ification_id, cx);
6664 }
6665 },
6666 ))
6667 .on_action(cx.listener(
6668 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6669 workspace.show_worktree_trust_security_modal(true, window, cx);
6670 },
6671 ))
6672 .on_action(
6673 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6674 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6675 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6676 trusted_worktrees.clear_trusted_paths()
6677 });
6678 let clear_task = persistence::DB.clear_trusted_worktrees();
6679 cx.spawn(async move |_, cx| {
6680 if clear_task.await.log_err().is_some() {
6681 cx.update(|cx| reload(cx));
6682 }
6683 })
6684 .detach();
6685 }
6686 }),
6687 )
6688 .on_action(cx.listener(
6689 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
6690 workspace.reopen_closed_item(window, cx).detach();
6691 },
6692 ))
6693 .on_action(cx.listener(
6694 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
6695 for dock in workspace.all_docks() {
6696 if dock.focus_handle(cx).contains_focused(window, cx) {
6697 let Some(panel) = dock.read(cx).active_panel() else {
6698 return;
6699 };
6700
6701 // Set to `None`, then the size will fall back to the default.
6702 panel.clone().set_size(None, window, cx);
6703
6704 return;
6705 }
6706 }
6707 },
6708 ))
6709 .on_action(cx.listener(
6710 |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
6711 for dock in workspace.all_docks() {
6712 if let Some(panel) = dock.read(cx).visible_panel() {
6713 // Set to `None`, then the size will fall back to the default.
6714 panel.clone().set_size(None, window, cx);
6715 }
6716 }
6717 },
6718 ))
6719 .on_action(cx.listener(
6720 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
6721 adjust_active_dock_size_by_px(
6722 px_with_ui_font_fallback(act.px, cx),
6723 workspace,
6724 window,
6725 cx,
6726 );
6727 },
6728 ))
6729 .on_action(cx.listener(
6730 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
6731 adjust_active_dock_size_by_px(
6732 px_with_ui_font_fallback(act.px, cx) * -1.,
6733 workspace,
6734 window,
6735 cx,
6736 );
6737 },
6738 ))
6739 .on_action(cx.listener(
6740 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
6741 adjust_open_docks_size_by_px(
6742 px_with_ui_font_fallback(act.px, cx),
6743 workspace,
6744 window,
6745 cx,
6746 );
6747 },
6748 ))
6749 .on_action(cx.listener(
6750 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
6751 adjust_open_docks_size_by_px(
6752 px_with_ui_font_fallback(act.px, cx) * -1.,
6753 workspace,
6754 window,
6755 cx,
6756 );
6757 },
6758 ))
6759 .on_action(cx.listener(Workspace::toggle_centered_layout))
6760 .on_action(cx.listener(
6761 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
6762 if let Some(active_dock) = workspace.active_dock(window, cx) {
6763 let dock = active_dock.read(cx);
6764 if let Some(active_panel) = dock.active_panel() {
6765 if active_panel.pane(cx).is_none() {
6766 let mut recent_pane: Option<Entity<Pane>> = None;
6767 let mut recent_timestamp = 0;
6768 for pane_handle in workspace.panes() {
6769 let pane = pane_handle.read(cx);
6770 for entry in pane.activation_history() {
6771 if entry.timestamp > recent_timestamp {
6772 recent_timestamp = entry.timestamp;
6773 recent_pane = Some(pane_handle.clone());
6774 }
6775 }
6776 }
6777
6778 if let Some(pane) = recent_pane {
6779 pane.update(cx, |pane, cx| {
6780 let current_index = pane.active_item_index();
6781 let items_len = pane.items_len();
6782 if items_len > 0 {
6783 let next_index = if current_index + 1 < items_len {
6784 current_index + 1
6785 } else {
6786 0
6787 };
6788 pane.activate_item(
6789 next_index, false, false, window, cx,
6790 );
6791 }
6792 });
6793 return;
6794 }
6795 }
6796 }
6797 }
6798 cx.propagate();
6799 },
6800 ))
6801 .on_action(cx.listener(
6802 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
6803 if let Some(active_dock) = workspace.active_dock(window, cx) {
6804 let dock = active_dock.read(cx);
6805 if let Some(active_panel) = dock.active_panel() {
6806 if active_panel.pane(cx).is_none() {
6807 let mut recent_pane: Option<Entity<Pane>> = None;
6808 let mut recent_timestamp = 0;
6809 for pane_handle in workspace.panes() {
6810 let pane = pane_handle.read(cx);
6811 for entry in pane.activation_history() {
6812 if entry.timestamp > recent_timestamp {
6813 recent_timestamp = entry.timestamp;
6814 recent_pane = Some(pane_handle.clone());
6815 }
6816 }
6817 }
6818
6819 if let Some(pane) = recent_pane {
6820 pane.update(cx, |pane, cx| {
6821 let current_index = pane.active_item_index();
6822 let items_len = pane.items_len();
6823 if items_len > 0 {
6824 let prev_index = if current_index > 0 {
6825 current_index - 1
6826 } else {
6827 items_len.saturating_sub(1)
6828 };
6829 pane.activate_item(
6830 prev_index, false, false, window, cx,
6831 );
6832 }
6833 });
6834 return;
6835 }
6836 }
6837 }
6838 }
6839 cx.propagate();
6840 },
6841 ))
6842 .on_action(cx.listener(
6843 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
6844 if let Some(active_dock) = workspace.active_dock(window, cx) {
6845 let dock = active_dock.read(cx);
6846 if let Some(active_panel) = dock.active_panel() {
6847 if active_panel.pane(cx).is_none() {
6848 let active_pane = workspace.active_pane().clone();
6849 active_pane.update(cx, |pane, cx| {
6850 pane.close_active_item(action, window, cx)
6851 .detach_and_log_err(cx);
6852 });
6853 return;
6854 }
6855 }
6856 }
6857 cx.propagate();
6858 },
6859 ))
6860 .on_action(
6861 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
6862 let pane = workspace.active_pane().clone();
6863 if let Some(item) = pane.read(cx).active_item() {
6864 item.toggle_read_only(window, cx);
6865 }
6866 }),
6867 )
6868 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
6869 workspace.focus_center_pane(window, cx);
6870 }))
6871 .on_action(cx.listener(Workspace::cancel))
6872 }
6873
6874 #[cfg(any(test, feature = "test-support"))]
6875 pub fn set_random_database_id(&mut self) {
6876 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
6877 }
6878
6879 #[cfg(any(test, feature = "test-support"))]
6880 pub(crate) fn test_new(
6881 project: Entity<Project>,
6882 window: &mut Window,
6883 cx: &mut Context<Self>,
6884 ) -> Self {
6885 use node_runtime::NodeRuntime;
6886 use session::Session;
6887
6888 let client = project.read(cx).client();
6889 let user_store = project.read(cx).user_store();
6890 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
6891 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
6892 window.activate_window();
6893 let app_state = Arc::new(AppState {
6894 languages: project.read(cx).languages().clone(),
6895 workspace_store,
6896 client,
6897 user_store,
6898 fs: project.read(cx).fs().clone(),
6899 build_window_options: |_, _| Default::default(),
6900 node_runtime: NodeRuntime::unavailable(),
6901 session,
6902 });
6903 let workspace = Self::new(Default::default(), project, app_state, window, cx);
6904 workspace
6905 .active_pane
6906 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6907 workspace
6908 }
6909
6910 pub fn register_action<A: Action>(
6911 &mut self,
6912 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
6913 ) -> &mut Self {
6914 let callback = Arc::new(callback);
6915
6916 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
6917 let callback = callback.clone();
6918 div.on_action(cx.listener(move |workspace, event, window, cx| {
6919 (callback)(workspace, event, window, cx)
6920 }))
6921 }));
6922 self
6923 }
6924 pub fn register_action_renderer(
6925 &mut self,
6926 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
6927 ) -> &mut Self {
6928 self.workspace_actions.push(Box::new(callback));
6929 self
6930 }
6931
6932 fn add_workspace_actions_listeners(
6933 &self,
6934 mut div: Div,
6935 window: &mut Window,
6936 cx: &mut Context<Self>,
6937 ) -> Div {
6938 for action in self.workspace_actions.iter() {
6939 div = (action)(div, self, window, cx)
6940 }
6941 div
6942 }
6943
6944 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
6945 self.modal_layer.read(cx).has_active_modal()
6946 }
6947
6948 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
6949 self.modal_layer.read(cx).active_modal()
6950 }
6951
6952 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
6953 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
6954 /// If no modal is active, the new modal will be shown.
6955 ///
6956 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
6957 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
6958 /// will not be shown.
6959 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
6960 where
6961 B: FnOnce(&mut Window, &mut Context<V>) -> V,
6962 {
6963 self.modal_layer.update(cx, |modal_layer, cx| {
6964 modal_layer.toggle_modal(window, cx, build)
6965 })
6966 }
6967
6968 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
6969 self.modal_layer
6970 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
6971 }
6972
6973 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
6974 self.toast_layer
6975 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
6976 }
6977
6978 pub fn toggle_centered_layout(
6979 &mut self,
6980 _: &ToggleCenteredLayout,
6981 _: &mut Window,
6982 cx: &mut Context<Self>,
6983 ) {
6984 self.centered_layout = !self.centered_layout;
6985 if let Some(database_id) = self.database_id() {
6986 cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
6987 .detach_and_log_err(cx);
6988 }
6989 cx.notify();
6990 }
6991
6992 fn adjust_padding(padding: Option<f32>) -> f32 {
6993 padding
6994 .unwrap_or(CenteredPaddingSettings::default().0)
6995 .clamp(
6996 CenteredPaddingSettings::MIN_PADDING,
6997 CenteredPaddingSettings::MAX_PADDING,
6998 )
6999 }
7000
7001 fn render_dock(
7002 &self,
7003 position: DockPosition,
7004 dock: &Entity<Dock>,
7005 window: &mut Window,
7006 cx: &mut App,
7007 ) -> Option<Div> {
7008 if self.zoomed_position == Some(position) {
7009 return None;
7010 }
7011
7012 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7013 let pane = panel.pane(cx)?;
7014 let follower_states = &self.follower_states;
7015 leader_border_for_pane(follower_states, &pane, window, cx)
7016 });
7017
7018 Some(
7019 div()
7020 .flex()
7021 .flex_none()
7022 .overflow_hidden()
7023 .child(dock.clone())
7024 .children(leader_border),
7025 )
7026 }
7027
7028 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7029 window
7030 .root::<MultiWorkspace>()
7031 .flatten()
7032 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7033 }
7034
7035 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7036 self.zoomed.as_ref()
7037 }
7038
7039 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7040 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7041 return;
7042 };
7043 let windows = cx.windows();
7044 let next_window =
7045 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7046 || {
7047 windows
7048 .iter()
7049 .cycle()
7050 .skip_while(|window| window.window_id() != current_window_id)
7051 .nth(1)
7052 },
7053 );
7054
7055 if let Some(window) = next_window {
7056 window
7057 .update(cx, |_, window, _| window.activate_window())
7058 .ok();
7059 }
7060 }
7061
7062 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7063 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7064 return;
7065 };
7066 let windows = cx.windows();
7067 let prev_window =
7068 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7069 || {
7070 windows
7071 .iter()
7072 .rev()
7073 .cycle()
7074 .skip_while(|window| window.window_id() != current_window_id)
7075 .nth(1)
7076 },
7077 );
7078
7079 if let Some(window) = prev_window {
7080 window
7081 .update(cx, |_, window, _| window.activate_window())
7082 .ok();
7083 }
7084 }
7085
7086 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7087 if cx.stop_active_drag(window) {
7088 } else if let Some((notification_id, _)) = self.notifications.pop() {
7089 dismiss_app_notification(¬ification_id, cx);
7090 } else {
7091 cx.propagate();
7092 }
7093 }
7094
7095 fn adjust_dock_size_by_px(
7096 &mut self,
7097 panel_size: Pixels,
7098 dock_pos: DockPosition,
7099 px: Pixels,
7100 window: &mut Window,
7101 cx: &mut Context<Self>,
7102 ) {
7103 match dock_pos {
7104 DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
7105 DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
7106 DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
7107 }
7108 }
7109
7110 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7111 let workspace_width = self.bounds.size.width;
7112 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7113
7114 self.right_dock.read_with(cx, |right_dock, cx| {
7115 let right_dock_size = right_dock
7116 .active_panel_size(window, cx)
7117 .unwrap_or(Pixels::ZERO);
7118 if right_dock_size + size > workspace_width {
7119 size = workspace_width - right_dock_size
7120 }
7121 });
7122
7123 self.left_dock.update(cx, |left_dock, cx| {
7124 if WorkspaceSettings::get_global(cx)
7125 .resize_all_panels_in_dock
7126 .contains(&DockPosition::Left)
7127 {
7128 left_dock.resize_all_panels(Some(size), window, cx);
7129 } else {
7130 left_dock.resize_active_panel(Some(size), window, cx);
7131 }
7132 });
7133 }
7134
7135 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7136 let workspace_width = self.bounds.size.width;
7137 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7138 self.left_dock.read_with(cx, |left_dock, cx| {
7139 let left_dock_size = left_dock
7140 .active_panel_size(window, cx)
7141 .unwrap_or(Pixels::ZERO);
7142 if left_dock_size + size > workspace_width {
7143 size = workspace_width - left_dock_size
7144 }
7145 });
7146 self.right_dock.update(cx, |right_dock, cx| {
7147 if WorkspaceSettings::get_global(cx)
7148 .resize_all_panels_in_dock
7149 .contains(&DockPosition::Right)
7150 {
7151 right_dock.resize_all_panels(Some(size), window, cx);
7152 } else {
7153 right_dock.resize_active_panel(Some(size), window, cx);
7154 }
7155 });
7156 }
7157
7158 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7159 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7160 self.bottom_dock.update(cx, |bottom_dock, cx| {
7161 if WorkspaceSettings::get_global(cx)
7162 .resize_all_panels_in_dock
7163 .contains(&DockPosition::Bottom)
7164 {
7165 bottom_dock.resize_all_panels(Some(size), window, cx);
7166 } else {
7167 bottom_dock.resize_active_panel(Some(size), window, cx);
7168 }
7169 });
7170 }
7171
7172 fn toggle_edit_predictions_all_files(
7173 &mut self,
7174 _: &ToggleEditPrediction,
7175 _window: &mut Window,
7176 cx: &mut Context<Self>,
7177 ) {
7178 let fs = self.project().read(cx).fs().clone();
7179 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7180 update_settings_file(fs, cx, move |file, _| {
7181 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7182 });
7183 }
7184
7185 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7186 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7187 let next_mode = match current_mode {
7188 Some(theme::ThemeAppearanceMode::Light) => theme::ThemeAppearanceMode::Dark,
7189 Some(theme::ThemeAppearanceMode::Dark) => theme::ThemeAppearanceMode::Light,
7190 Some(theme::ThemeAppearanceMode::System) | None => match cx.theme().appearance() {
7191 theme::Appearance::Light => theme::ThemeAppearanceMode::Dark,
7192 theme::Appearance::Dark => theme::ThemeAppearanceMode::Light,
7193 },
7194 };
7195
7196 let fs = self.project().read(cx).fs().clone();
7197 settings::update_settings_file(fs, cx, move |settings, _cx| {
7198 theme::set_mode(settings, next_mode);
7199 });
7200 }
7201
7202 pub fn show_worktree_trust_security_modal(
7203 &mut self,
7204 toggle: bool,
7205 window: &mut Window,
7206 cx: &mut Context<Self>,
7207 ) {
7208 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7209 if toggle {
7210 security_modal.update(cx, |security_modal, cx| {
7211 security_modal.dismiss(cx);
7212 })
7213 } else {
7214 security_modal.update(cx, |security_modal, cx| {
7215 security_modal.refresh_restricted_paths(cx);
7216 });
7217 }
7218 } else {
7219 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7220 .map(|trusted_worktrees| {
7221 trusted_worktrees
7222 .read(cx)
7223 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7224 })
7225 .unwrap_or(false);
7226 if has_restricted_worktrees {
7227 let project = self.project().read(cx);
7228 let remote_host = project
7229 .remote_connection_options(cx)
7230 .map(RemoteHostLocation::from);
7231 let worktree_store = project.worktree_store().downgrade();
7232 self.toggle_modal(window, cx, |_, cx| {
7233 SecurityModal::new(worktree_store, remote_host, cx)
7234 });
7235 }
7236 }
7237 }
7238}
7239
7240pub trait AnyActiveCall {
7241 fn entity(&self) -> AnyEntity;
7242 fn is_in_room(&self, _: &App) -> bool;
7243 fn room_id(&self, _: &App) -> Option<u64>;
7244 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7245 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7246 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7247 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7248 fn is_sharing_project(&self, _: &App) -> bool;
7249 fn has_remote_participants(&self, _: &App) -> bool;
7250 fn local_participant_is_guest(&self, _: &App) -> bool;
7251 fn client(&self, _: &App) -> Arc<Client>;
7252 fn share_on_join(&self, _: &App) -> bool;
7253 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7254 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7255 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7256 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7257 fn join_project(
7258 &self,
7259 _: u64,
7260 _: Arc<LanguageRegistry>,
7261 _: Arc<dyn Fs>,
7262 _: &mut App,
7263 ) -> Task<Result<Entity<Project>>>;
7264 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7265 fn subscribe(
7266 &self,
7267 _: &mut Window,
7268 _: &mut Context<Workspace>,
7269 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7270 ) -> Subscription;
7271 fn create_shared_screen(
7272 &self,
7273 _: PeerId,
7274 _: &Entity<Pane>,
7275 _: &mut Window,
7276 _: &mut App,
7277 ) -> Option<Entity<SharedScreen>>;
7278}
7279
7280#[derive(Clone)]
7281pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7282impl Global for GlobalAnyActiveCall {}
7283
7284impl GlobalAnyActiveCall {
7285 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7286 cx.try_global()
7287 }
7288
7289 pub(crate) fn global(cx: &App) -> &Self {
7290 cx.global()
7291 }
7292}
7293
7294pub fn merge_conflict_notification_id() -> NotificationId {
7295 struct MergeConflictNotification;
7296 NotificationId::unique::<MergeConflictNotification>()
7297}
7298
7299/// Workspace-local view of a remote participant's location.
7300#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7301pub enum ParticipantLocation {
7302 SharedProject { project_id: u64 },
7303 UnsharedProject,
7304 External,
7305}
7306
7307impl ParticipantLocation {
7308 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7309 match location
7310 .and_then(|l| l.variant)
7311 .context("participant location was not provided")?
7312 {
7313 proto::participant_location::Variant::SharedProject(project) => {
7314 Ok(Self::SharedProject {
7315 project_id: project.id,
7316 })
7317 }
7318 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7319 proto::participant_location::Variant::External(_) => Ok(Self::External),
7320 }
7321 }
7322}
7323/// Workspace-local view of a remote collaborator's state.
7324/// This is the subset of `call::RemoteParticipant` that workspace needs.
7325#[derive(Clone)]
7326pub struct RemoteCollaborator {
7327 pub user: Arc<User>,
7328 pub peer_id: PeerId,
7329 pub location: ParticipantLocation,
7330 pub participant_index: ParticipantIndex,
7331}
7332
7333pub enum ActiveCallEvent {
7334 ParticipantLocationChanged { participant_id: PeerId },
7335 RemoteVideoTracksChanged { participant_id: PeerId },
7336}
7337
7338fn leader_border_for_pane(
7339 follower_states: &HashMap<CollaboratorId, FollowerState>,
7340 pane: &Entity<Pane>,
7341 _: &Window,
7342 cx: &App,
7343) -> Option<Div> {
7344 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7345 if state.pane() == pane {
7346 Some((*leader_id, state))
7347 } else {
7348 None
7349 }
7350 })?;
7351
7352 let mut leader_color = match leader_id {
7353 CollaboratorId::PeerId(leader_peer_id) => {
7354 let leader = GlobalAnyActiveCall::try_global(cx)?
7355 .0
7356 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7357
7358 cx.theme()
7359 .players()
7360 .color_for_participant(leader.participant_index.0)
7361 .cursor
7362 }
7363 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7364 };
7365 leader_color.fade_out(0.3);
7366 Some(
7367 div()
7368 .absolute()
7369 .size_full()
7370 .left_0()
7371 .top_0()
7372 .border_2()
7373 .border_color(leader_color),
7374 )
7375}
7376
7377fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7378 ZED_WINDOW_POSITION
7379 .zip(*ZED_WINDOW_SIZE)
7380 .map(|(position, size)| Bounds {
7381 origin: position,
7382 size,
7383 })
7384}
7385
7386fn open_items(
7387 serialized_workspace: Option<SerializedWorkspace>,
7388 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7389 window: &mut Window,
7390 cx: &mut Context<Workspace>,
7391) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7392 let restored_items = serialized_workspace.map(|serialized_workspace| {
7393 Workspace::load_workspace(
7394 serialized_workspace,
7395 project_paths_to_open
7396 .iter()
7397 .map(|(_, project_path)| project_path)
7398 .cloned()
7399 .collect(),
7400 window,
7401 cx,
7402 )
7403 });
7404
7405 cx.spawn_in(window, async move |workspace, cx| {
7406 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7407
7408 if let Some(restored_items) = restored_items {
7409 let restored_items = restored_items.await?;
7410
7411 let restored_project_paths = restored_items
7412 .iter()
7413 .filter_map(|item| {
7414 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7415 .ok()
7416 .flatten()
7417 })
7418 .collect::<HashSet<_>>();
7419
7420 for restored_item in restored_items {
7421 opened_items.push(restored_item.map(Ok));
7422 }
7423
7424 project_paths_to_open
7425 .iter_mut()
7426 .for_each(|(_, project_path)| {
7427 if let Some(project_path_to_open) = project_path
7428 && restored_project_paths.contains(project_path_to_open)
7429 {
7430 *project_path = None;
7431 }
7432 });
7433 } else {
7434 for _ in 0..project_paths_to_open.len() {
7435 opened_items.push(None);
7436 }
7437 }
7438 assert!(opened_items.len() == project_paths_to_open.len());
7439
7440 let tasks =
7441 project_paths_to_open
7442 .into_iter()
7443 .enumerate()
7444 .map(|(ix, (abs_path, project_path))| {
7445 let workspace = workspace.clone();
7446 cx.spawn(async move |cx| {
7447 let file_project_path = project_path?;
7448 let abs_path_task = workspace.update(cx, |workspace, cx| {
7449 workspace.project().update(cx, |project, cx| {
7450 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7451 })
7452 });
7453
7454 // We only want to open file paths here. If one of the items
7455 // here is a directory, it was already opened further above
7456 // with a `find_or_create_worktree`.
7457 if let Ok(task) = abs_path_task
7458 && task.await.is_none_or(|p| p.is_file())
7459 {
7460 return Some((
7461 ix,
7462 workspace
7463 .update_in(cx, |workspace, window, cx| {
7464 workspace.open_path(
7465 file_project_path,
7466 None,
7467 true,
7468 window,
7469 cx,
7470 )
7471 })
7472 .log_err()?
7473 .await,
7474 ));
7475 }
7476 None
7477 })
7478 });
7479
7480 let tasks = tasks.collect::<Vec<_>>();
7481
7482 let tasks = futures::future::join_all(tasks);
7483 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7484 opened_items[ix] = Some(path_open_result);
7485 }
7486
7487 Ok(opened_items)
7488 })
7489}
7490
7491enum ActivateInDirectionTarget {
7492 Pane(Entity<Pane>),
7493 Dock(Entity<Dock>),
7494}
7495
7496fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7497 window
7498 .update(cx, |multi_workspace, _, cx| {
7499 let workspace = multi_workspace.workspace().clone();
7500 workspace.update(cx, |workspace, cx| {
7501 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7502 struct DatabaseFailedNotification;
7503
7504 workspace.show_notification(
7505 NotificationId::unique::<DatabaseFailedNotification>(),
7506 cx,
7507 |cx| {
7508 cx.new(|cx| {
7509 MessageNotification::new("Failed to load the database file.", cx)
7510 .primary_message("File an Issue")
7511 .primary_icon(IconName::Plus)
7512 .primary_on_click(|window, cx| {
7513 window.dispatch_action(Box::new(FileBugReport), cx)
7514 })
7515 })
7516 },
7517 );
7518 }
7519 });
7520 })
7521 .log_err();
7522}
7523
7524fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7525 if val == 0 {
7526 ThemeSettings::get_global(cx).ui_font_size(cx)
7527 } else {
7528 px(val as f32)
7529 }
7530}
7531
7532fn adjust_active_dock_size_by_px(
7533 px: Pixels,
7534 workspace: &mut Workspace,
7535 window: &mut Window,
7536 cx: &mut Context<Workspace>,
7537) {
7538 let Some(active_dock) = workspace
7539 .all_docks()
7540 .into_iter()
7541 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7542 else {
7543 return;
7544 };
7545 let dock = active_dock.read(cx);
7546 let Some(panel_size) = dock.active_panel_size(window, cx) else {
7547 return;
7548 };
7549 let dock_pos = dock.position();
7550 workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
7551}
7552
7553fn adjust_open_docks_size_by_px(
7554 px: Pixels,
7555 workspace: &mut Workspace,
7556 window: &mut Window,
7557 cx: &mut Context<Workspace>,
7558) {
7559 let docks = workspace
7560 .all_docks()
7561 .into_iter()
7562 .filter_map(|dock| {
7563 if dock.read(cx).is_open() {
7564 let dock = dock.read(cx);
7565 let panel_size = dock.active_panel_size(window, cx)?;
7566 let dock_pos = dock.position();
7567 Some((panel_size, dock_pos, px))
7568 } else {
7569 None
7570 }
7571 })
7572 .collect::<Vec<_>>();
7573
7574 docks
7575 .into_iter()
7576 .for_each(|(panel_size, dock_pos, offset)| {
7577 workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
7578 });
7579}
7580
7581impl Focusable for Workspace {
7582 fn focus_handle(&self, cx: &App) -> FocusHandle {
7583 self.active_pane.focus_handle(cx)
7584 }
7585}
7586
7587#[derive(Clone)]
7588struct DraggedDock(DockPosition);
7589
7590impl Render for DraggedDock {
7591 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7592 gpui::Empty
7593 }
7594}
7595
7596impl Render for Workspace {
7597 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7598 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7599 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7600 log::info!("Rendered first frame");
7601 }
7602
7603 let centered_layout = self.centered_layout
7604 && self.center.panes().len() == 1
7605 && self.active_item(cx).is_some();
7606 let render_padding = |size| {
7607 (size > 0.0).then(|| {
7608 div()
7609 .h_full()
7610 .w(relative(size))
7611 .bg(cx.theme().colors().editor_background)
7612 .border_color(cx.theme().colors().pane_group_border)
7613 })
7614 };
7615 let paddings = if centered_layout {
7616 let settings = WorkspaceSettings::get_global(cx).centered_layout;
7617 (
7618 render_padding(Self::adjust_padding(
7619 settings.left_padding.map(|padding| padding.0),
7620 )),
7621 render_padding(Self::adjust_padding(
7622 settings.right_padding.map(|padding| padding.0),
7623 )),
7624 )
7625 } else {
7626 (None, None)
7627 };
7628 let ui_font = theme::setup_ui_font(window, cx);
7629
7630 let theme = cx.theme().clone();
7631 let colors = theme.colors();
7632 let notification_entities = self
7633 .notifications
7634 .iter()
7635 .map(|(_, notification)| notification.entity_id())
7636 .collect::<Vec<_>>();
7637 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
7638
7639 div()
7640 .relative()
7641 .size_full()
7642 .flex()
7643 .flex_col()
7644 .font(ui_font)
7645 .gap_0()
7646 .justify_start()
7647 .items_start()
7648 .text_color(colors.text)
7649 .overflow_hidden()
7650 .children(self.titlebar_item.clone())
7651 .on_modifiers_changed(move |_, _, cx| {
7652 for &id in ¬ification_entities {
7653 cx.notify(id);
7654 }
7655 })
7656 .child(
7657 div()
7658 .size_full()
7659 .relative()
7660 .flex_1()
7661 .flex()
7662 .flex_col()
7663 .child(
7664 div()
7665 .id("workspace")
7666 .bg(colors.background)
7667 .relative()
7668 .flex_1()
7669 .w_full()
7670 .flex()
7671 .flex_col()
7672 .overflow_hidden()
7673 .border_t_1()
7674 .border_b_1()
7675 .border_color(colors.border)
7676 .child({
7677 let this = cx.entity();
7678 canvas(
7679 move |bounds, window, cx| {
7680 this.update(cx, |this, cx| {
7681 let bounds_changed = this.bounds != bounds;
7682 this.bounds = bounds;
7683
7684 if bounds_changed {
7685 this.left_dock.update(cx, |dock, cx| {
7686 dock.clamp_panel_size(
7687 bounds.size.width,
7688 window,
7689 cx,
7690 )
7691 });
7692
7693 this.right_dock.update(cx, |dock, cx| {
7694 dock.clamp_panel_size(
7695 bounds.size.width,
7696 window,
7697 cx,
7698 )
7699 });
7700
7701 this.bottom_dock.update(cx, |dock, cx| {
7702 dock.clamp_panel_size(
7703 bounds.size.height,
7704 window,
7705 cx,
7706 )
7707 });
7708 }
7709 })
7710 },
7711 |_, _, _, _| {},
7712 )
7713 .absolute()
7714 .size_full()
7715 })
7716 .when(self.zoomed.is_none(), |this| {
7717 this.on_drag_move(cx.listener(
7718 move |workspace,
7719 e: &DragMoveEvent<DraggedDock>,
7720 window,
7721 cx| {
7722 if workspace.previous_dock_drag_coordinates
7723 != Some(e.event.position)
7724 {
7725 workspace.previous_dock_drag_coordinates =
7726 Some(e.event.position);
7727
7728 match e.drag(cx).0 {
7729 DockPosition::Left => {
7730 workspace.resize_left_dock(
7731 e.event.position.x
7732 - workspace.bounds.left(),
7733 window,
7734 cx,
7735 );
7736 }
7737 DockPosition::Right => {
7738 workspace.resize_right_dock(
7739 workspace.bounds.right()
7740 - e.event.position.x,
7741 window,
7742 cx,
7743 );
7744 }
7745 DockPosition::Bottom => {
7746 workspace.resize_bottom_dock(
7747 workspace.bounds.bottom()
7748 - e.event.position.y,
7749 window,
7750 cx,
7751 );
7752 }
7753 };
7754 workspace.serialize_workspace(window, cx);
7755 }
7756 },
7757 ))
7758
7759 })
7760 .child({
7761 match bottom_dock_layout {
7762 BottomDockLayout::Full => div()
7763 .flex()
7764 .flex_col()
7765 .h_full()
7766 .child(
7767 div()
7768 .flex()
7769 .flex_row()
7770 .flex_1()
7771 .overflow_hidden()
7772 .children(self.render_dock(
7773 DockPosition::Left,
7774 &self.left_dock,
7775 window,
7776 cx,
7777 ))
7778
7779 .child(
7780 div()
7781 .flex()
7782 .flex_col()
7783 .flex_1()
7784 .overflow_hidden()
7785 .child(
7786 h_flex()
7787 .flex_1()
7788 .when_some(
7789 paddings.0,
7790 |this, p| {
7791 this.child(
7792 p.border_r_1(),
7793 )
7794 },
7795 )
7796 .child(self.center.render(
7797 self.zoomed.as_ref(),
7798 &PaneRenderContext {
7799 follower_states:
7800 &self.follower_states,
7801 active_call: self.active_call(),
7802 active_pane: &self.active_pane,
7803 app_state: &self.app_state,
7804 project: &self.project,
7805 workspace: &self.weak_self,
7806 },
7807 window,
7808 cx,
7809 ))
7810 .when_some(
7811 paddings.1,
7812 |this, p| {
7813 this.child(
7814 p.border_l_1(),
7815 )
7816 },
7817 ),
7818 ),
7819 )
7820
7821 .children(self.render_dock(
7822 DockPosition::Right,
7823 &self.right_dock,
7824 window,
7825 cx,
7826 )),
7827 )
7828 .child(div().w_full().children(self.render_dock(
7829 DockPosition::Bottom,
7830 &self.bottom_dock,
7831 window,
7832 cx
7833 ))),
7834
7835 BottomDockLayout::LeftAligned => div()
7836 .flex()
7837 .flex_row()
7838 .h_full()
7839 .child(
7840 div()
7841 .flex()
7842 .flex_col()
7843 .flex_1()
7844 .h_full()
7845 .child(
7846 div()
7847 .flex()
7848 .flex_row()
7849 .flex_1()
7850 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
7851
7852 .child(
7853 div()
7854 .flex()
7855 .flex_col()
7856 .flex_1()
7857 .overflow_hidden()
7858 .child(
7859 h_flex()
7860 .flex_1()
7861 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7862 .child(self.center.render(
7863 self.zoomed.as_ref(),
7864 &PaneRenderContext {
7865 follower_states:
7866 &self.follower_states,
7867 active_call: self.active_call(),
7868 active_pane: &self.active_pane,
7869 app_state: &self.app_state,
7870 project: &self.project,
7871 workspace: &self.weak_self,
7872 },
7873 window,
7874 cx,
7875 ))
7876 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7877 )
7878 )
7879
7880 )
7881 .child(
7882 div()
7883 .w_full()
7884 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7885 ),
7886 )
7887 .children(self.render_dock(
7888 DockPosition::Right,
7889 &self.right_dock,
7890 window,
7891 cx,
7892 )),
7893 BottomDockLayout::RightAligned => div()
7894 .flex()
7895 .flex_row()
7896 .h_full()
7897 .children(self.render_dock(
7898 DockPosition::Left,
7899 &self.left_dock,
7900 window,
7901 cx,
7902 ))
7903
7904 .child(
7905 div()
7906 .flex()
7907 .flex_col()
7908 .flex_1()
7909 .h_full()
7910 .child(
7911 div()
7912 .flex()
7913 .flex_row()
7914 .flex_1()
7915 .child(
7916 div()
7917 .flex()
7918 .flex_col()
7919 .flex_1()
7920 .overflow_hidden()
7921 .child(
7922 h_flex()
7923 .flex_1()
7924 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7925 .child(self.center.render(
7926 self.zoomed.as_ref(),
7927 &PaneRenderContext {
7928 follower_states:
7929 &self.follower_states,
7930 active_call: self.active_call(),
7931 active_pane: &self.active_pane,
7932 app_state: &self.app_state,
7933 project: &self.project,
7934 workspace: &self.weak_self,
7935 },
7936 window,
7937 cx,
7938 ))
7939 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7940 )
7941 )
7942
7943 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
7944 )
7945 .child(
7946 div()
7947 .w_full()
7948 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7949 ),
7950 ),
7951 BottomDockLayout::Contained => div()
7952 .flex()
7953 .flex_row()
7954 .h_full()
7955 .children(self.render_dock(
7956 DockPosition::Left,
7957 &self.left_dock,
7958 window,
7959 cx,
7960 ))
7961
7962 .child(
7963 div()
7964 .flex()
7965 .flex_col()
7966 .flex_1()
7967 .overflow_hidden()
7968 .child(
7969 h_flex()
7970 .flex_1()
7971 .when_some(paddings.0, |this, p| {
7972 this.child(p.border_r_1())
7973 })
7974 .child(self.center.render(
7975 self.zoomed.as_ref(),
7976 &PaneRenderContext {
7977 follower_states:
7978 &self.follower_states,
7979 active_call: self.active_call(),
7980 active_pane: &self.active_pane,
7981 app_state: &self.app_state,
7982 project: &self.project,
7983 workspace: &self.weak_self,
7984 },
7985 window,
7986 cx,
7987 ))
7988 .when_some(paddings.1, |this, p| {
7989 this.child(p.border_l_1())
7990 }),
7991 )
7992 .children(self.render_dock(
7993 DockPosition::Bottom,
7994 &self.bottom_dock,
7995 window,
7996 cx,
7997 )),
7998 )
7999
8000 .children(self.render_dock(
8001 DockPosition::Right,
8002 &self.right_dock,
8003 window,
8004 cx,
8005 )),
8006 }
8007 })
8008 .children(self.zoomed.as_ref().and_then(|view| {
8009 let zoomed_view = view.upgrade()?;
8010 let div = div()
8011 .occlude()
8012 .absolute()
8013 .overflow_hidden()
8014 .border_color(colors.border)
8015 .bg(colors.background)
8016 .child(zoomed_view)
8017 .inset_0()
8018 .shadow_lg();
8019
8020 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8021 return Some(div);
8022 }
8023
8024 Some(match self.zoomed_position {
8025 Some(DockPosition::Left) => div.right_2().border_r_1(),
8026 Some(DockPosition::Right) => div.left_2().border_l_1(),
8027 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8028 None => {
8029 div.top_2().bottom_2().left_2().right_2().border_1()
8030 }
8031 })
8032 }))
8033 .children(self.render_notifications(window, cx)),
8034 )
8035 .when(self.status_bar_visible(cx), |parent| {
8036 parent.child(self.status_bar.clone())
8037 })
8038 .child(self.toast_layer.clone()),
8039 )
8040 }
8041}
8042
8043impl WorkspaceStore {
8044 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8045 Self {
8046 workspaces: Default::default(),
8047 _subscriptions: vec![
8048 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8049 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8050 ],
8051 client,
8052 }
8053 }
8054
8055 pub fn update_followers(
8056 &self,
8057 project_id: Option<u64>,
8058 update: proto::update_followers::Variant,
8059 cx: &App,
8060 ) -> Option<()> {
8061 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8062 let room_id = active_call.0.room_id(cx)?;
8063 self.client
8064 .send(proto::UpdateFollowers {
8065 room_id,
8066 project_id,
8067 variant: Some(update),
8068 })
8069 .log_err()
8070 }
8071
8072 pub async fn handle_follow(
8073 this: Entity<Self>,
8074 envelope: TypedEnvelope<proto::Follow>,
8075 mut cx: AsyncApp,
8076 ) -> Result<proto::FollowResponse> {
8077 this.update(&mut cx, |this, cx| {
8078 let follower = Follower {
8079 project_id: envelope.payload.project_id,
8080 peer_id: envelope.original_sender_id()?,
8081 };
8082
8083 let mut response = proto::FollowResponse::default();
8084
8085 this.workspaces.retain(|(window_handle, weak_workspace)| {
8086 let Some(workspace) = weak_workspace.upgrade() else {
8087 return false;
8088 };
8089 window_handle
8090 .update(cx, |_, window, cx| {
8091 workspace.update(cx, |workspace, cx| {
8092 let handler_response =
8093 workspace.handle_follow(follower.project_id, window, cx);
8094 if let Some(active_view) = handler_response.active_view
8095 && workspace.project.read(cx).remote_id() == follower.project_id
8096 {
8097 response.active_view = Some(active_view)
8098 }
8099 });
8100 })
8101 .is_ok()
8102 });
8103
8104 Ok(response)
8105 })
8106 }
8107
8108 async fn handle_update_followers(
8109 this: Entity<Self>,
8110 envelope: TypedEnvelope<proto::UpdateFollowers>,
8111 mut cx: AsyncApp,
8112 ) -> Result<()> {
8113 let leader_id = envelope.original_sender_id()?;
8114 let update = envelope.payload;
8115
8116 this.update(&mut cx, |this, cx| {
8117 this.workspaces.retain(|(window_handle, weak_workspace)| {
8118 let Some(workspace) = weak_workspace.upgrade() else {
8119 return false;
8120 };
8121 window_handle
8122 .update(cx, |_, window, cx| {
8123 workspace.update(cx, |workspace, cx| {
8124 let project_id = workspace.project.read(cx).remote_id();
8125 if update.project_id != project_id && update.project_id.is_some() {
8126 return;
8127 }
8128 workspace.handle_update_followers(
8129 leader_id,
8130 update.clone(),
8131 window,
8132 cx,
8133 );
8134 });
8135 })
8136 .is_ok()
8137 });
8138 Ok(())
8139 })
8140 }
8141
8142 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8143 self.workspaces.iter().map(|(_, weak)| weak)
8144 }
8145
8146 pub fn workspaces_with_windows(
8147 &self,
8148 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8149 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8150 }
8151}
8152
8153impl ViewId {
8154 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8155 Ok(Self {
8156 creator: message
8157 .creator
8158 .map(CollaboratorId::PeerId)
8159 .context("creator is missing")?,
8160 id: message.id,
8161 })
8162 }
8163
8164 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8165 if let CollaboratorId::PeerId(peer_id) = self.creator {
8166 Some(proto::ViewId {
8167 creator: Some(peer_id),
8168 id: self.id,
8169 })
8170 } else {
8171 None
8172 }
8173 }
8174}
8175
8176impl FollowerState {
8177 fn pane(&self) -> &Entity<Pane> {
8178 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8179 }
8180}
8181
8182pub trait WorkspaceHandle {
8183 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8184}
8185
8186impl WorkspaceHandle for Entity<Workspace> {
8187 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8188 self.read(cx)
8189 .worktrees(cx)
8190 .flat_map(|worktree| {
8191 let worktree_id = worktree.read(cx).id();
8192 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8193 worktree_id,
8194 path: f.path.clone(),
8195 })
8196 })
8197 .collect::<Vec<_>>()
8198 }
8199}
8200
8201pub async fn last_opened_workspace_location(
8202 fs: &dyn fs::Fs,
8203) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8204 DB.last_workspace(fs)
8205 .await
8206 .log_err()
8207 .flatten()
8208 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8209}
8210
8211pub async fn last_session_workspace_locations(
8212 last_session_id: &str,
8213 last_session_window_stack: Option<Vec<WindowId>>,
8214 fs: &dyn fs::Fs,
8215) -> Option<Vec<SessionWorkspace>> {
8216 DB.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8217 .await
8218 .log_err()
8219}
8220
8221pub struct MultiWorkspaceRestoreResult {
8222 pub window_handle: WindowHandle<MultiWorkspace>,
8223 pub errors: Vec<anyhow::Error>,
8224}
8225
8226pub async fn restore_multiworkspace(
8227 multi_workspace: SerializedMultiWorkspace,
8228 app_state: Arc<AppState>,
8229 cx: &mut AsyncApp,
8230) -> anyhow::Result<MultiWorkspaceRestoreResult> {
8231 let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
8232 let mut group_iter = workspaces.into_iter();
8233 let first = group_iter
8234 .next()
8235 .context("window group must not be empty")?;
8236
8237 let window_handle = if first.paths.is_empty() {
8238 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
8239 .await?
8240 } else {
8241 let OpenResult { window, .. } = cx
8242 .update(|cx| {
8243 Workspace::new_local(
8244 first.paths.paths().to_vec(),
8245 app_state.clone(),
8246 None,
8247 None,
8248 None,
8249 true,
8250 cx,
8251 )
8252 })
8253 .await?;
8254 window
8255 };
8256
8257 let mut errors = Vec::new();
8258
8259 for session_workspace in group_iter {
8260 let error = if session_workspace.paths.is_empty() {
8261 cx.update(|cx| {
8262 open_workspace_by_id(
8263 session_workspace.workspace_id,
8264 app_state.clone(),
8265 Some(window_handle),
8266 cx,
8267 )
8268 })
8269 .await
8270 .err()
8271 } else {
8272 cx.update(|cx| {
8273 Workspace::new_local(
8274 session_workspace.paths.paths().to_vec(),
8275 app_state.clone(),
8276 Some(window_handle),
8277 None,
8278 None,
8279 false,
8280 cx,
8281 )
8282 })
8283 .await
8284 .err()
8285 };
8286
8287 if let Some(error) = error {
8288 errors.push(error);
8289 }
8290 }
8291
8292 if let Some(target_id) = state.active_workspace_id {
8293 window_handle
8294 .update(cx, |multi_workspace, window, cx| {
8295 let target_index = multi_workspace
8296 .workspaces()
8297 .iter()
8298 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8299 if let Some(index) = target_index {
8300 multi_workspace.activate_index(index, window, cx);
8301 } else if !multi_workspace.workspaces().is_empty() {
8302 multi_workspace.activate_index(0, window, cx);
8303 }
8304 })
8305 .ok();
8306 } else {
8307 window_handle
8308 .update(cx, |multi_workspace, window, cx| {
8309 if !multi_workspace.workspaces().is_empty() {
8310 multi_workspace.activate_index(0, window, cx);
8311 }
8312 })
8313 .ok();
8314 }
8315
8316 if state.sidebar_open {
8317 window_handle
8318 .update(cx, |multi_workspace, _, cx| {
8319 multi_workspace.open_sidebar(cx);
8320 })
8321 .ok();
8322 }
8323
8324 window_handle
8325 .update(cx, |_, window, _cx| {
8326 window.activate_window();
8327 })
8328 .ok();
8329
8330 Ok(MultiWorkspaceRestoreResult {
8331 window_handle,
8332 errors,
8333 })
8334}
8335
8336actions!(
8337 collab,
8338 [
8339 /// Opens the channel notes for the current call.
8340 ///
8341 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8342 /// channel in the collab panel.
8343 ///
8344 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8345 /// can be copied via "Copy link to section" in the context menu of the channel notes
8346 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8347 OpenChannelNotes,
8348 /// Mutes your microphone.
8349 Mute,
8350 /// Deafens yourself (mute both microphone and speakers).
8351 Deafen,
8352 /// Leaves the current call.
8353 LeaveCall,
8354 /// Shares the current project with collaborators.
8355 ShareProject,
8356 /// Shares your screen with collaborators.
8357 ScreenShare,
8358 /// Copies the current room name and session id for debugging purposes.
8359 CopyRoomId,
8360 ]
8361);
8362
8363/// Opens the channel notes for a specific channel by its ID.
8364#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8365#[action(namespace = collab)]
8366#[serde(deny_unknown_fields)]
8367pub struct OpenChannelNotesById {
8368 pub channel_id: u64,
8369}
8370
8371actions!(
8372 zed,
8373 [
8374 /// Opens the Zed log file.
8375 OpenLog,
8376 /// Reveals the Zed log file in the system file manager.
8377 RevealLogInFileManager
8378 ]
8379);
8380
8381async fn join_channel_internal(
8382 channel_id: ChannelId,
8383 app_state: &Arc<AppState>,
8384 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8385 requesting_workspace: Option<WeakEntity<Workspace>>,
8386 active_call: &dyn AnyActiveCall,
8387 cx: &mut AsyncApp,
8388) -> Result<bool> {
8389 let (should_prompt, already_in_channel) = cx.update(|cx| {
8390 if !active_call.is_in_room(cx) {
8391 return (false, false);
8392 }
8393
8394 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8395 let should_prompt = active_call.is_sharing_project(cx)
8396 && active_call.has_remote_participants(cx)
8397 && !already_in_channel;
8398 (should_prompt, already_in_channel)
8399 });
8400
8401 if already_in_channel {
8402 let task = cx.update(|cx| {
8403 if let Some((project, host)) = active_call.most_active_project(cx) {
8404 Some(join_in_room_project(project, host, app_state.clone(), cx))
8405 } else {
8406 None
8407 }
8408 });
8409 if let Some(task) = task {
8410 task.await?;
8411 }
8412 return anyhow::Ok(true);
8413 }
8414
8415 if should_prompt {
8416 if let Some(multi_workspace) = requesting_window {
8417 let answer = multi_workspace
8418 .update(cx, |_, window, cx| {
8419 window.prompt(
8420 PromptLevel::Warning,
8421 "Do you want to switch channels?",
8422 Some("Leaving this call will unshare your current project."),
8423 &["Yes, Join Channel", "Cancel"],
8424 cx,
8425 )
8426 })?
8427 .await;
8428
8429 if answer == Ok(1) {
8430 return Ok(false);
8431 }
8432 } else {
8433 return Ok(false);
8434 }
8435 }
8436
8437 let client = cx.update(|cx| active_call.client(cx));
8438
8439 let mut client_status = client.status();
8440
8441 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8442 'outer: loop {
8443 let Some(status) = client_status.recv().await else {
8444 anyhow::bail!("error connecting");
8445 };
8446
8447 match status {
8448 Status::Connecting
8449 | Status::Authenticating
8450 | Status::Authenticated
8451 | Status::Reconnecting
8452 | Status::Reauthenticating
8453 | Status::Reauthenticated => continue,
8454 Status::Connected { .. } => break 'outer,
8455 Status::SignedOut | Status::AuthenticationError => {
8456 return Err(ErrorCode::SignedOut.into());
8457 }
8458 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8459 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8460 return Err(ErrorCode::Disconnected.into());
8461 }
8462 }
8463 }
8464
8465 let joined = cx
8466 .update(|cx| active_call.join_channel(channel_id, cx))
8467 .await?;
8468
8469 if !joined {
8470 return anyhow::Ok(true);
8471 }
8472
8473 cx.update(|cx| active_call.room_update_completed(cx)).await;
8474
8475 let task = cx.update(|cx| {
8476 if let Some((project, host)) = active_call.most_active_project(cx) {
8477 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8478 }
8479
8480 // If you are the first to join a channel, see if you should share your project.
8481 if !active_call.has_remote_participants(cx)
8482 && !active_call.local_participant_is_guest(cx)
8483 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8484 {
8485 let project = workspace.update(cx, |workspace, cx| {
8486 let project = workspace.project.read(cx);
8487
8488 if !active_call.share_on_join(cx) {
8489 return None;
8490 }
8491
8492 if (project.is_local() || project.is_via_remote_server())
8493 && project.visible_worktrees(cx).any(|tree| {
8494 tree.read(cx)
8495 .root_entry()
8496 .is_some_and(|entry| entry.is_dir())
8497 })
8498 {
8499 Some(workspace.project.clone())
8500 } else {
8501 None
8502 }
8503 });
8504 if let Some(project) = project {
8505 let share_task = active_call.share_project(project, cx);
8506 return Some(cx.spawn(async move |_cx| -> Result<()> {
8507 share_task.await?;
8508 Ok(())
8509 }));
8510 }
8511 }
8512
8513 None
8514 });
8515 if let Some(task) = task {
8516 task.await?;
8517 return anyhow::Ok(true);
8518 }
8519 anyhow::Ok(false)
8520}
8521
8522pub fn join_channel(
8523 channel_id: ChannelId,
8524 app_state: Arc<AppState>,
8525 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8526 requesting_workspace: Option<WeakEntity<Workspace>>,
8527 cx: &mut App,
8528) -> Task<Result<()>> {
8529 let active_call = GlobalAnyActiveCall::global(cx).clone();
8530 cx.spawn(async move |cx| {
8531 let result = join_channel_internal(
8532 channel_id,
8533 &app_state,
8534 requesting_window,
8535 requesting_workspace,
8536 &*active_call.0,
8537 cx,
8538 )
8539 .await;
8540
8541 // join channel succeeded, and opened a window
8542 if matches!(result, Ok(true)) {
8543 return anyhow::Ok(());
8544 }
8545
8546 // find an existing workspace to focus and show call controls
8547 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8548 if active_window.is_none() {
8549 // no open workspaces, make one to show the error in (blergh)
8550 let OpenResult {
8551 window: window_handle,
8552 ..
8553 } = cx
8554 .update(|cx| {
8555 Workspace::new_local(
8556 vec![],
8557 app_state.clone(),
8558 requesting_window,
8559 None,
8560 None,
8561 true,
8562 cx,
8563 )
8564 })
8565 .await?;
8566
8567 window_handle
8568 .update(cx, |_, window, _cx| {
8569 window.activate_window();
8570 })
8571 .ok();
8572
8573 if result.is_ok() {
8574 cx.update(|cx| {
8575 cx.dispatch_action(&OpenChannelNotes);
8576 });
8577 }
8578
8579 active_window = Some(window_handle);
8580 }
8581
8582 if let Err(err) = result {
8583 log::error!("failed to join channel: {}", err);
8584 if let Some(active_window) = active_window {
8585 active_window
8586 .update(cx, |_, window, cx| {
8587 let detail: SharedString = match err.error_code() {
8588 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8589 ErrorCode::UpgradeRequired => concat!(
8590 "Your are running an unsupported version of Zed. ",
8591 "Please update to continue."
8592 )
8593 .into(),
8594 ErrorCode::NoSuchChannel => concat!(
8595 "No matching channel was found. ",
8596 "Please check the link and try again."
8597 )
8598 .into(),
8599 ErrorCode::Forbidden => concat!(
8600 "This channel is private, and you do not have access. ",
8601 "Please ask someone to add you and try again."
8602 )
8603 .into(),
8604 ErrorCode::Disconnected => {
8605 "Please check your internet connection and try again.".into()
8606 }
8607 _ => format!("{}\n\nPlease try again.", err).into(),
8608 };
8609 window.prompt(
8610 PromptLevel::Critical,
8611 "Failed to join channel",
8612 Some(&detail),
8613 &["Ok"],
8614 cx,
8615 )
8616 })?
8617 .await
8618 .ok();
8619 }
8620 }
8621
8622 // return ok, we showed the error to the user.
8623 anyhow::Ok(())
8624 })
8625}
8626
8627pub async fn get_any_active_multi_workspace(
8628 app_state: Arc<AppState>,
8629 mut cx: AsyncApp,
8630) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8631 // find an existing workspace to focus and show call controls
8632 let active_window = activate_any_workspace_window(&mut cx);
8633 if active_window.is_none() {
8634 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
8635 .await?;
8636 }
8637 activate_any_workspace_window(&mut cx).context("could not open zed")
8638}
8639
8640fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
8641 cx.update(|cx| {
8642 if let Some(workspace_window) = cx
8643 .active_window()
8644 .and_then(|window| window.downcast::<MultiWorkspace>())
8645 {
8646 return Some(workspace_window);
8647 }
8648
8649 for window in cx.windows() {
8650 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
8651 workspace_window
8652 .update(cx, |_, window, _| window.activate_window())
8653 .ok();
8654 return Some(workspace_window);
8655 }
8656 }
8657 None
8658 })
8659}
8660
8661pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
8662 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
8663}
8664
8665pub fn workspace_windows_for_location(
8666 serialized_location: &SerializedWorkspaceLocation,
8667 cx: &App,
8668) -> Vec<WindowHandle<MultiWorkspace>> {
8669 cx.windows()
8670 .into_iter()
8671 .filter_map(|window| window.downcast::<MultiWorkspace>())
8672 .filter(|multi_workspace| {
8673 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
8674 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
8675 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
8676 }
8677 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
8678 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
8679 a.distro_name == b.distro_name
8680 }
8681 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
8682 a.container_id == b.container_id
8683 }
8684 #[cfg(any(test, feature = "test-support"))]
8685 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
8686 a.id == b.id
8687 }
8688 _ => false,
8689 };
8690
8691 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
8692 multi_workspace.workspaces().iter().any(|workspace| {
8693 match workspace.read(cx).workspace_location(cx) {
8694 WorkspaceLocation::Location(location, _) => {
8695 match (&location, serialized_location) {
8696 (
8697 SerializedWorkspaceLocation::Local,
8698 SerializedWorkspaceLocation::Local,
8699 ) => true,
8700 (
8701 SerializedWorkspaceLocation::Remote(a),
8702 SerializedWorkspaceLocation::Remote(b),
8703 ) => same_host(a, b),
8704 _ => false,
8705 }
8706 }
8707 _ => false,
8708 }
8709 })
8710 })
8711 })
8712 .collect()
8713}
8714
8715pub async fn find_existing_workspace(
8716 abs_paths: &[PathBuf],
8717 open_options: &OpenOptions,
8718 location: &SerializedWorkspaceLocation,
8719 cx: &mut AsyncApp,
8720) -> (
8721 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
8722 OpenVisible,
8723) {
8724 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
8725 let mut open_visible = OpenVisible::All;
8726 let mut best_match = None;
8727
8728 if open_options.open_new_workspace != Some(true) {
8729 cx.update(|cx| {
8730 for window in workspace_windows_for_location(location, cx) {
8731 if let Ok(multi_workspace) = window.read(cx) {
8732 for workspace in multi_workspace.workspaces() {
8733 let project = workspace.read(cx).project.read(cx);
8734 let m = project.visibility_for_paths(
8735 abs_paths,
8736 open_options.open_new_workspace == None,
8737 cx,
8738 );
8739 if m > best_match {
8740 existing = Some((window, workspace.clone()));
8741 best_match = m;
8742 } else if best_match.is_none()
8743 && open_options.open_new_workspace == Some(false)
8744 {
8745 existing = Some((window, workspace.clone()))
8746 }
8747 }
8748 }
8749 }
8750 });
8751
8752 let all_paths_are_files = existing
8753 .as_ref()
8754 .and_then(|(_, target_workspace)| {
8755 cx.update(|cx| {
8756 let workspace = target_workspace.read(cx);
8757 let project = workspace.project.read(cx);
8758 let path_style = workspace.path_style(cx);
8759 Some(!abs_paths.iter().any(|path| {
8760 let path = util::paths::SanitizedPath::new(path);
8761 project.worktrees(cx).any(|worktree| {
8762 let worktree = worktree.read(cx);
8763 let abs_path = worktree.abs_path();
8764 path_style
8765 .strip_prefix(path.as_ref(), abs_path.as_ref())
8766 .and_then(|rel| worktree.entry_for_path(&rel))
8767 .is_some_and(|e| e.is_dir())
8768 })
8769 }))
8770 })
8771 })
8772 .unwrap_or(false);
8773
8774 if open_options.open_new_workspace.is_none()
8775 && existing.is_some()
8776 && open_options.wait
8777 && all_paths_are_files
8778 {
8779 cx.update(|cx| {
8780 let windows = workspace_windows_for_location(location, cx);
8781 let window = cx
8782 .active_window()
8783 .and_then(|window| window.downcast::<MultiWorkspace>())
8784 .filter(|window| windows.contains(window))
8785 .or_else(|| windows.into_iter().next());
8786 if let Some(window) = window {
8787 if let Ok(multi_workspace) = window.read(cx) {
8788 let active_workspace = multi_workspace.workspace().clone();
8789 existing = Some((window, active_workspace));
8790 open_visible = OpenVisible::None;
8791 }
8792 }
8793 });
8794 }
8795 }
8796 (existing, open_visible)
8797}
8798
8799#[derive(Default, Clone)]
8800pub struct OpenOptions {
8801 pub visible: Option<OpenVisible>,
8802 pub focus: Option<bool>,
8803 pub open_new_workspace: Option<bool>,
8804 pub wait: bool,
8805 pub replace_window: Option<WindowHandle<MultiWorkspace>>,
8806 pub env: Option<HashMap<String, String>>,
8807}
8808
8809/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
8810/// or [`Workspace::open_workspace_for_paths`].
8811pub struct OpenResult {
8812 pub window: WindowHandle<MultiWorkspace>,
8813 pub workspace: Entity<Workspace>,
8814 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
8815}
8816
8817/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
8818pub fn open_workspace_by_id(
8819 workspace_id: WorkspaceId,
8820 app_state: Arc<AppState>,
8821 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8822 cx: &mut App,
8823) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
8824 let project_handle = Project::local(
8825 app_state.client.clone(),
8826 app_state.node_runtime.clone(),
8827 app_state.user_store.clone(),
8828 app_state.languages.clone(),
8829 app_state.fs.clone(),
8830 None,
8831 project::LocalProjectFlags {
8832 init_worktree_trust: true,
8833 ..project::LocalProjectFlags::default()
8834 },
8835 cx,
8836 );
8837
8838 cx.spawn(async move |cx| {
8839 let serialized_workspace = persistence::DB
8840 .workspace_for_id(workspace_id)
8841 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
8842
8843 let centered_layout = serialized_workspace.centered_layout;
8844
8845 let (window, workspace) = if let Some(window) = requesting_window {
8846 let workspace = window.update(cx, |multi_workspace, window, cx| {
8847 let workspace = cx.new(|cx| {
8848 let mut workspace = Workspace::new(
8849 Some(workspace_id),
8850 project_handle.clone(),
8851 app_state.clone(),
8852 window,
8853 cx,
8854 );
8855 workspace.centered_layout = centered_layout;
8856 workspace
8857 });
8858 multi_workspace.add_workspace(workspace.clone(), cx);
8859 workspace
8860 })?;
8861 (window, workspace)
8862 } else {
8863 let window_bounds_override = window_bounds_env_override();
8864
8865 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
8866 (Some(WindowBounds::Windowed(bounds)), None)
8867 } else if let Some(display) = serialized_workspace.display
8868 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
8869 {
8870 (Some(bounds.0), Some(display))
8871 } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
8872 (Some(bounds), Some(display))
8873 } else {
8874 (None, None)
8875 };
8876
8877 let options = cx.update(|cx| {
8878 let mut options = (app_state.build_window_options)(display, cx);
8879 options.window_bounds = window_bounds;
8880 options
8881 });
8882
8883 let window = cx.open_window(options, {
8884 let app_state = app_state.clone();
8885 let project_handle = project_handle.clone();
8886 move |window, cx| {
8887 let workspace = cx.new(|cx| {
8888 let mut workspace = Workspace::new(
8889 Some(workspace_id),
8890 project_handle,
8891 app_state,
8892 window,
8893 cx,
8894 );
8895 workspace.centered_layout = centered_layout;
8896 workspace
8897 });
8898 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
8899 }
8900 })?;
8901
8902 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
8903 multi_workspace.workspace().clone()
8904 })?;
8905
8906 (window, workspace)
8907 };
8908
8909 notify_if_database_failed(window, cx);
8910
8911 // Restore items from the serialized workspace
8912 window
8913 .update(cx, |_, window, cx| {
8914 workspace.update(cx, |_workspace, cx| {
8915 open_items(Some(serialized_workspace), vec![], window, cx)
8916 })
8917 })?
8918 .await?;
8919
8920 window.update(cx, |_, window, cx| {
8921 workspace.update(cx, |workspace, cx| {
8922 workspace.serialize_workspace(window, cx);
8923 });
8924 })?;
8925
8926 Ok(window)
8927 })
8928}
8929
8930#[allow(clippy::type_complexity)]
8931pub fn open_paths(
8932 abs_paths: &[PathBuf],
8933 app_state: Arc<AppState>,
8934 open_options: OpenOptions,
8935 cx: &mut App,
8936) -> Task<anyhow::Result<OpenResult>> {
8937 let abs_paths = abs_paths.to_vec();
8938 #[cfg(target_os = "windows")]
8939 let wsl_path = abs_paths
8940 .iter()
8941 .find_map(|p| util::paths::WslPath::from_path(p));
8942
8943 cx.spawn(async move |cx| {
8944 let (mut existing, mut open_visible) = find_existing_workspace(
8945 &abs_paths,
8946 &open_options,
8947 &SerializedWorkspaceLocation::Local,
8948 cx,
8949 )
8950 .await;
8951
8952 // Fallback: if no workspace contains the paths and all paths are files,
8953 // prefer an existing local workspace window (active window first).
8954 if open_options.open_new_workspace.is_none() && existing.is_none() {
8955 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
8956 let all_metadatas = futures::future::join_all(all_paths)
8957 .await
8958 .into_iter()
8959 .filter_map(|result| result.ok().flatten())
8960 .collect::<Vec<_>>();
8961
8962 if all_metadatas.iter().all(|file| !file.is_dir) {
8963 cx.update(|cx| {
8964 let windows = workspace_windows_for_location(
8965 &SerializedWorkspaceLocation::Local,
8966 cx,
8967 );
8968 let window = cx
8969 .active_window()
8970 .and_then(|window| window.downcast::<MultiWorkspace>())
8971 .filter(|window| windows.contains(window))
8972 .or_else(|| windows.into_iter().next());
8973 if let Some(window) = window {
8974 if let Ok(multi_workspace) = window.read(cx) {
8975 let active_workspace = multi_workspace.workspace().clone();
8976 existing = Some((window, active_workspace));
8977 open_visible = OpenVisible::None;
8978 }
8979 }
8980 });
8981 }
8982 }
8983
8984 let result = if let Some((existing, target_workspace)) = existing {
8985 let open_task = existing
8986 .update(cx, |multi_workspace, window, cx| {
8987 window.activate_window();
8988 multi_workspace.activate(target_workspace.clone(), cx);
8989 target_workspace.update(cx, |workspace, cx| {
8990 workspace.open_paths(
8991 abs_paths,
8992 OpenOptions {
8993 visible: Some(open_visible),
8994 ..Default::default()
8995 },
8996 None,
8997 window,
8998 cx,
8999 )
9000 })
9001 })?
9002 .await;
9003
9004 _ = existing.update(cx, |multi_workspace, _, cx| {
9005 let workspace = multi_workspace.workspace().clone();
9006 workspace.update(cx, |workspace, cx| {
9007 for item in open_task.iter().flatten() {
9008 if let Err(e) = item {
9009 workspace.show_error(&e, cx);
9010 }
9011 }
9012 });
9013 });
9014
9015 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9016 } else {
9017 let result = cx
9018 .update(move |cx| {
9019 Workspace::new_local(
9020 abs_paths,
9021 app_state.clone(),
9022 open_options.replace_window,
9023 open_options.env,
9024 None,
9025 true,
9026 cx,
9027 )
9028 })
9029 .await;
9030
9031 if let Ok(ref result) = result {
9032 result.window
9033 .update(cx, |_, window, _cx| {
9034 window.activate_window();
9035 })
9036 .log_err();
9037 }
9038
9039 result
9040 };
9041
9042 #[cfg(target_os = "windows")]
9043 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9044 && let Ok(ref result) = result
9045 {
9046 result.window
9047 .update(cx, move |multi_workspace, _window, cx| {
9048 struct OpenInWsl;
9049 let workspace = multi_workspace.workspace().clone();
9050 workspace.update(cx, |workspace, cx| {
9051 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9052 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9053 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9054 cx.new(move |cx| {
9055 MessageNotification::new(msg, cx)
9056 .primary_message("Open in WSL")
9057 .primary_icon(IconName::FolderOpen)
9058 .primary_on_click(move |window, cx| {
9059 window.dispatch_action(Box::new(remote::OpenWslPath {
9060 distro: remote::WslConnectionOptions {
9061 distro_name: distro.clone(),
9062 user: None,
9063 },
9064 paths: vec![path.clone().into()],
9065 }), cx)
9066 })
9067 })
9068 });
9069 });
9070 })
9071 .unwrap();
9072 };
9073 result
9074 })
9075}
9076
9077pub fn open_new(
9078 open_options: OpenOptions,
9079 app_state: Arc<AppState>,
9080 cx: &mut App,
9081 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9082) -> Task<anyhow::Result<()>> {
9083 let task = Workspace::new_local(
9084 Vec::new(),
9085 app_state,
9086 open_options.replace_window,
9087 open_options.env,
9088 Some(Box::new(init)),
9089 true,
9090 cx,
9091 );
9092 cx.spawn(async move |cx| {
9093 let OpenResult { window, .. } = task.await?;
9094 window
9095 .update(cx, |_, window, _cx| {
9096 window.activate_window();
9097 })
9098 .ok();
9099 Ok(())
9100 })
9101}
9102
9103pub fn create_and_open_local_file(
9104 path: &'static Path,
9105 window: &mut Window,
9106 cx: &mut Context<Workspace>,
9107 default_content: impl 'static + Send + FnOnce() -> Rope,
9108) -> Task<Result<Box<dyn ItemHandle>>> {
9109 cx.spawn_in(window, async move |workspace, cx| {
9110 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9111 if !fs.is_file(path).await {
9112 fs.create_file(path, Default::default()).await?;
9113 fs.save(path, &default_content(), Default::default())
9114 .await?;
9115 }
9116
9117 workspace
9118 .update_in(cx, |workspace, window, cx| {
9119 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9120 let path = workspace
9121 .project
9122 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9123 cx.spawn_in(window, async move |workspace, cx| {
9124 let path = path.await?;
9125 let mut items = workspace
9126 .update_in(cx, |workspace, window, cx| {
9127 workspace.open_paths(
9128 vec![path.to_path_buf()],
9129 OpenOptions {
9130 visible: Some(OpenVisible::None),
9131 ..Default::default()
9132 },
9133 None,
9134 window,
9135 cx,
9136 )
9137 })?
9138 .await;
9139 let item = items.pop().flatten();
9140 item.with_context(|| format!("path {path:?} is not a file"))?
9141 })
9142 })
9143 })?
9144 .await?
9145 .await
9146 })
9147}
9148
9149pub fn open_remote_project_with_new_connection(
9150 window: WindowHandle<MultiWorkspace>,
9151 remote_connection: Arc<dyn RemoteConnection>,
9152 cancel_rx: oneshot::Receiver<()>,
9153 delegate: Arc<dyn RemoteClientDelegate>,
9154 app_state: Arc<AppState>,
9155 paths: Vec<PathBuf>,
9156 cx: &mut App,
9157) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9158 cx.spawn(async move |cx| {
9159 let (workspace_id, serialized_workspace) =
9160 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9161 .await?;
9162
9163 let session = match cx
9164 .update(|cx| {
9165 remote::RemoteClient::new(
9166 ConnectionIdentifier::Workspace(workspace_id.0),
9167 remote_connection,
9168 cancel_rx,
9169 delegate,
9170 cx,
9171 )
9172 })
9173 .await?
9174 {
9175 Some(result) => result,
9176 None => return Ok(Vec::new()),
9177 };
9178
9179 let project = cx.update(|cx| {
9180 project::Project::remote(
9181 session,
9182 app_state.client.clone(),
9183 app_state.node_runtime.clone(),
9184 app_state.user_store.clone(),
9185 app_state.languages.clone(),
9186 app_state.fs.clone(),
9187 true,
9188 cx,
9189 )
9190 });
9191
9192 open_remote_project_inner(
9193 project,
9194 paths,
9195 workspace_id,
9196 serialized_workspace,
9197 app_state,
9198 window,
9199 cx,
9200 )
9201 .await
9202 })
9203}
9204
9205pub fn open_remote_project_with_existing_connection(
9206 connection_options: RemoteConnectionOptions,
9207 project: Entity<Project>,
9208 paths: Vec<PathBuf>,
9209 app_state: Arc<AppState>,
9210 window: WindowHandle<MultiWorkspace>,
9211 cx: &mut AsyncApp,
9212) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9213 cx.spawn(async move |cx| {
9214 let (workspace_id, serialized_workspace) =
9215 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9216
9217 open_remote_project_inner(
9218 project,
9219 paths,
9220 workspace_id,
9221 serialized_workspace,
9222 app_state,
9223 window,
9224 cx,
9225 )
9226 .await
9227 })
9228}
9229
9230async fn open_remote_project_inner(
9231 project: Entity<Project>,
9232 paths: Vec<PathBuf>,
9233 workspace_id: WorkspaceId,
9234 serialized_workspace: Option<SerializedWorkspace>,
9235 app_state: Arc<AppState>,
9236 window: WindowHandle<MultiWorkspace>,
9237 cx: &mut AsyncApp,
9238) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9239 let toolchains = DB.toolchains(workspace_id).await?;
9240 for (toolchain, worktree_path, path) in toolchains {
9241 project
9242 .update(cx, |this, cx| {
9243 let Some(worktree_id) =
9244 this.find_worktree(&worktree_path, cx)
9245 .and_then(|(worktree, rel_path)| {
9246 if rel_path.is_empty() {
9247 Some(worktree.read(cx).id())
9248 } else {
9249 None
9250 }
9251 })
9252 else {
9253 return Task::ready(None);
9254 };
9255
9256 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9257 })
9258 .await;
9259 }
9260 let mut project_paths_to_open = vec![];
9261 let mut project_path_errors = vec![];
9262
9263 for path in paths {
9264 let result = cx
9265 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9266 .await;
9267 match result {
9268 Ok((_, project_path)) => {
9269 project_paths_to_open.push((path.clone(), Some(project_path)));
9270 }
9271 Err(error) => {
9272 project_path_errors.push(error);
9273 }
9274 };
9275 }
9276
9277 if project_paths_to_open.is_empty() {
9278 return Err(project_path_errors.pop().context("no paths given")?);
9279 }
9280
9281 let workspace = window.update(cx, |multi_workspace, window, cx| {
9282 telemetry::event!("SSH Project Opened");
9283
9284 let new_workspace = cx.new(|cx| {
9285 let mut workspace =
9286 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9287 workspace.update_history(cx);
9288
9289 if let Some(ref serialized) = serialized_workspace {
9290 workspace.centered_layout = serialized.centered_layout;
9291 }
9292
9293 workspace
9294 });
9295
9296 multi_workspace.activate(new_workspace.clone(), cx);
9297 new_workspace
9298 })?;
9299
9300 let items = window
9301 .update(cx, |_, window, cx| {
9302 window.activate_window();
9303 workspace.update(cx, |_workspace, cx| {
9304 open_items(serialized_workspace, project_paths_to_open, window, cx)
9305 })
9306 })?
9307 .await?;
9308
9309 workspace.update(cx, |workspace, cx| {
9310 for error in project_path_errors {
9311 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9312 if let Some(path) = error.error_tag("path") {
9313 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9314 }
9315 } else {
9316 workspace.show_error(&error, cx)
9317 }
9318 }
9319 });
9320
9321 Ok(items.into_iter().map(|item| item?.ok()).collect())
9322}
9323
9324fn deserialize_remote_project(
9325 connection_options: RemoteConnectionOptions,
9326 paths: Vec<PathBuf>,
9327 cx: &AsyncApp,
9328) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9329 cx.background_spawn(async move {
9330 let remote_connection_id = persistence::DB
9331 .get_or_create_remote_connection(connection_options)
9332 .await?;
9333
9334 let serialized_workspace =
9335 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
9336
9337 let workspace_id = if let Some(workspace_id) =
9338 serialized_workspace.as_ref().map(|workspace| workspace.id)
9339 {
9340 workspace_id
9341 } else {
9342 persistence::DB.next_id().await?
9343 };
9344
9345 Ok((workspace_id, serialized_workspace))
9346 })
9347}
9348
9349pub fn join_in_room_project(
9350 project_id: u64,
9351 follow_user_id: u64,
9352 app_state: Arc<AppState>,
9353 cx: &mut App,
9354) -> Task<Result<()>> {
9355 let windows = cx.windows();
9356 cx.spawn(async move |cx| {
9357 let existing_window_and_workspace: Option<(
9358 WindowHandle<MultiWorkspace>,
9359 Entity<Workspace>,
9360 )> = windows.into_iter().find_map(|window_handle| {
9361 window_handle
9362 .downcast::<MultiWorkspace>()
9363 .and_then(|window_handle| {
9364 window_handle
9365 .update(cx, |multi_workspace, _window, cx| {
9366 for workspace in multi_workspace.workspaces() {
9367 if workspace.read(cx).project().read(cx).remote_id()
9368 == Some(project_id)
9369 {
9370 return Some((window_handle, workspace.clone()));
9371 }
9372 }
9373 None
9374 })
9375 .unwrap_or(None)
9376 })
9377 });
9378
9379 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9380 existing_window_and_workspace
9381 {
9382 existing_window
9383 .update(cx, |multi_workspace, _, cx| {
9384 multi_workspace.activate(target_workspace, cx);
9385 })
9386 .ok();
9387 existing_window
9388 } else {
9389 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9390 let project = cx
9391 .update(|cx| {
9392 active_call.0.join_project(
9393 project_id,
9394 app_state.languages.clone(),
9395 app_state.fs.clone(),
9396 cx,
9397 )
9398 })
9399 .await?;
9400
9401 let window_bounds_override = window_bounds_env_override();
9402 cx.update(|cx| {
9403 let mut options = (app_state.build_window_options)(None, cx);
9404 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9405 cx.open_window(options, |window, cx| {
9406 let workspace = cx.new(|cx| {
9407 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9408 });
9409 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9410 })
9411 })?
9412 };
9413
9414 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9415 cx.activate(true);
9416 window.activate_window();
9417
9418 // We set the active workspace above, so this is the correct workspace.
9419 let workspace = multi_workspace.workspace().clone();
9420 workspace.update(cx, |workspace, cx| {
9421 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9422 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9423 .or_else(|| {
9424 // If we couldn't follow the given user, follow the host instead.
9425 let collaborator = workspace
9426 .project()
9427 .read(cx)
9428 .collaborators()
9429 .values()
9430 .find(|collaborator| collaborator.is_host)?;
9431 Some(collaborator.peer_id)
9432 });
9433
9434 if let Some(follow_peer_id) = follow_peer_id {
9435 workspace.follow(follow_peer_id, window, cx);
9436 }
9437 });
9438 })?;
9439
9440 anyhow::Ok(())
9441 })
9442}
9443
9444pub fn reload(cx: &mut App) {
9445 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9446 let mut workspace_windows = cx
9447 .windows()
9448 .into_iter()
9449 .filter_map(|window| window.downcast::<MultiWorkspace>())
9450 .collect::<Vec<_>>();
9451
9452 // If multiple windows have unsaved changes, and need a save prompt,
9453 // prompt in the active window before switching to a different window.
9454 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9455
9456 let mut prompt = None;
9457 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9458 prompt = window
9459 .update(cx, |_, window, cx| {
9460 window.prompt(
9461 PromptLevel::Info,
9462 "Are you sure you want to restart?",
9463 None,
9464 &["Restart", "Cancel"],
9465 cx,
9466 )
9467 })
9468 .ok();
9469 }
9470
9471 cx.spawn(async move |cx| {
9472 if let Some(prompt) = prompt {
9473 let answer = prompt.await?;
9474 if answer != 0 {
9475 return anyhow::Ok(());
9476 }
9477 }
9478
9479 // If the user cancels any save prompt, then keep the app open.
9480 for window in workspace_windows {
9481 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9482 let workspace = multi_workspace.workspace().clone();
9483 workspace.update(cx, |workspace, cx| {
9484 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9485 })
9486 }) && !should_close.await?
9487 {
9488 return anyhow::Ok(());
9489 }
9490 }
9491 cx.update(|cx| cx.restart());
9492 anyhow::Ok(())
9493 })
9494 .detach_and_log_err(cx);
9495}
9496
9497fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9498 let mut parts = value.split(',');
9499 let x: usize = parts.next()?.parse().ok()?;
9500 let y: usize = parts.next()?.parse().ok()?;
9501 Some(point(px(x as f32), px(y as f32)))
9502}
9503
9504fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9505 let mut parts = value.split(',');
9506 let width: usize = parts.next()?.parse().ok()?;
9507 let height: usize = parts.next()?.parse().ok()?;
9508 Some(size(px(width as f32), px(height as f32)))
9509}
9510
9511/// Add client-side decorations (rounded corners, shadows, resize handling) when
9512/// appropriate.
9513///
9514/// The `border_radius_tiling` parameter allows overriding which corners get
9515/// rounded, independently of the actual window tiling state. This is used
9516/// specifically for the workspace switcher sidebar: when the sidebar is open,
9517/// we want square corners on the left (so the sidebar appears flush with the
9518/// window edge) but we still need the shadow padding for proper visual
9519/// appearance. Unlike actual window tiling, this only affects border radius -
9520/// not padding or shadows.
9521pub fn client_side_decorations(
9522 element: impl IntoElement,
9523 window: &mut Window,
9524 cx: &mut App,
9525 border_radius_tiling: Tiling,
9526) -> Stateful<Div> {
9527 const BORDER_SIZE: Pixels = px(1.0);
9528 let decorations = window.window_decorations();
9529 let tiling = match decorations {
9530 Decorations::Server => Tiling::default(),
9531 Decorations::Client { tiling } => tiling,
9532 };
9533
9534 match decorations {
9535 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9536 Decorations::Server => window.set_client_inset(px(0.0)),
9537 }
9538
9539 struct GlobalResizeEdge(ResizeEdge);
9540 impl Global for GlobalResizeEdge {}
9541
9542 div()
9543 .id("window-backdrop")
9544 .bg(transparent_black())
9545 .map(|div| match decorations {
9546 Decorations::Server => div,
9547 Decorations::Client { .. } => div
9548 .when(
9549 !(tiling.top
9550 || tiling.right
9551 || border_radius_tiling.top
9552 || border_radius_tiling.right),
9553 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9554 )
9555 .when(
9556 !(tiling.top
9557 || tiling.left
9558 || border_radius_tiling.top
9559 || border_radius_tiling.left),
9560 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9561 )
9562 .when(
9563 !(tiling.bottom
9564 || tiling.right
9565 || border_radius_tiling.bottom
9566 || border_radius_tiling.right),
9567 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9568 )
9569 .when(
9570 !(tiling.bottom
9571 || tiling.left
9572 || border_radius_tiling.bottom
9573 || border_radius_tiling.left),
9574 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9575 )
9576 .when(!tiling.top, |div| {
9577 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9578 })
9579 .when(!tiling.bottom, |div| {
9580 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9581 })
9582 .when(!tiling.left, |div| {
9583 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9584 })
9585 .when(!tiling.right, |div| {
9586 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9587 })
9588 .on_mouse_move(move |e, window, cx| {
9589 let size = window.window_bounds().get_bounds().size;
9590 let pos = e.position;
9591
9592 let new_edge =
9593 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9594
9595 let edge = cx.try_global::<GlobalResizeEdge>();
9596 if new_edge != edge.map(|edge| edge.0) {
9597 window
9598 .window_handle()
9599 .update(cx, |workspace, _, cx| {
9600 cx.notify(workspace.entity_id());
9601 })
9602 .ok();
9603 }
9604 })
9605 .on_mouse_down(MouseButton::Left, move |e, window, _| {
9606 let size = window.window_bounds().get_bounds().size;
9607 let pos = e.position;
9608
9609 let edge = match resize_edge(
9610 pos,
9611 theme::CLIENT_SIDE_DECORATION_SHADOW,
9612 size,
9613 tiling,
9614 ) {
9615 Some(value) => value,
9616 None => return,
9617 };
9618
9619 window.start_window_resize(edge);
9620 }),
9621 })
9622 .size_full()
9623 .child(
9624 div()
9625 .cursor(CursorStyle::Arrow)
9626 .map(|div| match decorations {
9627 Decorations::Server => div,
9628 Decorations::Client { .. } => div
9629 .border_color(cx.theme().colors().border)
9630 .when(
9631 !(tiling.top
9632 || tiling.right
9633 || border_radius_tiling.top
9634 || border_radius_tiling.right),
9635 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9636 )
9637 .when(
9638 !(tiling.top
9639 || tiling.left
9640 || border_radius_tiling.top
9641 || border_radius_tiling.left),
9642 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9643 )
9644 .when(
9645 !(tiling.bottom
9646 || tiling.right
9647 || border_radius_tiling.bottom
9648 || border_radius_tiling.right),
9649 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9650 )
9651 .when(
9652 !(tiling.bottom
9653 || tiling.left
9654 || border_radius_tiling.bottom
9655 || border_radius_tiling.left),
9656 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9657 )
9658 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
9659 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
9660 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
9661 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
9662 .when(!tiling.is_tiled(), |div| {
9663 div.shadow(vec![gpui::BoxShadow {
9664 color: Hsla {
9665 h: 0.,
9666 s: 0.,
9667 l: 0.,
9668 a: 0.4,
9669 },
9670 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
9671 spread_radius: px(0.),
9672 offset: point(px(0.0), px(0.0)),
9673 }])
9674 }),
9675 })
9676 .on_mouse_move(|_e, _, cx| {
9677 cx.stop_propagation();
9678 })
9679 .size_full()
9680 .child(element),
9681 )
9682 .map(|div| match decorations {
9683 Decorations::Server => div,
9684 Decorations::Client { tiling, .. } => div.child(
9685 canvas(
9686 |_bounds, window, _| {
9687 window.insert_hitbox(
9688 Bounds::new(
9689 point(px(0.0), px(0.0)),
9690 window.window_bounds().get_bounds().size,
9691 ),
9692 HitboxBehavior::Normal,
9693 )
9694 },
9695 move |_bounds, hitbox, window, cx| {
9696 let mouse = window.mouse_position();
9697 let size = window.window_bounds().get_bounds().size;
9698 let Some(edge) =
9699 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
9700 else {
9701 return;
9702 };
9703 cx.set_global(GlobalResizeEdge(edge));
9704 window.set_cursor_style(
9705 match edge {
9706 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
9707 ResizeEdge::Left | ResizeEdge::Right => {
9708 CursorStyle::ResizeLeftRight
9709 }
9710 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
9711 CursorStyle::ResizeUpLeftDownRight
9712 }
9713 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
9714 CursorStyle::ResizeUpRightDownLeft
9715 }
9716 },
9717 &hitbox,
9718 );
9719 },
9720 )
9721 .size_full()
9722 .absolute(),
9723 ),
9724 })
9725}
9726
9727fn resize_edge(
9728 pos: Point<Pixels>,
9729 shadow_size: Pixels,
9730 window_size: Size<Pixels>,
9731 tiling: Tiling,
9732) -> Option<ResizeEdge> {
9733 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
9734 if bounds.contains(&pos) {
9735 return None;
9736 }
9737
9738 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
9739 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
9740 if !tiling.top && top_left_bounds.contains(&pos) {
9741 return Some(ResizeEdge::TopLeft);
9742 }
9743
9744 let top_right_bounds = Bounds::new(
9745 Point::new(window_size.width - corner_size.width, px(0.)),
9746 corner_size,
9747 );
9748 if !tiling.top && top_right_bounds.contains(&pos) {
9749 return Some(ResizeEdge::TopRight);
9750 }
9751
9752 let bottom_left_bounds = Bounds::new(
9753 Point::new(px(0.), window_size.height - corner_size.height),
9754 corner_size,
9755 );
9756 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
9757 return Some(ResizeEdge::BottomLeft);
9758 }
9759
9760 let bottom_right_bounds = Bounds::new(
9761 Point::new(
9762 window_size.width - corner_size.width,
9763 window_size.height - corner_size.height,
9764 ),
9765 corner_size,
9766 );
9767 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
9768 return Some(ResizeEdge::BottomRight);
9769 }
9770
9771 if !tiling.top && pos.y < shadow_size {
9772 Some(ResizeEdge::Top)
9773 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
9774 Some(ResizeEdge::Bottom)
9775 } else if !tiling.left && pos.x < shadow_size {
9776 Some(ResizeEdge::Left)
9777 } else if !tiling.right && pos.x > window_size.width - shadow_size {
9778 Some(ResizeEdge::Right)
9779 } else {
9780 None
9781 }
9782}
9783
9784fn join_pane_into_active(
9785 active_pane: &Entity<Pane>,
9786 pane: &Entity<Pane>,
9787 window: &mut Window,
9788 cx: &mut App,
9789) {
9790 if pane == active_pane {
9791 } else if pane.read(cx).items_len() == 0 {
9792 pane.update(cx, |_, cx| {
9793 cx.emit(pane::Event::Remove {
9794 focus_on_pane: None,
9795 });
9796 })
9797 } else {
9798 move_all_items(pane, active_pane, window, cx);
9799 }
9800}
9801
9802fn move_all_items(
9803 from_pane: &Entity<Pane>,
9804 to_pane: &Entity<Pane>,
9805 window: &mut Window,
9806 cx: &mut App,
9807) {
9808 let destination_is_different = from_pane != to_pane;
9809 let mut moved_items = 0;
9810 for (item_ix, item_handle) in from_pane
9811 .read(cx)
9812 .items()
9813 .enumerate()
9814 .map(|(ix, item)| (ix, item.clone()))
9815 .collect::<Vec<_>>()
9816 {
9817 let ix = item_ix - moved_items;
9818 if destination_is_different {
9819 // Close item from previous pane
9820 from_pane.update(cx, |source, cx| {
9821 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
9822 });
9823 moved_items += 1;
9824 }
9825
9826 // This automatically removes duplicate items in the pane
9827 to_pane.update(cx, |destination, cx| {
9828 destination.add_item(item_handle, true, true, None, window, cx);
9829 window.focus(&destination.focus_handle(cx), cx)
9830 });
9831 }
9832}
9833
9834pub fn move_item(
9835 source: &Entity<Pane>,
9836 destination: &Entity<Pane>,
9837 item_id_to_move: EntityId,
9838 destination_index: usize,
9839 activate: bool,
9840 window: &mut Window,
9841 cx: &mut App,
9842) {
9843 let Some((item_ix, item_handle)) = source
9844 .read(cx)
9845 .items()
9846 .enumerate()
9847 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
9848 .map(|(ix, item)| (ix, item.clone()))
9849 else {
9850 // Tab was closed during drag
9851 return;
9852 };
9853
9854 if source != destination {
9855 // Close item from previous pane
9856 source.update(cx, |source, cx| {
9857 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
9858 });
9859 }
9860
9861 // This automatically removes duplicate items in the pane
9862 destination.update(cx, |destination, cx| {
9863 destination.add_item_inner(
9864 item_handle,
9865 activate,
9866 activate,
9867 activate,
9868 Some(destination_index),
9869 window,
9870 cx,
9871 );
9872 if activate {
9873 window.focus(&destination.focus_handle(cx), cx)
9874 }
9875 });
9876}
9877
9878pub fn move_active_item(
9879 source: &Entity<Pane>,
9880 destination: &Entity<Pane>,
9881 focus_destination: bool,
9882 close_if_empty: bool,
9883 window: &mut Window,
9884 cx: &mut App,
9885) {
9886 if source == destination {
9887 return;
9888 }
9889 let Some(active_item) = source.read(cx).active_item() else {
9890 return;
9891 };
9892 source.update(cx, |source_pane, cx| {
9893 let item_id = active_item.item_id();
9894 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
9895 destination.update(cx, |target_pane, cx| {
9896 target_pane.add_item(
9897 active_item,
9898 focus_destination,
9899 focus_destination,
9900 Some(target_pane.items_len()),
9901 window,
9902 cx,
9903 );
9904 });
9905 });
9906}
9907
9908pub fn clone_active_item(
9909 workspace_id: Option<WorkspaceId>,
9910 source: &Entity<Pane>,
9911 destination: &Entity<Pane>,
9912 focus_destination: bool,
9913 window: &mut Window,
9914 cx: &mut App,
9915) {
9916 if source == destination {
9917 return;
9918 }
9919 let Some(active_item) = source.read(cx).active_item() else {
9920 return;
9921 };
9922 if !active_item.can_split(cx) {
9923 return;
9924 }
9925 let destination = destination.downgrade();
9926 let task = active_item.clone_on_split(workspace_id, window, cx);
9927 window
9928 .spawn(cx, async move |cx| {
9929 let Some(clone) = task.await else {
9930 return;
9931 };
9932 destination
9933 .update_in(cx, |target_pane, window, cx| {
9934 target_pane.add_item(
9935 clone,
9936 focus_destination,
9937 focus_destination,
9938 Some(target_pane.items_len()),
9939 window,
9940 cx,
9941 );
9942 })
9943 .log_err();
9944 })
9945 .detach();
9946}
9947
9948#[derive(Debug)]
9949pub struct WorkspacePosition {
9950 pub window_bounds: Option<WindowBounds>,
9951 pub display: Option<Uuid>,
9952 pub centered_layout: bool,
9953}
9954
9955pub fn remote_workspace_position_from_db(
9956 connection_options: RemoteConnectionOptions,
9957 paths_to_open: &[PathBuf],
9958 cx: &App,
9959) -> Task<Result<WorkspacePosition>> {
9960 let paths = paths_to_open.to_vec();
9961
9962 cx.background_spawn(async move {
9963 let remote_connection_id = persistence::DB
9964 .get_or_create_remote_connection(connection_options)
9965 .await
9966 .context("fetching serialized ssh project")?;
9967 let serialized_workspace =
9968 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
9969
9970 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
9971 (Some(WindowBounds::Windowed(bounds)), None)
9972 } else {
9973 let restorable_bounds = serialized_workspace
9974 .as_ref()
9975 .and_then(|workspace| {
9976 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
9977 })
9978 .or_else(|| persistence::read_default_window_bounds());
9979
9980 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
9981 (Some(serialized_bounds), Some(serialized_display))
9982 } else {
9983 (None, None)
9984 }
9985 };
9986
9987 let centered_layout = serialized_workspace
9988 .as_ref()
9989 .map(|w| w.centered_layout)
9990 .unwrap_or(false);
9991
9992 Ok(WorkspacePosition {
9993 window_bounds,
9994 display,
9995 centered_layout,
9996 })
9997 })
9998}
9999
10000pub fn with_active_or_new_workspace(
10001 cx: &mut App,
10002 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10003) {
10004 match cx
10005 .active_window()
10006 .and_then(|w| w.downcast::<MultiWorkspace>())
10007 {
10008 Some(multi_workspace) => {
10009 cx.defer(move |cx| {
10010 multi_workspace
10011 .update(cx, |multi_workspace, window, cx| {
10012 let workspace = multi_workspace.workspace().clone();
10013 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10014 })
10015 .log_err();
10016 });
10017 }
10018 None => {
10019 let app_state = AppState::global(cx);
10020 if let Some(app_state) = app_state.upgrade() {
10021 open_new(
10022 OpenOptions::default(),
10023 app_state,
10024 cx,
10025 move |workspace, window, cx| f(workspace, window, cx),
10026 )
10027 .detach_and_log_err(cx);
10028 }
10029 }
10030 }
10031}
10032
10033#[cfg(test)]
10034mod tests {
10035 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10036
10037 use super::*;
10038 use crate::{
10039 dock::{PanelEvent, test::TestPanel},
10040 item::{
10041 ItemBufferKind, ItemEvent,
10042 test::{TestItem, TestProjectItem},
10043 },
10044 };
10045 use fs::FakeFs;
10046 use gpui::{
10047 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10048 UpdateGlobal, VisualTestContext, px,
10049 };
10050 use project::{Project, ProjectEntryId};
10051 use serde_json::json;
10052 use settings::SettingsStore;
10053 use util::path;
10054 use util::rel_path::rel_path;
10055
10056 #[gpui::test]
10057 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10058 init_test(cx);
10059
10060 let fs = FakeFs::new(cx.executor());
10061 let project = Project::test(fs, [], cx).await;
10062 let (workspace, cx) =
10063 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10064
10065 // Adding an item with no ambiguity renders the tab without detail.
10066 let item1 = cx.new(|cx| {
10067 let mut item = TestItem::new(cx);
10068 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10069 item
10070 });
10071 workspace.update_in(cx, |workspace, window, cx| {
10072 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10073 });
10074 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10075
10076 // Adding an item that creates ambiguity increases the level of detail on
10077 // both tabs.
10078 let item2 = cx.new_window_entity(|_window, cx| {
10079 let mut item = TestItem::new(cx);
10080 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10081 item
10082 });
10083 workspace.update_in(cx, |workspace, window, cx| {
10084 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10085 });
10086 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10087 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10088
10089 // Adding an item that creates ambiguity increases the level of detail only
10090 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10091 // we stop at the highest detail available.
10092 let item3 = cx.new(|cx| {
10093 let mut item = TestItem::new(cx);
10094 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10095 item
10096 });
10097 workspace.update_in(cx, |workspace, window, cx| {
10098 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10099 });
10100 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10101 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10102 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10103 }
10104
10105 #[gpui::test]
10106 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10107 init_test(cx);
10108
10109 let fs = FakeFs::new(cx.executor());
10110 fs.insert_tree(
10111 "/root1",
10112 json!({
10113 "one.txt": "",
10114 "two.txt": "",
10115 }),
10116 )
10117 .await;
10118 fs.insert_tree(
10119 "/root2",
10120 json!({
10121 "three.txt": "",
10122 }),
10123 )
10124 .await;
10125
10126 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10127 let (workspace, cx) =
10128 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10129 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10130 let worktree_id = project.update(cx, |project, cx| {
10131 project.worktrees(cx).next().unwrap().read(cx).id()
10132 });
10133
10134 let item1 = cx.new(|cx| {
10135 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10136 });
10137 let item2 = cx.new(|cx| {
10138 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10139 });
10140
10141 // Add an item to an empty pane
10142 workspace.update_in(cx, |workspace, window, cx| {
10143 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10144 });
10145 project.update(cx, |project, cx| {
10146 assert_eq!(
10147 project.active_entry(),
10148 project
10149 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10150 .map(|e| e.id)
10151 );
10152 });
10153 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10154
10155 // Add a second item to a non-empty pane
10156 workspace.update_in(cx, |workspace, window, cx| {
10157 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10158 });
10159 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10160 project.update(cx, |project, cx| {
10161 assert_eq!(
10162 project.active_entry(),
10163 project
10164 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10165 .map(|e| e.id)
10166 );
10167 });
10168
10169 // Close the active item
10170 pane.update_in(cx, |pane, window, cx| {
10171 pane.close_active_item(&Default::default(), window, cx)
10172 })
10173 .await
10174 .unwrap();
10175 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10176 project.update(cx, |project, cx| {
10177 assert_eq!(
10178 project.active_entry(),
10179 project
10180 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10181 .map(|e| e.id)
10182 );
10183 });
10184
10185 // Add a project folder
10186 project
10187 .update(cx, |project, cx| {
10188 project.find_or_create_worktree("root2", true, cx)
10189 })
10190 .await
10191 .unwrap();
10192 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10193
10194 // Remove a project folder
10195 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10196 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10197 }
10198
10199 #[gpui::test]
10200 async fn test_close_window(cx: &mut TestAppContext) {
10201 init_test(cx);
10202
10203 let fs = FakeFs::new(cx.executor());
10204 fs.insert_tree("/root", json!({ "one": "" })).await;
10205
10206 let project = Project::test(fs, ["root".as_ref()], cx).await;
10207 let (workspace, cx) =
10208 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10209
10210 // When there are no dirty items, there's nothing to do.
10211 let item1 = cx.new(TestItem::new);
10212 workspace.update_in(cx, |w, window, cx| {
10213 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10214 });
10215 let task = workspace.update_in(cx, |w, window, cx| {
10216 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10217 });
10218 assert!(task.await.unwrap());
10219
10220 // When there are dirty untitled items, prompt to save each one. If the user
10221 // cancels any prompt, then abort.
10222 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10223 let item3 = cx.new(|cx| {
10224 TestItem::new(cx)
10225 .with_dirty(true)
10226 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10227 });
10228 workspace.update_in(cx, |w, window, cx| {
10229 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10230 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10231 });
10232 let task = workspace.update_in(cx, |w, window, cx| {
10233 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10234 });
10235 cx.executor().run_until_parked();
10236 cx.simulate_prompt_answer("Cancel"); // cancel save all
10237 cx.executor().run_until_parked();
10238 assert!(!cx.has_pending_prompt());
10239 assert!(!task.await.unwrap());
10240 }
10241
10242 #[gpui::test]
10243 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10244 init_test(cx);
10245
10246 let fs = FakeFs::new(cx.executor());
10247 fs.insert_tree("/root", json!({ "one": "" })).await;
10248
10249 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10250 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10251 let multi_workspace_handle =
10252 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10253 cx.run_until_parked();
10254
10255 let workspace_a = multi_workspace_handle
10256 .read_with(cx, |mw, _| mw.workspace().clone())
10257 .unwrap();
10258
10259 let workspace_b = multi_workspace_handle
10260 .update(cx, |mw, window, cx| {
10261 mw.test_add_workspace(project_b, window, cx)
10262 })
10263 .unwrap();
10264
10265 // Activate workspace A
10266 multi_workspace_handle
10267 .update(cx, |mw, window, cx| {
10268 mw.activate_index(0, window, cx);
10269 })
10270 .unwrap();
10271
10272 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10273
10274 // Workspace A has a clean item
10275 let item_a = cx.new(TestItem::new);
10276 workspace_a.update_in(cx, |w, window, cx| {
10277 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10278 });
10279
10280 // Workspace B has a dirty item
10281 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10282 workspace_b.update_in(cx, |w, window, cx| {
10283 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10284 });
10285
10286 // Verify workspace A is active
10287 multi_workspace_handle
10288 .read_with(cx, |mw, _| {
10289 assert_eq!(mw.active_workspace_index(), 0);
10290 })
10291 .unwrap();
10292
10293 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10294 multi_workspace_handle
10295 .update(cx, |mw, window, cx| {
10296 mw.close_window(&CloseWindow, window, cx);
10297 })
10298 .unwrap();
10299 cx.run_until_parked();
10300
10301 // Workspace B should now be active since it has dirty items that need attention
10302 multi_workspace_handle
10303 .read_with(cx, |mw, _| {
10304 assert_eq!(
10305 mw.active_workspace_index(),
10306 1,
10307 "workspace B should be activated when it prompts"
10308 );
10309 })
10310 .unwrap();
10311
10312 // User cancels the save prompt from workspace B
10313 cx.simulate_prompt_answer("Cancel");
10314 cx.run_until_parked();
10315
10316 // Window should still exist because workspace B's close was cancelled
10317 assert!(
10318 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10319 "window should still exist after cancelling one workspace's close"
10320 );
10321 }
10322
10323 #[gpui::test]
10324 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10325 init_test(cx);
10326
10327 // Register TestItem as a serializable item
10328 cx.update(|cx| {
10329 register_serializable_item::<TestItem>(cx);
10330 });
10331
10332 let fs = FakeFs::new(cx.executor());
10333 fs.insert_tree("/root", json!({ "one": "" })).await;
10334
10335 let project = Project::test(fs, ["root".as_ref()], cx).await;
10336 let (workspace, cx) =
10337 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10338
10339 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10340 let item1 = cx.new(|cx| {
10341 TestItem::new(cx)
10342 .with_dirty(true)
10343 .with_serialize(|| Some(Task::ready(Ok(()))))
10344 });
10345 let item2 = cx.new(|cx| {
10346 TestItem::new(cx)
10347 .with_dirty(true)
10348 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10349 .with_serialize(|| Some(Task::ready(Ok(()))))
10350 });
10351 workspace.update_in(cx, |w, window, cx| {
10352 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10353 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10354 });
10355 let task = workspace.update_in(cx, |w, window, cx| {
10356 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10357 });
10358 assert!(task.await.unwrap());
10359 }
10360
10361 #[gpui::test]
10362 async fn test_close_pane_items(cx: &mut TestAppContext) {
10363 init_test(cx);
10364
10365 let fs = FakeFs::new(cx.executor());
10366
10367 let project = Project::test(fs, None, cx).await;
10368 let (workspace, cx) =
10369 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10370
10371 let item1 = cx.new(|cx| {
10372 TestItem::new(cx)
10373 .with_dirty(true)
10374 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10375 });
10376 let item2 = cx.new(|cx| {
10377 TestItem::new(cx)
10378 .with_dirty(true)
10379 .with_conflict(true)
10380 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10381 });
10382 let item3 = cx.new(|cx| {
10383 TestItem::new(cx)
10384 .with_dirty(true)
10385 .with_conflict(true)
10386 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10387 });
10388 let item4 = cx.new(|cx| {
10389 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10390 let project_item = TestProjectItem::new_untitled(cx);
10391 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10392 project_item
10393 }])
10394 });
10395 let pane = workspace.update_in(cx, |workspace, window, cx| {
10396 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10397 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10398 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10399 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10400 workspace.active_pane().clone()
10401 });
10402
10403 let close_items = pane.update_in(cx, |pane, window, cx| {
10404 pane.activate_item(1, true, true, window, cx);
10405 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10406 let item1_id = item1.item_id();
10407 let item3_id = item3.item_id();
10408 let item4_id = item4.item_id();
10409 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10410 [item1_id, item3_id, item4_id].contains(&id)
10411 })
10412 });
10413 cx.executor().run_until_parked();
10414
10415 assert!(cx.has_pending_prompt());
10416 cx.simulate_prompt_answer("Save all");
10417
10418 cx.executor().run_until_parked();
10419
10420 // Item 1 is saved. There's a prompt to save item 3.
10421 pane.update(cx, |pane, cx| {
10422 assert_eq!(item1.read(cx).save_count, 1);
10423 assert_eq!(item1.read(cx).save_as_count, 0);
10424 assert_eq!(item1.read(cx).reload_count, 0);
10425 assert_eq!(pane.items_len(), 3);
10426 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10427 });
10428 assert!(cx.has_pending_prompt());
10429
10430 // Cancel saving item 3.
10431 cx.simulate_prompt_answer("Discard");
10432 cx.executor().run_until_parked();
10433
10434 // Item 3 is reloaded. There's a prompt to save item 4.
10435 pane.update(cx, |pane, cx| {
10436 assert_eq!(item3.read(cx).save_count, 0);
10437 assert_eq!(item3.read(cx).save_as_count, 0);
10438 assert_eq!(item3.read(cx).reload_count, 1);
10439 assert_eq!(pane.items_len(), 2);
10440 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10441 });
10442
10443 // There's a prompt for a path for item 4.
10444 cx.simulate_new_path_selection(|_| Some(Default::default()));
10445 close_items.await.unwrap();
10446
10447 // The requested items are closed.
10448 pane.update(cx, |pane, cx| {
10449 assert_eq!(item4.read(cx).save_count, 0);
10450 assert_eq!(item4.read(cx).save_as_count, 1);
10451 assert_eq!(item4.read(cx).reload_count, 0);
10452 assert_eq!(pane.items_len(), 1);
10453 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10454 });
10455 }
10456
10457 #[gpui::test]
10458 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10459 init_test(cx);
10460
10461 let fs = FakeFs::new(cx.executor());
10462 let project = Project::test(fs, [], cx).await;
10463 let (workspace, cx) =
10464 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10465
10466 // Create several workspace items with single project entries, and two
10467 // workspace items with multiple project entries.
10468 let single_entry_items = (0..=4)
10469 .map(|project_entry_id| {
10470 cx.new(|cx| {
10471 TestItem::new(cx)
10472 .with_dirty(true)
10473 .with_project_items(&[dirty_project_item(
10474 project_entry_id,
10475 &format!("{project_entry_id}.txt"),
10476 cx,
10477 )])
10478 })
10479 })
10480 .collect::<Vec<_>>();
10481 let item_2_3 = cx.new(|cx| {
10482 TestItem::new(cx)
10483 .with_dirty(true)
10484 .with_buffer_kind(ItemBufferKind::Multibuffer)
10485 .with_project_items(&[
10486 single_entry_items[2].read(cx).project_items[0].clone(),
10487 single_entry_items[3].read(cx).project_items[0].clone(),
10488 ])
10489 });
10490 let item_3_4 = cx.new(|cx| {
10491 TestItem::new(cx)
10492 .with_dirty(true)
10493 .with_buffer_kind(ItemBufferKind::Multibuffer)
10494 .with_project_items(&[
10495 single_entry_items[3].read(cx).project_items[0].clone(),
10496 single_entry_items[4].read(cx).project_items[0].clone(),
10497 ])
10498 });
10499
10500 // Create two panes that contain the following project entries:
10501 // left pane:
10502 // multi-entry items: (2, 3)
10503 // single-entry items: 0, 2, 3, 4
10504 // right pane:
10505 // single-entry items: 4, 1
10506 // multi-entry items: (3, 4)
10507 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10508 let left_pane = workspace.active_pane().clone();
10509 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10510 workspace.add_item_to_active_pane(
10511 single_entry_items[0].boxed_clone(),
10512 None,
10513 true,
10514 window,
10515 cx,
10516 );
10517 workspace.add_item_to_active_pane(
10518 single_entry_items[2].boxed_clone(),
10519 None,
10520 true,
10521 window,
10522 cx,
10523 );
10524 workspace.add_item_to_active_pane(
10525 single_entry_items[3].boxed_clone(),
10526 None,
10527 true,
10528 window,
10529 cx,
10530 );
10531 workspace.add_item_to_active_pane(
10532 single_entry_items[4].boxed_clone(),
10533 None,
10534 true,
10535 window,
10536 cx,
10537 );
10538
10539 let right_pane =
10540 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10541
10542 let boxed_clone = single_entry_items[1].boxed_clone();
10543 let right_pane = window.spawn(cx, async move |cx| {
10544 right_pane.await.inspect(|right_pane| {
10545 right_pane
10546 .update_in(cx, |pane, window, cx| {
10547 pane.add_item(boxed_clone, true, true, None, window, cx);
10548 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10549 })
10550 .unwrap();
10551 })
10552 });
10553
10554 (left_pane, right_pane)
10555 });
10556 let right_pane = right_pane.await.unwrap();
10557 cx.focus(&right_pane);
10558
10559 let close = right_pane.update_in(cx, |pane, window, cx| {
10560 pane.close_all_items(&CloseAllItems::default(), window, cx)
10561 .unwrap()
10562 });
10563 cx.executor().run_until_parked();
10564
10565 let msg = cx.pending_prompt().unwrap().0;
10566 assert!(msg.contains("1.txt"));
10567 assert!(!msg.contains("2.txt"));
10568 assert!(!msg.contains("3.txt"));
10569 assert!(!msg.contains("4.txt"));
10570
10571 // With best-effort close, cancelling item 1 keeps it open but items 4
10572 // and (3,4) still close since their entries exist in left pane.
10573 cx.simulate_prompt_answer("Cancel");
10574 close.await;
10575
10576 right_pane.read_with(cx, |pane, _| {
10577 assert_eq!(pane.items_len(), 1);
10578 });
10579
10580 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10581 left_pane
10582 .update_in(cx, |left_pane, window, cx| {
10583 left_pane.close_item_by_id(
10584 single_entry_items[3].entity_id(),
10585 SaveIntent::Skip,
10586 window,
10587 cx,
10588 )
10589 })
10590 .await
10591 .unwrap();
10592
10593 let close = left_pane.update_in(cx, |pane, window, cx| {
10594 pane.close_all_items(&CloseAllItems::default(), window, cx)
10595 .unwrap()
10596 });
10597 cx.executor().run_until_parked();
10598
10599 let details = cx.pending_prompt().unwrap().1;
10600 assert!(details.contains("0.txt"));
10601 assert!(details.contains("3.txt"));
10602 assert!(details.contains("4.txt"));
10603 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10604 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10605 // assert!(!details.contains("2.txt"));
10606
10607 cx.simulate_prompt_answer("Save all");
10608 cx.executor().run_until_parked();
10609 close.await;
10610
10611 left_pane.read_with(cx, |pane, _| {
10612 assert_eq!(pane.items_len(), 0);
10613 });
10614 }
10615
10616 #[gpui::test]
10617 async fn test_autosave(cx: &mut gpui::TestAppContext) {
10618 init_test(cx);
10619
10620 let fs = FakeFs::new(cx.executor());
10621 let project = Project::test(fs, [], cx).await;
10622 let (workspace, cx) =
10623 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10624 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10625
10626 let item = cx.new(|cx| {
10627 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10628 });
10629 let item_id = item.entity_id();
10630 workspace.update_in(cx, |workspace, window, cx| {
10631 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10632 });
10633
10634 // Autosave on window change.
10635 item.update(cx, |item, cx| {
10636 SettingsStore::update_global(cx, |settings, cx| {
10637 settings.update_user_settings(cx, |settings| {
10638 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10639 })
10640 });
10641 item.is_dirty = true;
10642 });
10643
10644 // Deactivating the window saves the file.
10645 cx.deactivate_window();
10646 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10647
10648 // Re-activating the window doesn't save the file.
10649 cx.update(|window, _| window.activate_window());
10650 cx.executor().run_until_parked();
10651 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10652
10653 // Autosave on focus change.
10654 item.update_in(cx, |item, window, cx| {
10655 cx.focus_self(window);
10656 SettingsStore::update_global(cx, |settings, cx| {
10657 settings.update_user_settings(cx, |settings| {
10658 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10659 })
10660 });
10661 item.is_dirty = true;
10662 });
10663 // Blurring the item saves the file.
10664 item.update_in(cx, |_, window, _| window.blur());
10665 cx.executor().run_until_parked();
10666 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10667
10668 // Deactivating the window still saves the file.
10669 item.update_in(cx, |item, window, cx| {
10670 cx.focus_self(window);
10671 item.is_dirty = true;
10672 });
10673 cx.deactivate_window();
10674 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10675
10676 // Autosave after delay.
10677 item.update(cx, |item, cx| {
10678 SettingsStore::update_global(cx, |settings, cx| {
10679 settings.update_user_settings(cx, |settings| {
10680 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10681 milliseconds: 500.into(),
10682 });
10683 })
10684 });
10685 item.is_dirty = true;
10686 cx.emit(ItemEvent::Edit);
10687 });
10688
10689 // Delay hasn't fully expired, so the file is still dirty and unsaved.
10690 cx.executor().advance_clock(Duration::from_millis(250));
10691 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10692
10693 // After delay expires, the file is saved.
10694 cx.executor().advance_clock(Duration::from_millis(250));
10695 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10696
10697 // Autosave after delay, should save earlier than delay if tab is closed
10698 item.update(cx, |item, cx| {
10699 item.is_dirty = true;
10700 cx.emit(ItemEvent::Edit);
10701 });
10702 cx.executor().advance_clock(Duration::from_millis(250));
10703 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10704
10705 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10706 pane.update_in(cx, |pane, window, cx| {
10707 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10708 })
10709 .await
10710 .unwrap();
10711 assert!(!cx.has_pending_prompt());
10712 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10713
10714 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10715 workspace.update_in(cx, |workspace, window, cx| {
10716 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10717 });
10718 item.update_in(cx, |item, _window, cx| {
10719 item.is_dirty = true;
10720 for project_item in &mut item.project_items {
10721 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10722 }
10723 });
10724 cx.run_until_parked();
10725 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10726
10727 // Autosave on focus change, ensuring closing the tab counts as such.
10728 item.update(cx, |item, cx| {
10729 SettingsStore::update_global(cx, |settings, cx| {
10730 settings.update_user_settings(cx, |settings| {
10731 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10732 })
10733 });
10734 item.is_dirty = true;
10735 for project_item in &mut item.project_items {
10736 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10737 }
10738 });
10739
10740 pane.update_in(cx, |pane, window, cx| {
10741 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10742 })
10743 .await
10744 .unwrap();
10745 assert!(!cx.has_pending_prompt());
10746 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10747
10748 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10749 workspace.update_in(cx, |workspace, window, cx| {
10750 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10751 });
10752 item.update_in(cx, |item, window, cx| {
10753 item.project_items[0].update(cx, |item, _| {
10754 item.entry_id = None;
10755 });
10756 item.is_dirty = true;
10757 window.blur();
10758 });
10759 cx.run_until_parked();
10760 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10761
10762 // Ensure autosave is prevented for deleted files also when closing the buffer.
10763 let _close_items = pane.update_in(cx, |pane, window, cx| {
10764 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10765 });
10766 cx.run_until_parked();
10767 assert!(cx.has_pending_prompt());
10768 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10769 }
10770
10771 #[gpui::test]
10772 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
10773 init_test(cx);
10774
10775 let fs = FakeFs::new(cx.executor());
10776 let project = Project::test(fs, [], cx).await;
10777 let (workspace, cx) =
10778 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10779
10780 // Create a multibuffer-like item with two child focus handles,
10781 // simulating individual buffer editors within a multibuffer.
10782 let item = cx.new(|cx| {
10783 TestItem::new(cx)
10784 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10785 .with_child_focus_handles(2, cx)
10786 });
10787 workspace.update_in(cx, |workspace, window, cx| {
10788 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10789 });
10790
10791 // Set autosave to OnFocusChange and focus the first child handle,
10792 // simulating the user's cursor being inside one of the multibuffer's excerpts.
10793 item.update_in(cx, |item, window, cx| {
10794 SettingsStore::update_global(cx, |settings, cx| {
10795 settings.update_user_settings(cx, |settings| {
10796 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10797 })
10798 });
10799 item.is_dirty = true;
10800 window.focus(&item.child_focus_handles[0], cx);
10801 });
10802 cx.executor().run_until_parked();
10803 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
10804
10805 // Moving focus from one child to another within the same item should
10806 // NOT trigger autosave — focus is still within the item's focus hierarchy.
10807 item.update_in(cx, |item, window, cx| {
10808 window.focus(&item.child_focus_handles[1], cx);
10809 });
10810 cx.executor().run_until_parked();
10811 item.read_with(cx, |item, _| {
10812 assert_eq!(
10813 item.save_count, 0,
10814 "Switching focus between children within the same item should not autosave"
10815 );
10816 });
10817
10818 // Blurring the item saves the file. This is the core regression scenario:
10819 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
10820 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
10821 // the leaf is always a child focus handle, so `on_blur` never detected
10822 // focus leaving the item.
10823 item.update_in(cx, |_, window, _| window.blur());
10824 cx.executor().run_until_parked();
10825 item.read_with(cx, |item, _| {
10826 assert_eq!(
10827 item.save_count, 1,
10828 "Blurring should trigger autosave when focus was on a child of the item"
10829 );
10830 });
10831
10832 // Deactivating the window should also trigger autosave when a child of
10833 // the multibuffer item currently owns focus.
10834 item.update_in(cx, |item, window, cx| {
10835 item.is_dirty = true;
10836 window.focus(&item.child_focus_handles[0], cx);
10837 });
10838 cx.executor().run_until_parked();
10839 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10840
10841 cx.deactivate_window();
10842 item.read_with(cx, |item, _| {
10843 assert_eq!(
10844 item.save_count, 2,
10845 "Deactivating window should trigger autosave when focus was on a child"
10846 );
10847 });
10848 }
10849
10850 #[gpui::test]
10851 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10852 init_test(cx);
10853
10854 let fs = FakeFs::new(cx.executor());
10855
10856 let project = Project::test(fs, [], cx).await;
10857 let (workspace, cx) =
10858 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10859
10860 let item = cx.new(|cx| {
10861 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10862 });
10863 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10864 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10865 let toolbar_notify_count = Rc::new(RefCell::new(0));
10866
10867 workspace.update_in(cx, |workspace, window, cx| {
10868 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10869 let toolbar_notification_count = toolbar_notify_count.clone();
10870 cx.observe_in(&toolbar, window, move |_, _, _, _| {
10871 *toolbar_notification_count.borrow_mut() += 1
10872 })
10873 .detach();
10874 });
10875
10876 pane.read_with(cx, |pane, _| {
10877 assert!(!pane.can_navigate_backward());
10878 assert!(!pane.can_navigate_forward());
10879 });
10880
10881 item.update_in(cx, |item, _, cx| {
10882 item.set_state("one".to_string(), cx);
10883 });
10884
10885 // Toolbar must be notified to re-render the navigation buttons
10886 assert_eq!(*toolbar_notify_count.borrow(), 1);
10887
10888 pane.read_with(cx, |pane, _| {
10889 assert!(pane.can_navigate_backward());
10890 assert!(!pane.can_navigate_forward());
10891 });
10892
10893 workspace
10894 .update_in(cx, |workspace, window, cx| {
10895 workspace.go_back(pane.downgrade(), window, cx)
10896 })
10897 .await
10898 .unwrap();
10899
10900 assert_eq!(*toolbar_notify_count.borrow(), 2);
10901 pane.read_with(cx, |pane, _| {
10902 assert!(!pane.can_navigate_backward());
10903 assert!(pane.can_navigate_forward());
10904 });
10905 }
10906
10907 #[gpui::test]
10908 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
10909 init_test(cx);
10910 let fs = FakeFs::new(cx.executor());
10911 let project = Project::test(fs, [], cx).await;
10912 let (multi_workspace, cx) =
10913 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
10914 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
10915
10916 workspace.update_in(cx, |workspace, window, cx| {
10917 let first_item = cx.new(|cx| {
10918 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10919 });
10920 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
10921 workspace.split_pane(
10922 workspace.active_pane().clone(),
10923 SplitDirection::Right,
10924 window,
10925 cx,
10926 );
10927 workspace.split_pane(
10928 workspace.active_pane().clone(),
10929 SplitDirection::Right,
10930 window,
10931 cx,
10932 );
10933 });
10934
10935 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
10936 let panes = workspace.center.panes();
10937 assert!(panes.len() >= 2);
10938 (
10939 panes.first().expect("at least one pane").entity_id(),
10940 panes.last().expect("at least one pane").entity_id(),
10941 )
10942 });
10943
10944 workspace.update_in(cx, |workspace, window, cx| {
10945 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
10946 });
10947 workspace.update(cx, |workspace, _| {
10948 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
10949 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
10950 });
10951
10952 cx.dispatch_action(ActivateLastPane);
10953
10954 workspace.update(cx, |workspace, _| {
10955 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
10956 });
10957 }
10958
10959 #[gpui::test]
10960 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
10961 init_test(cx);
10962 let fs = FakeFs::new(cx.executor());
10963
10964 let project = Project::test(fs, [], cx).await;
10965 let (workspace, cx) =
10966 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10967
10968 let panel = workspace.update_in(cx, |workspace, window, cx| {
10969 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10970 workspace.add_panel(panel.clone(), window, cx);
10971
10972 workspace
10973 .right_dock()
10974 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10975
10976 panel
10977 });
10978
10979 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10980 pane.update_in(cx, |pane, window, cx| {
10981 let item = cx.new(TestItem::new);
10982 pane.add_item(Box::new(item), true, true, None, window, cx);
10983 });
10984
10985 // Transfer focus from center to panel
10986 workspace.update_in(cx, |workspace, window, cx| {
10987 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10988 });
10989
10990 workspace.update_in(cx, |workspace, window, cx| {
10991 assert!(workspace.right_dock().read(cx).is_open());
10992 assert!(!panel.is_zoomed(window, cx));
10993 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10994 });
10995
10996 // Transfer focus from panel to center
10997 workspace.update_in(cx, |workspace, window, cx| {
10998 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10999 });
11000
11001 workspace.update_in(cx, |workspace, window, cx| {
11002 assert!(workspace.right_dock().read(cx).is_open());
11003 assert!(!panel.is_zoomed(window, cx));
11004 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11005 });
11006
11007 // Close the dock
11008 workspace.update_in(cx, |workspace, window, cx| {
11009 workspace.toggle_dock(DockPosition::Right, window, cx);
11010 });
11011
11012 workspace.update_in(cx, |workspace, window, cx| {
11013 assert!(!workspace.right_dock().read(cx).is_open());
11014 assert!(!panel.is_zoomed(window, cx));
11015 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11016 });
11017
11018 // Open the dock
11019 workspace.update_in(cx, |workspace, window, cx| {
11020 workspace.toggle_dock(DockPosition::Right, window, cx);
11021 });
11022
11023 workspace.update_in(cx, |workspace, window, cx| {
11024 assert!(workspace.right_dock().read(cx).is_open());
11025 assert!(!panel.is_zoomed(window, cx));
11026 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11027 });
11028
11029 // Focus and zoom panel
11030 panel.update_in(cx, |panel, window, cx| {
11031 cx.focus_self(window);
11032 panel.set_zoomed(true, window, cx)
11033 });
11034
11035 workspace.update_in(cx, |workspace, window, cx| {
11036 assert!(workspace.right_dock().read(cx).is_open());
11037 assert!(panel.is_zoomed(window, cx));
11038 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11039 });
11040
11041 // Transfer focus to the center closes the dock
11042 workspace.update_in(cx, |workspace, window, cx| {
11043 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11044 });
11045
11046 workspace.update_in(cx, |workspace, window, cx| {
11047 assert!(!workspace.right_dock().read(cx).is_open());
11048 assert!(panel.is_zoomed(window, cx));
11049 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11050 });
11051
11052 // Transferring focus back to the panel keeps it zoomed
11053 workspace.update_in(cx, |workspace, window, cx| {
11054 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11055 });
11056
11057 workspace.update_in(cx, |workspace, window, cx| {
11058 assert!(workspace.right_dock().read(cx).is_open());
11059 assert!(panel.is_zoomed(window, cx));
11060 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11061 });
11062
11063 // Close the dock while it is zoomed
11064 workspace.update_in(cx, |workspace, window, cx| {
11065 workspace.toggle_dock(DockPosition::Right, window, cx)
11066 });
11067
11068 workspace.update_in(cx, |workspace, window, cx| {
11069 assert!(!workspace.right_dock().read(cx).is_open());
11070 assert!(panel.is_zoomed(window, cx));
11071 assert!(workspace.zoomed.is_none());
11072 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11073 });
11074
11075 // Opening the dock, when it's zoomed, retains focus
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!(workspace.zoomed.is_some());
11084 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11085 });
11086
11087 // Unzoom and close the panel, zoom the active pane.
11088 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11089 workspace.update_in(cx, |workspace, window, cx| {
11090 workspace.toggle_dock(DockPosition::Right, window, cx)
11091 });
11092 pane.update_in(cx, |pane, window, cx| {
11093 pane.toggle_zoom(&Default::default(), window, cx)
11094 });
11095
11096 // Opening a dock unzooms the pane.
11097 workspace.update_in(cx, |workspace, window, cx| {
11098 workspace.toggle_dock(DockPosition::Right, window, cx)
11099 });
11100 workspace.update_in(cx, |workspace, window, cx| {
11101 let pane = pane.read(cx);
11102 assert!(!pane.is_zoomed());
11103 assert!(!pane.focus_handle(cx).is_focused(window));
11104 assert!(workspace.right_dock().read(cx).is_open());
11105 assert!(workspace.zoomed.is_none());
11106 });
11107 }
11108
11109 #[gpui::test]
11110 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11111 init_test(cx);
11112 let fs = FakeFs::new(cx.executor());
11113
11114 let project = Project::test(fs, [], cx).await;
11115 let (workspace, cx) =
11116 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11117
11118 let panel = workspace.update_in(cx, |workspace, window, cx| {
11119 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11120 workspace.add_panel(panel.clone(), window, cx);
11121 panel
11122 });
11123
11124 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11125 pane.update_in(cx, |pane, window, cx| {
11126 let item = cx.new(TestItem::new);
11127 pane.add_item(Box::new(item), true, true, None, window, cx);
11128 });
11129
11130 // Enable close_panel_on_toggle
11131 cx.update_global(|store: &mut SettingsStore, cx| {
11132 store.update_user_settings(cx, |settings| {
11133 settings.workspace.close_panel_on_toggle = Some(true);
11134 });
11135 });
11136
11137 // Panel starts closed. Toggling should open and focus it.
11138 workspace.update_in(cx, |workspace, window, cx| {
11139 assert!(!workspace.right_dock().read(cx).is_open());
11140 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11141 });
11142
11143 workspace.update_in(cx, |workspace, window, cx| {
11144 assert!(
11145 workspace.right_dock().read(cx).is_open(),
11146 "Dock should be open after toggling from center"
11147 );
11148 assert!(
11149 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11150 "Panel should be focused after toggling from center"
11151 );
11152 });
11153
11154 // Panel is open and focused. Toggling should close the panel and
11155 // return focus to the center.
11156 workspace.update_in(cx, |workspace, window, cx| {
11157 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11158 });
11159
11160 workspace.update_in(cx, |workspace, window, cx| {
11161 assert!(
11162 !workspace.right_dock().read(cx).is_open(),
11163 "Dock should be closed after toggling from focused panel"
11164 );
11165 assert!(
11166 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11167 "Panel should not be focused after toggling from focused panel"
11168 );
11169 });
11170
11171 // Open the dock and focus something else so the panel is open but not
11172 // focused. Toggling should focus the panel (not close it).
11173 workspace.update_in(cx, |workspace, window, cx| {
11174 workspace
11175 .right_dock()
11176 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11177 window.focus(&pane.read(cx).focus_handle(cx), cx);
11178 });
11179
11180 workspace.update_in(cx, |workspace, window, cx| {
11181 assert!(workspace.right_dock().read(cx).is_open());
11182 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11183 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11184 });
11185
11186 workspace.update_in(cx, |workspace, window, cx| {
11187 assert!(
11188 workspace.right_dock().read(cx).is_open(),
11189 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11190 );
11191 assert!(
11192 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11193 "Panel should be focused after toggling an open-but-unfocused panel"
11194 );
11195 });
11196
11197 // Now disable the setting and verify the original behavior: toggling
11198 // from a focused panel moves focus to center but leaves the dock open.
11199 cx.update_global(|store: &mut SettingsStore, cx| {
11200 store.update_user_settings(cx, |settings| {
11201 settings.workspace.close_panel_on_toggle = Some(false);
11202 });
11203 });
11204
11205 workspace.update_in(cx, |workspace, window, cx| {
11206 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11207 });
11208
11209 workspace.update_in(cx, |workspace, window, cx| {
11210 assert!(
11211 workspace.right_dock().read(cx).is_open(),
11212 "Dock should remain open when setting is disabled"
11213 );
11214 assert!(
11215 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11216 "Panel should not be focused after toggling with setting disabled"
11217 );
11218 });
11219 }
11220
11221 #[gpui::test]
11222 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11223 init_test(cx);
11224 let fs = FakeFs::new(cx.executor());
11225
11226 let project = Project::test(fs, [], cx).await;
11227 let (workspace, cx) =
11228 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11229
11230 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11231 workspace.active_pane().clone()
11232 });
11233
11234 // Add an item to the pane so it can be zoomed
11235 workspace.update_in(cx, |workspace, window, cx| {
11236 let item = cx.new(TestItem::new);
11237 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11238 });
11239
11240 // Initially not zoomed
11241 workspace.update_in(cx, |workspace, _window, cx| {
11242 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11243 assert!(
11244 workspace.zoomed.is_none(),
11245 "Workspace should track no zoomed pane"
11246 );
11247 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11248 });
11249
11250 // Zoom In
11251 pane.update_in(cx, |pane, window, cx| {
11252 pane.zoom_in(&crate::ZoomIn, window, cx);
11253 });
11254
11255 workspace.update_in(cx, |workspace, window, cx| {
11256 assert!(
11257 pane.read(cx).is_zoomed(),
11258 "Pane should be zoomed after ZoomIn"
11259 );
11260 assert!(
11261 workspace.zoomed.is_some(),
11262 "Workspace should track the zoomed pane"
11263 );
11264 assert!(
11265 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11266 "ZoomIn should focus the pane"
11267 );
11268 });
11269
11270 // Zoom In again is a no-op
11271 pane.update_in(cx, |pane, window, cx| {
11272 pane.zoom_in(&crate::ZoomIn, window, cx);
11273 });
11274
11275 workspace.update_in(cx, |workspace, window, cx| {
11276 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11277 assert!(
11278 workspace.zoomed.is_some(),
11279 "Workspace still tracks zoomed pane"
11280 );
11281 assert!(
11282 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11283 "Pane remains focused after repeated ZoomIn"
11284 );
11285 });
11286
11287 // Zoom Out
11288 pane.update_in(cx, |pane, window, cx| {
11289 pane.zoom_out(&crate::ZoomOut, window, cx);
11290 });
11291
11292 workspace.update_in(cx, |workspace, _window, cx| {
11293 assert!(
11294 !pane.read(cx).is_zoomed(),
11295 "Pane should unzoom after ZoomOut"
11296 );
11297 assert!(
11298 workspace.zoomed.is_none(),
11299 "Workspace clears zoom tracking after ZoomOut"
11300 );
11301 });
11302
11303 // Zoom Out again is a no-op
11304 pane.update_in(cx, |pane, window, cx| {
11305 pane.zoom_out(&crate::ZoomOut, window, cx);
11306 });
11307
11308 workspace.update_in(cx, |workspace, _window, cx| {
11309 assert!(
11310 !pane.read(cx).is_zoomed(),
11311 "Second ZoomOut keeps pane unzoomed"
11312 );
11313 assert!(
11314 workspace.zoomed.is_none(),
11315 "Workspace remains without zoomed pane"
11316 );
11317 });
11318 }
11319
11320 #[gpui::test]
11321 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11322 init_test(cx);
11323 let fs = FakeFs::new(cx.executor());
11324
11325 let project = Project::test(fs, [], cx).await;
11326 let (workspace, cx) =
11327 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11328 workspace.update_in(cx, |workspace, window, cx| {
11329 // Open two docks
11330 let left_dock = workspace.dock_at_position(DockPosition::Left);
11331 let right_dock = workspace.dock_at_position(DockPosition::Right);
11332
11333 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11334 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11335
11336 assert!(left_dock.read(cx).is_open());
11337 assert!(right_dock.read(cx).is_open());
11338 });
11339
11340 workspace.update_in(cx, |workspace, window, cx| {
11341 // Toggle all docks - should close both
11342 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11343
11344 let left_dock = workspace.dock_at_position(DockPosition::Left);
11345 let right_dock = workspace.dock_at_position(DockPosition::Right);
11346 assert!(!left_dock.read(cx).is_open());
11347 assert!(!right_dock.read(cx).is_open());
11348 });
11349
11350 workspace.update_in(cx, |workspace, window, cx| {
11351 // Toggle again - should reopen both
11352 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11353
11354 let left_dock = workspace.dock_at_position(DockPosition::Left);
11355 let right_dock = workspace.dock_at_position(DockPosition::Right);
11356 assert!(left_dock.read(cx).is_open());
11357 assert!(right_dock.read(cx).is_open());
11358 });
11359 }
11360
11361 #[gpui::test]
11362 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11363 init_test(cx);
11364 let fs = FakeFs::new(cx.executor());
11365
11366 let project = Project::test(fs, [], cx).await;
11367 let (workspace, cx) =
11368 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11369 workspace.update_in(cx, |workspace, window, cx| {
11370 // Open two docks
11371 let left_dock = workspace.dock_at_position(DockPosition::Left);
11372 let right_dock = workspace.dock_at_position(DockPosition::Right);
11373
11374 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11375 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11376
11377 assert!(left_dock.read(cx).is_open());
11378 assert!(right_dock.read(cx).is_open());
11379 });
11380
11381 workspace.update_in(cx, |workspace, window, cx| {
11382 // Close them manually
11383 workspace.toggle_dock(DockPosition::Left, window, cx);
11384 workspace.toggle_dock(DockPosition::Right, window, cx);
11385
11386 let left_dock = workspace.dock_at_position(DockPosition::Left);
11387 let right_dock = workspace.dock_at_position(DockPosition::Right);
11388 assert!(!left_dock.read(cx).is_open());
11389 assert!(!right_dock.read(cx).is_open());
11390 });
11391
11392 workspace.update_in(cx, |workspace, window, cx| {
11393 // Toggle all docks - only last closed (right dock) should reopen
11394 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11395
11396 let left_dock = workspace.dock_at_position(DockPosition::Left);
11397 let right_dock = workspace.dock_at_position(DockPosition::Right);
11398 assert!(!left_dock.read(cx).is_open());
11399 assert!(right_dock.read(cx).is_open());
11400 });
11401 }
11402
11403 #[gpui::test]
11404 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11405 init_test(cx);
11406 let fs = FakeFs::new(cx.executor());
11407 let project = Project::test(fs, [], cx).await;
11408 let (multi_workspace, cx) =
11409 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11410 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11411
11412 // Open two docks (left and right) with one panel each
11413 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11414 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11415 workspace.add_panel(left_panel.clone(), window, cx);
11416
11417 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11418 workspace.add_panel(right_panel.clone(), window, cx);
11419
11420 workspace.toggle_dock(DockPosition::Left, window, cx);
11421 workspace.toggle_dock(DockPosition::Right, window, cx);
11422
11423 // Verify initial state
11424 assert!(
11425 workspace.left_dock().read(cx).is_open(),
11426 "Left dock should be open"
11427 );
11428 assert_eq!(
11429 workspace
11430 .left_dock()
11431 .read(cx)
11432 .visible_panel()
11433 .unwrap()
11434 .panel_id(),
11435 left_panel.panel_id(),
11436 "Left panel should be visible in left dock"
11437 );
11438 assert!(
11439 workspace.right_dock().read(cx).is_open(),
11440 "Right dock should be open"
11441 );
11442 assert_eq!(
11443 workspace
11444 .right_dock()
11445 .read(cx)
11446 .visible_panel()
11447 .unwrap()
11448 .panel_id(),
11449 right_panel.panel_id(),
11450 "Right panel should be visible in right dock"
11451 );
11452 assert!(
11453 !workspace.bottom_dock().read(cx).is_open(),
11454 "Bottom dock should be closed"
11455 );
11456
11457 (left_panel, right_panel)
11458 });
11459
11460 // Focus the left panel and move it to the next position (bottom dock)
11461 workspace.update_in(cx, |workspace, window, cx| {
11462 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11463 assert!(
11464 left_panel.read(cx).focus_handle(cx).is_focused(window),
11465 "Left panel should be focused"
11466 );
11467 });
11468
11469 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11470
11471 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11472 workspace.update(cx, |workspace, cx| {
11473 assert!(
11474 !workspace.left_dock().read(cx).is_open(),
11475 "Left dock should be closed"
11476 );
11477 assert!(
11478 workspace.bottom_dock().read(cx).is_open(),
11479 "Bottom dock should now be open"
11480 );
11481 assert_eq!(
11482 left_panel.read(cx).position,
11483 DockPosition::Bottom,
11484 "Left panel should now be in the bottom dock"
11485 );
11486 assert_eq!(
11487 workspace
11488 .bottom_dock()
11489 .read(cx)
11490 .visible_panel()
11491 .unwrap()
11492 .panel_id(),
11493 left_panel.panel_id(),
11494 "Left panel should be the visible panel in the bottom dock"
11495 );
11496 });
11497
11498 // Toggle all docks off
11499 workspace.update_in(cx, |workspace, window, cx| {
11500 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11501 assert!(
11502 !workspace.left_dock().read(cx).is_open(),
11503 "Left dock should be closed"
11504 );
11505 assert!(
11506 !workspace.right_dock().read(cx).is_open(),
11507 "Right dock should be closed"
11508 );
11509 assert!(
11510 !workspace.bottom_dock().read(cx).is_open(),
11511 "Bottom dock should be closed"
11512 );
11513 });
11514
11515 // Toggle all docks back on and verify positions are restored
11516 workspace.update_in(cx, |workspace, window, cx| {
11517 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11518 assert!(
11519 !workspace.left_dock().read(cx).is_open(),
11520 "Left dock should remain closed"
11521 );
11522 assert!(
11523 workspace.right_dock().read(cx).is_open(),
11524 "Right dock should remain open"
11525 );
11526 assert!(
11527 workspace.bottom_dock().read(cx).is_open(),
11528 "Bottom dock should remain open"
11529 );
11530 assert_eq!(
11531 left_panel.read(cx).position,
11532 DockPosition::Bottom,
11533 "Left panel should remain in the bottom dock"
11534 );
11535 assert_eq!(
11536 right_panel.read(cx).position,
11537 DockPosition::Right,
11538 "Right panel should remain in the right dock"
11539 );
11540 assert_eq!(
11541 workspace
11542 .bottom_dock()
11543 .read(cx)
11544 .visible_panel()
11545 .unwrap()
11546 .panel_id(),
11547 left_panel.panel_id(),
11548 "Left panel should be the visible panel in the right dock"
11549 );
11550 });
11551 }
11552
11553 #[gpui::test]
11554 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11555 init_test(cx);
11556
11557 let fs = FakeFs::new(cx.executor());
11558
11559 let project = Project::test(fs, None, cx).await;
11560 let (workspace, cx) =
11561 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11562
11563 // Let's arrange the panes like this:
11564 //
11565 // +-----------------------+
11566 // | top |
11567 // +------+--------+-------+
11568 // | left | center | right |
11569 // +------+--------+-------+
11570 // | bottom |
11571 // +-----------------------+
11572
11573 let top_item = cx.new(|cx| {
11574 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11575 });
11576 let bottom_item = cx.new(|cx| {
11577 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11578 });
11579 let left_item = cx.new(|cx| {
11580 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11581 });
11582 let right_item = cx.new(|cx| {
11583 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11584 });
11585 let center_item = cx.new(|cx| {
11586 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11587 });
11588
11589 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11590 let top_pane_id = workspace.active_pane().entity_id();
11591 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11592 workspace.split_pane(
11593 workspace.active_pane().clone(),
11594 SplitDirection::Down,
11595 window,
11596 cx,
11597 );
11598 top_pane_id
11599 });
11600 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11601 let bottom_pane_id = workspace.active_pane().entity_id();
11602 workspace.add_item_to_active_pane(
11603 Box::new(bottom_item.clone()),
11604 None,
11605 false,
11606 window,
11607 cx,
11608 );
11609 workspace.split_pane(
11610 workspace.active_pane().clone(),
11611 SplitDirection::Up,
11612 window,
11613 cx,
11614 );
11615 bottom_pane_id
11616 });
11617 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11618 let left_pane_id = workspace.active_pane().entity_id();
11619 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11620 workspace.split_pane(
11621 workspace.active_pane().clone(),
11622 SplitDirection::Right,
11623 window,
11624 cx,
11625 );
11626 left_pane_id
11627 });
11628 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11629 let right_pane_id = workspace.active_pane().entity_id();
11630 workspace.add_item_to_active_pane(
11631 Box::new(right_item.clone()),
11632 None,
11633 false,
11634 window,
11635 cx,
11636 );
11637 workspace.split_pane(
11638 workspace.active_pane().clone(),
11639 SplitDirection::Left,
11640 window,
11641 cx,
11642 );
11643 right_pane_id
11644 });
11645 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11646 let center_pane_id = workspace.active_pane().entity_id();
11647 workspace.add_item_to_active_pane(
11648 Box::new(center_item.clone()),
11649 None,
11650 false,
11651 window,
11652 cx,
11653 );
11654 center_pane_id
11655 });
11656 cx.executor().run_until_parked();
11657
11658 workspace.update_in(cx, |workspace, window, cx| {
11659 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11660
11661 // Join into next from center pane into right
11662 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11663 });
11664
11665 workspace.update_in(cx, |workspace, window, cx| {
11666 let active_pane = workspace.active_pane();
11667 assert_eq!(right_pane_id, active_pane.entity_id());
11668 assert_eq!(2, active_pane.read(cx).items_len());
11669 let item_ids_in_pane =
11670 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11671 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11672 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11673
11674 // Join into next from right pane into bottom
11675 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11676 });
11677
11678 workspace.update_in(cx, |workspace, window, cx| {
11679 let active_pane = workspace.active_pane();
11680 assert_eq!(bottom_pane_id, active_pane.entity_id());
11681 assert_eq!(3, active_pane.read(cx).items_len());
11682 let item_ids_in_pane =
11683 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11684 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11685 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11686 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11687
11688 // Join into next from bottom pane into left
11689 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11690 });
11691
11692 workspace.update_in(cx, |workspace, window, cx| {
11693 let active_pane = workspace.active_pane();
11694 assert_eq!(left_pane_id, active_pane.entity_id());
11695 assert_eq!(4, active_pane.read(cx).items_len());
11696 let item_ids_in_pane =
11697 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11698 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11699 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11700 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11701 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11702
11703 // Join into next from left pane into top
11704 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11705 });
11706
11707 workspace.update_in(cx, |workspace, window, cx| {
11708 let active_pane = workspace.active_pane();
11709 assert_eq!(top_pane_id, active_pane.entity_id());
11710 assert_eq!(5, active_pane.read(cx).items_len());
11711 let item_ids_in_pane =
11712 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11713 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11714 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11715 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11716 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11717 assert!(item_ids_in_pane.contains(&top_item.item_id()));
11718
11719 // Single pane left: no-op
11720 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11721 });
11722
11723 workspace.update(cx, |workspace, _cx| {
11724 let active_pane = workspace.active_pane();
11725 assert_eq!(top_pane_id, active_pane.entity_id());
11726 });
11727 }
11728
11729 fn add_an_item_to_active_pane(
11730 cx: &mut VisualTestContext,
11731 workspace: &Entity<Workspace>,
11732 item_id: u64,
11733 ) -> Entity<TestItem> {
11734 let item = cx.new(|cx| {
11735 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11736 item_id,
11737 "item{item_id}.txt",
11738 cx,
11739 )])
11740 });
11741 workspace.update_in(cx, |workspace, window, cx| {
11742 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11743 });
11744 item
11745 }
11746
11747 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11748 workspace.update_in(cx, |workspace, window, cx| {
11749 workspace.split_pane(
11750 workspace.active_pane().clone(),
11751 SplitDirection::Right,
11752 window,
11753 cx,
11754 )
11755 })
11756 }
11757
11758 #[gpui::test]
11759 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11760 init_test(cx);
11761 let fs = FakeFs::new(cx.executor());
11762 let project = Project::test(fs, None, cx).await;
11763 let (workspace, cx) =
11764 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11765
11766 add_an_item_to_active_pane(cx, &workspace, 1);
11767 split_pane(cx, &workspace);
11768 add_an_item_to_active_pane(cx, &workspace, 2);
11769 split_pane(cx, &workspace); // empty pane
11770 split_pane(cx, &workspace);
11771 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11772
11773 cx.executor().run_until_parked();
11774
11775 workspace.update(cx, |workspace, cx| {
11776 let num_panes = workspace.panes().len();
11777 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11778 let active_item = workspace
11779 .active_pane()
11780 .read(cx)
11781 .active_item()
11782 .expect("item is in focus");
11783
11784 assert_eq!(num_panes, 4);
11785 assert_eq!(num_items_in_current_pane, 1);
11786 assert_eq!(active_item.item_id(), last_item.item_id());
11787 });
11788
11789 workspace.update_in(cx, |workspace, window, cx| {
11790 workspace.join_all_panes(window, cx);
11791 });
11792
11793 workspace.update(cx, |workspace, cx| {
11794 let num_panes = workspace.panes().len();
11795 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11796 let active_item = workspace
11797 .active_pane()
11798 .read(cx)
11799 .active_item()
11800 .expect("item is in focus");
11801
11802 assert_eq!(num_panes, 1);
11803 assert_eq!(num_items_in_current_pane, 3);
11804 assert_eq!(active_item.item_id(), last_item.item_id());
11805 });
11806 }
11807 struct TestModal(FocusHandle);
11808
11809 impl TestModal {
11810 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11811 Self(cx.focus_handle())
11812 }
11813 }
11814
11815 impl EventEmitter<DismissEvent> for TestModal {}
11816
11817 impl Focusable for TestModal {
11818 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11819 self.0.clone()
11820 }
11821 }
11822
11823 impl ModalView for TestModal {}
11824
11825 impl Render for TestModal {
11826 fn render(
11827 &mut self,
11828 _window: &mut Window,
11829 _cx: &mut Context<TestModal>,
11830 ) -> impl IntoElement {
11831 div().track_focus(&self.0)
11832 }
11833 }
11834
11835 #[gpui::test]
11836 async fn test_panels(cx: &mut gpui::TestAppContext) {
11837 init_test(cx);
11838 let fs = FakeFs::new(cx.executor());
11839
11840 let project = Project::test(fs, [], cx).await;
11841 let (multi_workspace, cx) =
11842 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11843 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11844
11845 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11846 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11847 workspace.add_panel(panel_1.clone(), window, cx);
11848 workspace.toggle_dock(DockPosition::Left, window, cx);
11849 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11850 workspace.add_panel(panel_2.clone(), window, cx);
11851 workspace.toggle_dock(DockPosition::Right, window, cx);
11852
11853 let left_dock = workspace.left_dock();
11854 assert_eq!(
11855 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11856 panel_1.panel_id()
11857 );
11858 assert_eq!(
11859 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11860 panel_1.size(window, cx)
11861 );
11862
11863 left_dock.update(cx, |left_dock, cx| {
11864 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11865 });
11866 assert_eq!(
11867 workspace
11868 .right_dock()
11869 .read(cx)
11870 .visible_panel()
11871 .unwrap()
11872 .panel_id(),
11873 panel_2.panel_id(),
11874 );
11875
11876 (panel_1, panel_2)
11877 });
11878
11879 // Move panel_1 to the right
11880 panel_1.update_in(cx, |panel_1, window, cx| {
11881 panel_1.set_position(DockPosition::Right, window, cx)
11882 });
11883
11884 workspace.update_in(cx, |workspace, window, cx| {
11885 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11886 // Since it was the only panel on the left, the left dock should now be closed.
11887 assert!(!workspace.left_dock().read(cx).is_open());
11888 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11889 let right_dock = workspace.right_dock();
11890 assert_eq!(
11891 right_dock.read(cx).visible_panel().unwrap().panel_id(),
11892 panel_1.panel_id()
11893 );
11894 assert_eq!(
11895 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11896 px(1337.)
11897 );
11898
11899 // Now we move panel_2 to the left
11900 panel_2.set_position(DockPosition::Left, window, cx);
11901 });
11902
11903 workspace.update(cx, |workspace, cx| {
11904 // Since panel_2 was not visible on the right, we don't open the left dock.
11905 assert!(!workspace.left_dock().read(cx).is_open());
11906 // And the right dock is unaffected in its displaying of panel_1
11907 assert!(workspace.right_dock().read(cx).is_open());
11908 assert_eq!(
11909 workspace
11910 .right_dock()
11911 .read(cx)
11912 .visible_panel()
11913 .unwrap()
11914 .panel_id(),
11915 panel_1.panel_id(),
11916 );
11917 });
11918
11919 // Move panel_1 back to the left
11920 panel_1.update_in(cx, |panel_1, window, cx| {
11921 panel_1.set_position(DockPosition::Left, window, cx)
11922 });
11923
11924 workspace.update_in(cx, |workspace, window, cx| {
11925 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11926 let left_dock = workspace.left_dock();
11927 assert!(left_dock.read(cx).is_open());
11928 assert_eq!(
11929 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11930 panel_1.panel_id()
11931 );
11932 assert_eq!(
11933 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11934 px(1337.)
11935 );
11936 // And the right dock should be closed as it no longer has any panels.
11937 assert!(!workspace.right_dock().read(cx).is_open());
11938
11939 // Now we move panel_1 to the bottom
11940 panel_1.set_position(DockPosition::Bottom, window, cx);
11941 });
11942
11943 workspace.update_in(cx, |workspace, window, cx| {
11944 // Since panel_1 was visible on the left, we close the left dock.
11945 assert!(!workspace.left_dock().read(cx).is_open());
11946 // The bottom dock is sized based on the panel's default size,
11947 // since the panel orientation changed from vertical to horizontal.
11948 let bottom_dock = workspace.bottom_dock();
11949 assert_eq!(
11950 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
11951 panel_1.size(window, cx),
11952 );
11953 // Close bottom dock and move panel_1 back to the left.
11954 bottom_dock.update(cx, |bottom_dock, cx| {
11955 bottom_dock.set_open(false, window, cx)
11956 });
11957 panel_1.set_position(DockPosition::Left, window, cx);
11958 });
11959
11960 // Emit activated event on panel 1
11961 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
11962
11963 // Now the left dock is open and panel_1 is active and focused.
11964 workspace.update_in(cx, |workspace, window, cx| {
11965 let left_dock = workspace.left_dock();
11966 assert!(left_dock.read(cx).is_open());
11967 assert_eq!(
11968 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11969 panel_1.panel_id(),
11970 );
11971 assert!(panel_1.focus_handle(cx).is_focused(window));
11972 });
11973
11974 // Emit closed event on panel 2, which is not active
11975 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11976
11977 // Wo don't close the left dock, because panel_2 wasn't the active panel
11978 workspace.update(cx, |workspace, cx| {
11979 let left_dock = workspace.left_dock();
11980 assert!(left_dock.read(cx).is_open());
11981 assert_eq!(
11982 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11983 panel_1.panel_id(),
11984 );
11985 });
11986
11987 // Emitting a ZoomIn event shows the panel as zoomed.
11988 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
11989 workspace.read_with(cx, |workspace, _| {
11990 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11991 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
11992 });
11993
11994 // Move panel to another dock while it is zoomed
11995 panel_1.update_in(cx, |panel, window, cx| {
11996 panel.set_position(DockPosition::Right, window, cx)
11997 });
11998 workspace.read_with(cx, |workspace, _| {
11999 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12000
12001 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12002 });
12003
12004 // This is a helper for getting a:
12005 // - valid focus on an element,
12006 // - that isn't a part of the panes and panels system of the Workspace,
12007 // - and doesn't trigger the 'on_focus_lost' API.
12008 let focus_other_view = {
12009 let workspace = workspace.clone();
12010 move |cx: &mut VisualTestContext| {
12011 workspace.update_in(cx, |workspace, window, cx| {
12012 if workspace.active_modal::<TestModal>(cx).is_some() {
12013 workspace.toggle_modal(window, cx, TestModal::new);
12014 workspace.toggle_modal(window, cx, TestModal::new);
12015 } else {
12016 workspace.toggle_modal(window, cx, TestModal::new);
12017 }
12018 })
12019 }
12020 };
12021
12022 // If focus is transferred to another view that's not a panel or another pane, we still show
12023 // the panel as zoomed.
12024 focus_other_view(cx);
12025 workspace.read_with(cx, |workspace, _| {
12026 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12027 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12028 });
12029
12030 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12031 workspace.update_in(cx, |_workspace, window, cx| {
12032 cx.focus_self(window);
12033 });
12034 workspace.read_with(cx, |workspace, _| {
12035 assert_eq!(workspace.zoomed, None);
12036 assert_eq!(workspace.zoomed_position, None);
12037 });
12038
12039 // If focus is transferred again to another view that's not a panel or a pane, we won't
12040 // show the panel as zoomed because it wasn't zoomed before.
12041 focus_other_view(cx);
12042 workspace.read_with(cx, |workspace, _| {
12043 assert_eq!(workspace.zoomed, None);
12044 assert_eq!(workspace.zoomed_position, None);
12045 });
12046
12047 // When the panel is activated, it is zoomed again.
12048 cx.dispatch_action(ToggleRightDock);
12049 workspace.read_with(cx, |workspace, _| {
12050 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12051 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12052 });
12053
12054 // Emitting a ZoomOut event unzooms the panel.
12055 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12056 workspace.read_with(cx, |workspace, _| {
12057 assert_eq!(workspace.zoomed, None);
12058 assert_eq!(workspace.zoomed_position, None);
12059 });
12060
12061 // Emit closed event on panel 1, which is active
12062 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12063
12064 // Now the left dock is closed, because panel_1 was the active panel
12065 workspace.update(cx, |workspace, cx| {
12066 let right_dock = workspace.right_dock();
12067 assert!(!right_dock.read(cx).is_open());
12068 });
12069 }
12070
12071 #[gpui::test]
12072 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12073 init_test(cx);
12074
12075 let fs = FakeFs::new(cx.background_executor.clone());
12076 let project = Project::test(fs, [], cx).await;
12077 let (workspace, cx) =
12078 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12079 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12080
12081 let dirty_regular_buffer = cx.new(|cx| {
12082 TestItem::new(cx)
12083 .with_dirty(true)
12084 .with_label("1.txt")
12085 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12086 });
12087 let dirty_regular_buffer_2 = cx.new(|cx| {
12088 TestItem::new(cx)
12089 .with_dirty(true)
12090 .with_label("2.txt")
12091 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12092 });
12093 let dirty_multi_buffer_with_both = cx.new(|cx| {
12094 TestItem::new(cx)
12095 .with_dirty(true)
12096 .with_buffer_kind(ItemBufferKind::Multibuffer)
12097 .with_label("Fake Project Search")
12098 .with_project_items(&[
12099 dirty_regular_buffer.read(cx).project_items[0].clone(),
12100 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12101 ])
12102 });
12103 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12104 workspace.update_in(cx, |workspace, window, cx| {
12105 workspace.add_item(
12106 pane.clone(),
12107 Box::new(dirty_regular_buffer.clone()),
12108 None,
12109 false,
12110 false,
12111 window,
12112 cx,
12113 );
12114 workspace.add_item(
12115 pane.clone(),
12116 Box::new(dirty_regular_buffer_2.clone()),
12117 None,
12118 false,
12119 false,
12120 window,
12121 cx,
12122 );
12123 workspace.add_item(
12124 pane.clone(),
12125 Box::new(dirty_multi_buffer_with_both.clone()),
12126 None,
12127 false,
12128 false,
12129 window,
12130 cx,
12131 );
12132 });
12133
12134 pane.update_in(cx, |pane, window, cx| {
12135 pane.activate_item(2, true, true, window, cx);
12136 assert_eq!(
12137 pane.active_item().unwrap().item_id(),
12138 multi_buffer_with_both_files_id,
12139 "Should select the multi buffer in the pane"
12140 );
12141 });
12142 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12143 pane.close_other_items(
12144 &CloseOtherItems {
12145 save_intent: Some(SaveIntent::Save),
12146 close_pinned: true,
12147 },
12148 None,
12149 window,
12150 cx,
12151 )
12152 });
12153 cx.background_executor.run_until_parked();
12154 assert!(!cx.has_pending_prompt());
12155 close_all_but_multi_buffer_task
12156 .await
12157 .expect("Closing all buffers but the multi buffer failed");
12158 pane.update(cx, |pane, cx| {
12159 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12160 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12161 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12162 assert_eq!(pane.items_len(), 1);
12163 assert_eq!(
12164 pane.active_item().unwrap().item_id(),
12165 multi_buffer_with_both_files_id,
12166 "Should have only the multi buffer left in the pane"
12167 );
12168 assert!(
12169 dirty_multi_buffer_with_both.read(cx).is_dirty,
12170 "The multi buffer containing the unsaved buffer should still be dirty"
12171 );
12172 });
12173
12174 dirty_regular_buffer.update(cx, |buffer, cx| {
12175 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12176 });
12177
12178 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12179 pane.close_active_item(
12180 &CloseActiveItem {
12181 save_intent: Some(SaveIntent::Close),
12182 close_pinned: false,
12183 },
12184 window,
12185 cx,
12186 )
12187 });
12188 cx.background_executor.run_until_parked();
12189 assert!(
12190 cx.has_pending_prompt(),
12191 "Dirty multi buffer should prompt a save dialog"
12192 );
12193 cx.simulate_prompt_answer("Save");
12194 cx.background_executor.run_until_parked();
12195 close_multi_buffer_task
12196 .await
12197 .expect("Closing the multi buffer failed");
12198 pane.update(cx, |pane, cx| {
12199 assert_eq!(
12200 dirty_multi_buffer_with_both.read(cx).save_count,
12201 1,
12202 "Multi buffer item should get be saved"
12203 );
12204 // Test impl does not save inner items, so we do not assert them
12205 assert_eq!(
12206 pane.items_len(),
12207 0,
12208 "No more items should be left in the pane"
12209 );
12210 assert!(pane.active_item().is_none());
12211 });
12212 }
12213
12214 #[gpui::test]
12215 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
12216 cx: &mut TestAppContext,
12217 ) {
12218 init_test(cx);
12219
12220 let fs = FakeFs::new(cx.background_executor.clone());
12221 let project = Project::test(fs, [], cx).await;
12222 let (workspace, cx) =
12223 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12224 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12225
12226 let dirty_regular_buffer = cx.new(|cx| {
12227 TestItem::new(cx)
12228 .with_dirty(true)
12229 .with_label("1.txt")
12230 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12231 });
12232 let dirty_regular_buffer_2 = cx.new(|cx| {
12233 TestItem::new(cx)
12234 .with_dirty(true)
12235 .with_label("2.txt")
12236 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12237 });
12238 let clear_regular_buffer = cx.new(|cx| {
12239 TestItem::new(cx)
12240 .with_label("3.txt")
12241 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12242 });
12243
12244 let dirty_multi_buffer_with_both = cx.new(|cx| {
12245 TestItem::new(cx)
12246 .with_dirty(true)
12247 .with_buffer_kind(ItemBufferKind::Multibuffer)
12248 .with_label("Fake Project Search")
12249 .with_project_items(&[
12250 dirty_regular_buffer.read(cx).project_items[0].clone(),
12251 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12252 clear_regular_buffer.read(cx).project_items[0].clone(),
12253 ])
12254 });
12255 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12256 workspace.update_in(cx, |workspace, window, cx| {
12257 workspace.add_item(
12258 pane.clone(),
12259 Box::new(dirty_regular_buffer.clone()),
12260 None,
12261 false,
12262 false,
12263 window,
12264 cx,
12265 );
12266 workspace.add_item(
12267 pane.clone(),
12268 Box::new(dirty_multi_buffer_with_both.clone()),
12269 None,
12270 false,
12271 false,
12272 window,
12273 cx,
12274 );
12275 });
12276
12277 pane.update_in(cx, |pane, window, cx| {
12278 pane.activate_item(1, true, true, window, cx);
12279 assert_eq!(
12280 pane.active_item().unwrap().item_id(),
12281 multi_buffer_with_both_files_id,
12282 "Should select the multi buffer in the pane"
12283 );
12284 });
12285 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12286 pane.close_active_item(
12287 &CloseActiveItem {
12288 save_intent: None,
12289 close_pinned: false,
12290 },
12291 window,
12292 cx,
12293 )
12294 });
12295 cx.background_executor.run_until_parked();
12296 assert!(
12297 cx.has_pending_prompt(),
12298 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
12299 );
12300 }
12301
12302 /// Tests that when `close_on_file_delete` is enabled, files are automatically
12303 /// closed when they are deleted from disk.
12304 #[gpui::test]
12305 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
12306 init_test(cx);
12307
12308 // Enable the close_on_disk_deletion setting
12309 cx.update_global(|store: &mut SettingsStore, cx| {
12310 store.update_user_settings(cx, |settings| {
12311 settings.workspace.close_on_file_delete = Some(true);
12312 });
12313 });
12314
12315 let fs = FakeFs::new(cx.background_executor.clone());
12316 let project = Project::test(fs, [], cx).await;
12317 let (workspace, cx) =
12318 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12319 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12320
12321 // Create a test item that simulates a file
12322 let item = cx.new(|cx| {
12323 TestItem::new(cx)
12324 .with_label("test.txt")
12325 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12326 });
12327
12328 // Add item to workspace
12329 workspace.update_in(cx, |workspace, window, cx| {
12330 workspace.add_item(
12331 pane.clone(),
12332 Box::new(item.clone()),
12333 None,
12334 false,
12335 false,
12336 window,
12337 cx,
12338 );
12339 });
12340
12341 // Verify the item is in the pane
12342 pane.read_with(cx, |pane, _| {
12343 assert_eq!(pane.items().count(), 1);
12344 });
12345
12346 // Simulate file deletion by setting the item's deleted state
12347 item.update(cx, |item, _| {
12348 item.set_has_deleted_file(true);
12349 });
12350
12351 // Emit UpdateTab event to trigger the close behavior
12352 cx.run_until_parked();
12353 item.update(cx, |_, cx| {
12354 cx.emit(ItemEvent::UpdateTab);
12355 });
12356
12357 // Allow the close operation to complete
12358 cx.run_until_parked();
12359
12360 // Verify the item was automatically closed
12361 pane.read_with(cx, |pane, _| {
12362 assert_eq!(
12363 pane.items().count(),
12364 0,
12365 "Item should be automatically closed when file is deleted"
12366 );
12367 });
12368 }
12369
12370 /// Tests that when `close_on_file_delete` is disabled (default), files remain
12371 /// open with a strikethrough when they are deleted from disk.
12372 #[gpui::test]
12373 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12374 init_test(cx);
12375
12376 // Ensure close_on_disk_deletion is disabled (default)
12377 cx.update_global(|store: &mut SettingsStore, cx| {
12378 store.update_user_settings(cx, |settings| {
12379 settings.workspace.close_on_file_delete = Some(false);
12380 });
12381 });
12382
12383 let fs = FakeFs::new(cx.background_executor.clone());
12384 let project = Project::test(fs, [], cx).await;
12385 let (workspace, cx) =
12386 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12387 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12388
12389 // Create a test item that simulates a file
12390 let item = cx.new(|cx| {
12391 TestItem::new(cx)
12392 .with_label("test.txt")
12393 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12394 });
12395
12396 // Add item to workspace
12397 workspace.update_in(cx, |workspace, window, cx| {
12398 workspace.add_item(
12399 pane.clone(),
12400 Box::new(item.clone()),
12401 None,
12402 false,
12403 false,
12404 window,
12405 cx,
12406 );
12407 });
12408
12409 // Verify the item is in the pane
12410 pane.read_with(cx, |pane, _| {
12411 assert_eq!(pane.items().count(), 1);
12412 });
12413
12414 // Simulate file deletion
12415 item.update(cx, |item, _| {
12416 item.set_has_deleted_file(true);
12417 });
12418
12419 // Emit UpdateTab event
12420 cx.run_until_parked();
12421 item.update(cx, |_, cx| {
12422 cx.emit(ItemEvent::UpdateTab);
12423 });
12424
12425 // Allow any potential close operation to complete
12426 cx.run_until_parked();
12427
12428 // Verify the item remains open (with strikethrough)
12429 pane.read_with(cx, |pane, _| {
12430 assert_eq!(
12431 pane.items().count(),
12432 1,
12433 "Item should remain open when close_on_disk_deletion is disabled"
12434 );
12435 });
12436
12437 // Verify the item shows as deleted
12438 item.read_with(cx, |item, _| {
12439 assert!(
12440 item.has_deleted_file,
12441 "Item should be marked as having deleted file"
12442 );
12443 });
12444 }
12445
12446 /// Tests that dirty files are not automatically closed when deleted from disk,
12447 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12448 /// unsaved changes without being prompted.
12449 #[gpui::test]
12450 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12451 init_test(cx);
12452
12453 // Enable the close_on_file_delete setting
12454 cx.update_global(|store: &mut SettingsStore, cx| {
12455 store.update_user_settings(cx, |settings| {
12456 settings.workspace.close_on_file_delete = Some(true);
12457 });
12458 });
12459
12460 let fs = FakeFs::new(cx.background_executor.clone());
12461 let project = Project::test(fs, [], cx).await;
12462 let (workspace, cx) =
12463 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12464 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12465
12466 // Create a dirty test item
12467 let item = cx.new(|cx| {
12468 TestItem::new(cx)
12469 .with_dirty(true)
12470 .with_label("test.txt")
12471 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12472 });
12473
12474 // Add item to workspace
12475 workspace.update_in(cx, |workspace, window, cx| {
12476 workspace.add_item(
12477 pane.clone(),
12478 Box::new(item.clone()),
12479 None,
12480 false,
12481 false,
12482 window,
12483 cx,
12484 );
12485 });
12486
12487 // Simulate file deletion
12488 item.update(cx, |item, _| {
12489 item.set_has_deleted_file(true);
12490 });
12491
12492 // Emit UpdateTab event to trigger the close behavior
12493 cx.run_until_parked();
12494 item.update(cx, |_, cx| {
12495 cx.emit(ItemEvent::UpdateTab);
12496 });
12497
12498 // Allow any potential close operation to complete
12499 cx.run_until_parked();
12500
12501 // Verify the item remains open (dirty files are not auto-closed)
12502 pane.read_with(cx, |pane, _| {
12503 assert_eq!(
12504 pane.items().count(),
12505 1,
12506 "Dirty items should not be automatically closed even when file is deleted"
12507 );
12508 });
12509
12510 // Verify the item is marked as deleted and still dirty
12511 item.read_with(cx, |item, _| {
12512 assert!(
12513 item.has_deleted_file,
12514 "Item should be marked as having deleted file"
12515 );
12516 assert!(item.is_dirty, "Item should still be dirty");
12517 });
12518 }
12519
12520 /// Tests that navigation history is cleaned up when files are auto-closed
12521 /// due to deletion from disk.
12522 #[gpui::test]
12523 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12524 init_test(cx);
12525
12526 // Enable the close_on_file_delete setting
12527 cx.update_global(|store: &mut SettingsStore, cx| {
12528 store.update_user_settings(cx, |settings| {
12529 settings.workspace.close_on_file_delete = Some(true);
12530 });
12531 });
12532
12533 let fs = FakeFs::new(cx.background_executor.clone());
12534 let project = Project::test(fs, [], cx).await;
12535 let (workspace, cx) =
12536 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12537 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12538
12539 // Create test items
12540 let item1 = cx.new(|cx| {
12541 TestItem::new(cx)
12542 .with_label("test1.txt")
12543 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12544 });
12545 let item1_id = item1.item_id();
12546
12547 let item2 = cx.new(|cx| {
12548 TestItem::new(cx)
12549 .with_label("test2.txt")
12550 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12551 });
12552
12553 // Add items to workspace
12554 workspace.update_in(cx, |workspace, window, cx| {
12555 workspace.add_item(
12556 pane.clone(),
12557 Box::new(item1.clone()),
12558 None,
12559 false,
12560 false,
12561 window,
12562 cx,
12563 );
12564 workspace.add_item(
12565 pane.clone(),
12566 Box::new(item2.clone()),
12567 None,
12568 false,
12569 false,
12570 window,
12571 cx,
12572 );
12573 });
12574
12575 // Activate item1 to ensure it gets navigation entries
12576 pane.update_in(cx, |pane, window, cx| {
12577 pane.activate_item(0, true, true, window, cx);
12578 });
12579
12580 // Switch to item2 and back to create navigation history
12581 pane.update_in(cx, |pane, window, cx| {
12582 pane.activate_item(1, true, true, window, cx);
12583 });
12584 cx.run_until_parked();
12585
12586 pane.update_in(cx, |pane, window, cx| {
12587 pane.activate_item(0, true, true, window, cx);
12588 });
12589 cx.run_until_parked();
12590
12591 // Simulate file deletion for item1
12592 item1.update(cx, |item, _| {
12593 item.set_has_deleted_file(true);
12594 });
12595
12596 // Emit UpdateTab event to trigger the close behavior
12597 item1.update(cx, |_, cx| {
12598 cx.emit(ItemEvent::UpdateTab);
12599 });
12600 cx.run_until_parked();
12601
12602 // Verify item1 was closed
12603 pane.read_with(cx, |pane, _| {
12604 assert_eq!(
12605 pane.items().count(),
12606 1,
12607 "Should have 1 item remaining after auto-close"
12608 );
12609 });
12610
12611 // Check navigation history after close
12612 let has_item = pane.read_with(cx, |pane, cx| {
12613 let mut has_item = false;
12614 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12615 if entry.item.id() == item1_id {
12616 has_item = true;
12617 }
12618 });
12619 has_item
12620 });
12621
12622 assert!(
12623 !has_item,
12624 "Navigation history should not contain closed item entries"
12625 );
12626 }
12627
12628 #[gpui::test]
12629 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12630 cx: &mut TestAppContext,
12631 ) {
12632 init_test(cx);
12633
12634 let fs = FakeFs::new(cx.background_executor.clone());
12635 let project = Project::test(fs, [], cx).await;
12636 let (workspace, cx) =
12637 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12638 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12639
12640 let dirty_regular_buffer = cx.new(|cx| {
12641 TestItem::new(cx)
12642 .with_dirty(true)
12643 .with_label("1.txt")
12644 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12645 });
12646 let dirty_regular_buffer_2 = cx.new(|cx| {
12647 TestItem::new(cx)
12648 .with_dirty(true)
12649 .with_label("2.txt")
12650 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12651 });
12652 let clear_regular_buffer = cx.new(|cx| {
12653 TestItem::new(cx)
12654 .with_label("3.txt")
12655 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12656 });
12657
12658 let dirty_multi_buffer = cx.new(|cx| {
12659 TestItem::new(cx)
12660 .with_dirty(true)
12661 .with_buffer_kind(ItemBufferKind::Multibuffer)
12662 .with_label("Fake Project Search")
12663 .with_project_items(&[
12664 dirty_regular_buffer.read(cx).project_items[0].clone(),
12665 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12666 clear_regular_buffer.read(cx).project_items[0].clone(),
12667 ])
12668 });
12669 workspace.update_in(cx, |workspace, window, cx| {
12670 workspace.add_item(
12671 pane.clone(),
12672 Box::new(dirty_regular_buffer.clone()),
12673 None,
12674 false,
12675 false,
12676 window,
12677 cx,
12678 );
12679 workspace.add_item(
12680 pane.clone(),
12681 Box::new(dirty_regular_buffer_2.clone()),
12682 None,
12683 false,
12684 false,
12685 window,
12686 cx,
12687 );
12688 workspace.add_item(
12689 pane.clone(),
12690 Box::new(dirty_multi_buffer.clone()),
12691 None,
12692 false,
12693 false,
12694 window,
12695 cx,
12696 );
12697 });
12698
12699 pane.update_in(cx, |pane, window, cx| {
12700 pane.activate_item(2, true, true, window, cx);
12701 assert_eq!(
12702 pane.active_item().unwrap().item_id(),
12703 dirty_multi_buffer.item_id(),
12704 "Should select the multi buffer in the pane"
12705 );
12706 });
12707 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12708 pane.close_active_item(
12709 &CloseActiveItem {
12710 save_intent: None,
12711 close_pinned: false,
12712 },
12713 window,
12714 cx,
12715 )
12716 });
12717 cx.background_executor.run_until_parked();
12718 assert!(
12719 !cx.has_pending_prompt(),
12720 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12721 );
12722 close_multi_buffer_task
12723 .await
12724 .expect("Closing multi buffer failed");
12725 pane.update(cx, |pane, cx| {
12726 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12727 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12728 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12729 assert_eq!(
12730 pane.items()
12731 .map(|item| item.item_id())
12732 .sorted()
12733 .collect::<Vec<_>>(),
12734 vec![
12735 dirty_regular_buffer.item_id(),
12736 dirty_regular_buffer_2.item_id(),
12737 ],
12738 "Should have no multi buffer left in the pane"
12739 );
12740 assert!(dirty_regular_buffer.read(cx).is_dirty);
12741 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12742 });
12743 }
12744
12745 #[gpui::test]
12746 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12747 init_test(cx);
12748 let fs = FakeFs::new(cx.executor());
12749 let project = Project::test(fs, [], cx).await;
12750 let (multi_workspace, cx) =
12751 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12752 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12753
12754 // Add a new panel to the right dock, opening the dock and setting the
12755 // focus to the new panel.
12756 let panel = workspace.update_in(cx, |workspace, window, cx| {
12757 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12758 workspace.add_panel(panel.clone(), window, cx);
12759
12760 workspace
12761 .right_dock()
12762 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12763
12764 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12765
12766 panel
12767 });
12768
12769 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12770 // panel to the next valid position which, in this case, is the left
12771 // dock.
12772 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12773 workspace.update(cx, |workspace, cx| {
12774 assert!(workspace.left_dock().read(cx).is_open());
12775 assert_eq!(panel.read(cx).position, DockPosition::Left);
12776 });
12777
12778 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12779 // panel to the next valid position which, in this case, is the bottom
12780 // dock.
12781 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12782 workspace.update(cx, |workspace, cx| {
12783 assert!(workspace.bottom_dock().read(cx).is_open());
12784 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12785 });
12786
12787 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12788 // around moving the panel to its initial position, the right dock.
12789 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12790 workspace.update(cx, |workspace, cx| {
12791 assert!(workspace.right_dock().read(cx).is_open());
12792 assert_eq!(panel.read(cx).position, DockPosition::Right);
12793 });
12794
12795 // Remove focus from the panel, ensuring that, if the panel is not
12796 // focused, the `MoveFocusedPanelToNextPosition` action does not update
12797 // the panel's position, so the panel is still in the right dock.
12798 workspace.update_in(cx, |workspace, window, cx| {
12799 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12800 });
12801
12802 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12803 workspace.update(cx, |workspace, cx| {
12804 assert!(workspace.right_dock().read(cx).is_open());
12805 assert_eq!(panel.read(cx).position, DockPosition::Right);
12806 });
12807 }
12808
12809 #[gpui::test]
12810 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12811 init_test(cx);
12812
12813 let fs = FakeFs::new(cx.executor());
12814 let project = Project::test(fs, [], cx).await;
12815 let (workspace, cx) =
12816 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12817
12818 let item_1 = cx.new(|cx| {
12819 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12820 });
12821 workspace.update_in(cx, |workspace, window, cx| {
12822 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12823 workspace.move_item_to_pane_in_direction(
12824 &MoveItemToPaneInDirection {
12825 direction: SplitDirection::Right,
12826 focus: true,
12827 clone: false,
12828 },
12829 window,
12830 cx,
12831 );
12832 workspace.move_item_to_pane_at_index(
12833 &MoveItemToPane {
12834 destination: 3,
12835 focus: true,
12836 clone: false,
12837 },
12838 window,
12839 cx,
12840 );
12841
12842 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12843 assert_eq!(
12844 pane_items_paths(&workspace.active_pane, cx),
12845 vec!["first.txt".to_string()],
12846 "Single item was not moved anywhere"
12847 );
12848 });
12849
12850 let item_2 = cx.new(|cx| {
12851 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12852 });
12853 workspace.update_in(cx, |workspace, window, cx| {
12854 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12855 assert_eq!(
12856 pane_items_paths(&workspace.panes[0], cx),
12857 vec!["first.txt".to_string(), "second.txt".to_string()],
12858 );
12859 workspace.move_item_to_pane_in_direction(
12860 &MoveItemToPaneInDirection {
12861 direction: SplitDirection::Right,
12862 focus: true,
12863 clone: false,
12864 },
12865 window,
12866 cx,
12867 );
12868
12869 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12870 assert_eq!(
12871 pane_items_paths(&workspace.panes[0], cx),
12872 vec!["first.txt".to_string()],
12873 "After moving, one item should be left in the original pane"
12874 );
12875 assert_eq!(
12876 pane_items_paths(&workspace.panes[1], cx),
12877 vec!["second.txt".to_string()],
12878 "New item should have been moved to the new pane"
12879 );
12880 });
12881
12882 let item_3 = cx.new(|cx| {
12883 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12884 });
12885 workspace.update_in(cx, |workspace, window, cx| {
12886 let original_pane = workspace.panes[0].clone();
12887 workspace.set_active_pane(&original_pane, window, cx);
12888 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12889 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12890 assert_eq!(
12891 pane_items_paths(&workspace.active_pane, cx),
12892 vec!["first.txt".to_string(), "third.txt".to_string()],
12893 "New pane should be ready to move one item out"
12894 );
12895
12896 workspace.move_item_to_pane_at_index(
12897 &MoveItemToPane {
12898 destination: 3,
12899 focus: true,
12900 clone: false,
12901 },
12902 window,
12903 cx,
12904 );
12905 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12906 assert_eq!(
12907 pane_items_paths(&workspace.active_pane, cx),
12908 vec!["first.txt".to_string()],
12909 "After moving, one item should be left in the original pane"
12910 );
12911 assert_eq!(
12912 pane_items_paths(&workspace.panes[1], cx),
12913 vec!["second.txt".to_string()],
12914 "Previously created pane should be unchanged"
12915 );
12916 assert_eq!(
12917 pane_items_paths(&workspace.panes[2], cx),
12918 vec!["third.txt".to_string()],
12919 "New item should have been moved to the new pane"
12920 );
12921 });
12922 }
12923
12924 #[gpui::test]
12925 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12926 init_test(cx);
12927
12928 let fs = FakeFs::new(cx.executor());
12929 let project = Project::test(fs, [], cx).await;
12930 let (workspace, cx) =
12931 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12932
12933 let item_1 = cx.new(|cx| {
12934 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12935 });
12936 workspace.update_in(cx, |workspace, window, cx| {
12937 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12938 workspace.move_item_to_pane_in_direction(
12939 &MoveItemToPaneInDirection {
12940 direction: SplitDirection::Right,
12941 focus: true,
12942 clone: true,
12943 },
12944 window,
12945 cx,
12946 );
12947 });
12948 cx.run_until_parked();
12949 workspace.update_in(cx, |workspace, window, cx| {
12950 workspace.move_item_to_pane_at_index(
12951 &MoveItemToPane {
12952 destination: 3,
12953 focus: true,
12954 clone: true,
12955 },
12956 window,
12957 cx,
12958 );
12959 });
12960 cx.run_until_parked();
12961
12962 workspace.update(cx, |workspace, cx| {
12963 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
12964 for pane in workspace.panes() {
12965 assert_eq!(
12966 pane_items_paths(pane, cx),
12967 vec!["first.txt".to_string()],
12968 "Single item exists in all panes"
12969 );
12970 }
12971 });
12972
12973 // verify that the active pane has been updated after waiting for the
12974 // pane focus event to fire and resolve
12975 workspace.read_with(cx, |workspace, _app| {
12976 assert_eq!(
12977 workspace.active_pane(),
12978 &workspace.panes[2],
12979 "The third pane should be the active one: {:?}",
12980 workspace.panes
12981 );
12982 })
12983 }
12984
12985 #[gpui::test]
12986 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
12987 init_test(cx);
12988
12989 let fs = FakeFs::new(cx.executor());
12990 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
12991
12992 let project = Project::test(fs, ["root".as_ref()], cx).await;
12993 let (workspace, cx) =
12994 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12995
12996 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12997 // Add item to pane A with project path
12998 let item_a = cx.new(|cx| {
12999 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13000 });
13001 workspace.update_in(cx, |workspace, window, cx| {
13002 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13003 });
13004
13005 // Split to create pane B
13006 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13007 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13008 });
13009
13010 // Add item with SAME project path to pane B, and pin it
13011 let item_b = cx.new(|cx| {
13012 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13013 });
13014 pane_b.update_in(cx, |pane, window, cx| {
13015 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13016 pane.set_pinned_count(1);
13017 });
13018
13019 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13020 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13021
13022 // close_pinned: false should only close the unpinned copy
13023 workspace.update_in(cx, |workspace, window, cx| {
13024 workspace.close_item_in_all_panes(
13025 &CloseItemInAllPanes {
13026 save_intent: Some(SaveIntent::Close),
13027 close_pinned: false,
13028 },
13029 window,
13030 cx,
13031 )
13032 });
13033 cx.executor().run_until_parked();
13034
13035 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13036 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13037 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13038 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13039
13040 // Split again, seeing as closing the previous item also closed its
13041 // pane, so only pane remains, which does not allow us to properly test
13042 // that both items close when `close_pinned: true`.
13043 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13044 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13045 });
13046
13047 // Add an item with the same project path to pane C so that
13048 // close_item_in_all_panes can determine what to close across all panes
13049 // (it reads the active item from the active pane, and split_pane
13050 // creates an empty pane).
13051 let item_c = cx.new(|cx| {
13052 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13053 });
13054 pane_c.update_in(cx, |pane, window, cx| {
13055 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13056 });
13057
13058 // close_pinned: true should close the pinned copy too
13059 workspace.update_in(cx, |workspace, window, cx| {
13060 let panes_count = workspace.panes().len();
13061 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13062
13063 workspace.close_item_in_all_panes(
13064 &CloseItemInAllPanes {
13065 save_intent: Some(SaveIntent::Close),
13066 close_pinned: true,
13067 },
13068 window,
13069 cx,
13070 )
13071 });
13072 cx.executor().run_until_parked();
13073
13074 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13075 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13076 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13077 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13078 }
13079
13080 mod register_project_item_tests {
13081
13082 use super::*;
13083
13084 // View
13085 struct TestPngItemView {
13086 focus_handle: FocusHandle,
13087 }
13088 // Model
13089 struct TestPngItem {}
13090
13091 impl project::ProjectItem for TestPngItem {
13092 fn try_open(
13093 _project: &Entity<Project>,
13094 path: &ProjectPath,
13095 cx: &mut App,
13096 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13097 if path.path.extension().unwrap() == "png" {
13098 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13099 } else {
13100 None
13101 }
13102 }
13103
13104 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13105 None
13106 }
13107
13108 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13109 None
13110 }
13111
13112 fn is_dirty(&self) -> bool {
13113 false
13114 }
13115 }
13116
13117 impl Item for TestPngItemView {
13118 type Event = ();
13119 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13120 "".into()
13121 }
13122 }
13123 impl EventEmitter<()> for TestPngItemView {}
13124 impl Focusable for TestPngItemView {
13125 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13126 self.focus_handle.clone()
13127 }
13128 }
13129
13130 impl Render for TestPngItemView {
13131 fn render(
13132 &mut self,
13133 _window: &mut Window,
13134 _cx: &mut Context<Self>,
13135 ) -> impl IntoElement {
13136 Empty
13137 }
13138 }
13139
13140 impl ProjectItem for TestPngItemView {
13141 type Item = TestPngItem;
13142
13143 fn for_project_item(
13144 _project: Entity<Project>,
13145 _pane: Option<&Pane>,
13146 _item: Entity<Self::Item>,
13147 _: &mut Window,
13148 cx: &mut Context<Self>,
13149 ) -> Self
13150 where
13151 Self: Sized,
13152 {
13153 Self {
13154 focus_handle: cx.focus_handle(),
13155 }
13156 }
13157 }
13158
13159 // View
13160 struct TestIpynbItemView {
13161 focus_handle: FocusHandle,
13162 }
13163 // Model
13164 struct TestIpynbItem {}
13165
13166 impl project::ProjectItem for TestIpynbItem {
13167 fn try_open(
13168 _project: &Entity<Project>,
13169 path: &ProjectPath,
13170 cx: &mut App,
13171 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13172 if path.path.extension().unwrap() == "ipynb" {
13173 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13174 } else {
13175 None
13176 }
13177 }
13178
13179 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13180 None
13181 }
13182
13183 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13184 None
13185 }
13186
13187 fn is_dirty(&self) -> bool {
13188 false
13189 }
13190 }
13191
13192 impl Item for TestIpynbItemView {
13193 type Event = ();
13194 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13195 "".into()
13196 }
13197 }
13198 impl EventEmitter<()> for TestIpynbItemView {}
13199 impl Focusable for TestIpynbItemView {
13200 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13201 self.focus_handle.clone()
13202 }
13203 }
13204
13205 impl Render for TestIpynbItemView {
13206 fn render(
13207 &mut self,
13208 _window: &mut Window,
13209 _cx: &mut Context<Self>,
13210 ) -> impl IntoElement {
13211 Empty
13212 }
13213 }
13214
13215 impl ProjectItem for TestIpynbItemView {
13216 type Item = TestIpynbItem;
13217
13218 fn for_project_item(
13219 _project: Entity<Project>,
13220 _pane: Option<&Pane>,
13221 _item: Entity<Self::Item>,
13222 _: &mut Window,
13223 cx: &mut Context<Self>,
13224 ) -> Self
13225 where
13226 Self: Sized,
13227 {
13228 Self {
13229 focus_handle: cx.focus_handle(),
13230 }
13231 }
13232 }
13233
13234 struct TestAlternatePngItemView {
13235 focus_handle: FocusHandle,
13236 }
13237
13238 impl Item for TestAlternatePngItemView {
13239 type Event = ();
13240 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13241 "".into()
13242 }
13243 }
13244
13245 impl EventEmitter<()> for TestAlternatePngItemView {}
13246 impl Focusable for TestAlternatePngItemView {
13247 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13248 self.focus_handle.clone()
13249 }
13250 }
13251
13252 impl Render for TestAlternatePngItemView {
13253 fn render(
13254 &mut self,
13255 _window: &mut Window,
13256 _cx: &mut Context<Self>,
13257 ) -> impl IntoElement {
13258 Empty
13259 }
13260 }
13261
13262 impl ProjectItem for TestAlternatePngItemView {
13263 type Item = TestPngItem;
13264
13265 fn for_project_item(
13266 _project: Entity<Project>,
13267 _pane: Option<&Pane>,
13268 _item: Entity<Self::Item>,
13269 _: &mut Window,
13270 cx: &mut Context<Self>,
13271 ) -> Self
13272 where
13273 Self: Sized,
13274 {
13275 Self {
13276 focus_handle: cx.focus_handle(),
13277 }
13278 }
13279 }
13280
13281 #[gpui::test]
13282 async fn test_register_project_item(cx: &mut TestAppContext) {
13283 init_test(cx);
13284
13285 cx.update(|cx| {
13286 register_project_item::<TestPngItemView>(cx);
13287 register_project_item::<TestIpynbItemView>(cx);
13288 });
13289
13290 let fs = FakeFs::new(cx.executor());
13291 fs.insert_tree(
13292 "/root1",
13293 json!({
13294 "one.png": "BINARYDATAHERE",
13295 "two.ipynb": "{ totally a notebook }",
13296 "three.txt": "editing text, sure why not?"
13297 }),
13298 )
13299 .await;
13300
13301 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13302 let (workspace, cx) =
13303 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13304
13305 let worktree_id = project.update(cx, |project, cx| {
13306 project.worktrees(cx).next().unwrap().read(cx).id()
13307 });
13308
13309 let handle = workspace
13310 .update_in(cx, |workspace, window, cx| {
13311 let project_path = (worktree_id, rel_path("one.png"));
13312 workspace.open_path(project_path, None, true, window, cx)
13313 })
13314 .await
13315 .unwrap();
13316
13317 // Now we can check if the handle we got back errored or not
13318 assert_eq!(
13319 handle.to_any_view().entity_type(),
13320 TypeId::of::<TestPngItemView>()
13321 );
13322
13323 let handle = workspace
13324 .update_in(cx, |workspace, window, cx| {
13325 let project_path = (worktree_id, rel_path("two.ipynb"));
13326 workspace.open_path(project_path, None, true, window, cx)
13327 })
13328 .await
13329 .unwrap();
13330
13331 assert_eq!(
13332 handle.to_any_view().entity_type(),
13333 TypeId::of::<TestIpynbItemView>()
13334 );
13335
13336 let handle = workspace
13337 .update_in(cx, |workspace, window, cx| {
13338 let project_path = (worktree_id, rel_path("three.txt"));
13339 workspace.open_path(project_path, None, true, window, cx)
13340 })
13341 .await;
13342 assert!(handle.is_err());
13343 }
13344
13345 #[gpui::test]
13346 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
13347 init_test(cx);
13348
13349 cx.update(|cx| {
13350 register_project_item::<TestPngItemView>(cx);
13351 register_project_item::<TestAlternatePngItemView>(cx);
13352 });
13353
13354 let fs = FakeFs::new(cx.executor());
13355 fs.insert_tree(
13356 "/root1",
13357 json!({
13358 "one.png": "BINARYDATAHERE",
13359 "two.ipynb": "{ totally a notebook }",
13360 "three.txt": "editing text, sure why not?"
13361 }),
13362 )
13363 .await;
13364 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13365 let (workspace, cx) =
13366 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13367 let worktree_id = project.update(cx, |project, cx| {
13368 project.worktrees(cx).next().unwrap().read(cx).id()
13369 });
13370
13371 let handle = workspace
13372 .update_in(cx, |workspace, window, cx| {
13373 let project_path = (worktree_id, rel_path("one.png"));
13374 workspace.open_path(project_path, None, true, window, cx)
13375 })
13376 .await
13377 .unwrap();
13378
13379 // This _must_ be the second item registered
13380 assert_eq!(
13381 handle.to_any_view().entity_type(),
13382 TypeId::of::<TestAlternatePngItemView>()
13383 );
13384
13385 let handle = workspace
13386 .update_in(cx, |workspace, window, cx| {
13387 let project_path = (worktree_id, rel_path("three.txt"));
13388 workspace.open_path(project_path, None, true, window, cx)
13389 })
13390 .await;
13391 assert!(handle.is_err());
13392 }
13393 }
13394
13395 #[gpui::test]
13396 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13397 init_test(cx);
13398
13399 let fs = FakeFs::new(cx.executor());
13400 let project = Project::test(fs, [], cx).await;
13401 let (workspace, _cx) =
13402 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13403
13404 // Test with status bar shown (default)
13405 workspace.read_with(cx, |workspace, cx| {
13406 let visible = workspace.status_bar_visible(cx);
13407 assert!(visible, "Status bar should be visible by default");
13408 });
13409
13410 // Test with status bar hidden
13411 cx.update_global(|store: &mut SettingsStore, cx| {
13412 store.update_user_settings(cx, |settings| {
13413 settings.status_bar.get_or_insert_default().show = Some(false);
13414 });
13415 });
13416
13417 workspace.read_with(cx, |workspace, cx| {
13418 let visible = workspace.status_bar_visible(cx);
13419 assert!(!visible, "Status bar should be hidden when show is false");
13420 });
13421
13422 // Test with status bar shown explicitly
13423 cx.update_global(|store: &mut SettingsStore, cx| {
13424 store.update_user_settings(cx, |settings| {
13425 settings.status_bar.get_or_insert_default().show = Some(true);
13426 });
13427 });
13428
13429 workspace.read_with(cx, |workspace, cx| {
13430 let visible = workspace.status_bar_visible(cx);
13431 assert!(visible, "Status bar should be visible when show is true");
13432 });
13433 }
13434
13435 #[gpui::test]
13436 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13437 init_test(cx);
13438
13439 let fs = FakeFs::new(cx.executor());
13440 let project = Project::test(fs, [], cx).await;
13441 let (multi_workspace, cx) =
13442 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13443 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13444 let panel = workspace.update_in(cx, |workspace, window, cx| {
13445 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13446 workspace.add_panel(panel.clone(), window, cx);
13447
13448 workspace
13449 .right_dock()
13450 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13451
13452 panel
13453 });
13454
13455 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13456 let item_a = cx.new(TestItem::new);
13457 let item_b = cx.new(TestItem::new);
13458 let item_a_id = item_a.entity_id();
13459 let item_b_id = item_b.entity_id();
13460
13461 pane.update_in(cx, |pane, window, cx| {
13462 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13463 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13464 });
13465
13466 pane.read_with(cx, |pane, _| {
13467 assert_eq!(pane.items_len(), 2);
13468 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13469 });
13470
13471 workspace.update_in(cx, |workspace, window, cx| {
13472 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13473 });
13474
13475 workspace.update_in(cx, |_, window, cx| {
13476 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13477 });
13478
13479 // Assert that the `pane::CloseActiveItem` action is handled at the
13480 // workspace level when one of the dock panels is focused and, in that
13481 // case, the center pane's active item is closed but the focus is not
13482 // moved.
13483 cx.dispatch_action(pane::CloseActiveItem::default());
13484 cx.run_until_parked();
13485
13486 pane.read_with(cx, |pane, _| {
13487 assert_eq!(pane.items_len(), 1);
13488 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13489 });
13490
13491 workspace.update_in(cx, |workspace, window, cx| {
13492 assert!(workspace.right_dock().read(cx).is_open());
13493 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13494 });
13495 }
13496
13497 #[gpui::test]
13498 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13499 init_test(cx);
13500 let fs = FakeFs::new(cx.executor());
13501
13502 let project_a = Project::test(fs.clone(), [], cx).await;
13503 let project_b = Project::test(fs, [], cx).await;
13504
13505 let multi_workspace_handle =
13506 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13507 cx.run_until_parked();
13508
13509 let workspace_a = multi_workspace_handle
13510 .read_with(cx, |mw, _| mw.workspace().clone())
13511 .unwrap();
13512
13513 let _workspace_b = multi_workspace_handle
13514 .update(cx, |mw, window, cx| {
13515 mw.test_add_workspace(project_b, window, cx)
13516 })
13517 .unwrap();
13518
13519 // Switch to workspace A
13520 multi_workspace_handle
13521 .update(cx, |mw, window, cx| {
13522 mw.activate_index(0, window, cx);
13523 })
13524 .unwrap();
13525
13526 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13527
13528 // Add a panel to workspace A's right dock and open the dock
13529 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13530 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13531 workspace.add_panel(panel.clone(), window, cx);
13532 workspace
13533 .right_dock()
13534 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13535 panel
13536 });
13537
13538 // Focus the panel through the workspace (matching existing test pattern)
13539 workspace_a.update_in(cx, |workspace, window, cx| {
13540 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13541 });
13542
13543 // Zoom the panel
13544 panel.update_in(cx, |panel, window, cx| {
13545 panel.set_zoomed(true, window, cx);
13546 });
13547
13548 // Verify the panel is zoomed and the dock is open
13549 workspace_a.update_in(cx, |workspace, window, cx| {
13550 assert!(
13551 workspace.right_dock().read(cx).is_open(),
13552 "dock should be open before switch"
13553 );
13554 assert!(
13555 panel.is_zoomed(window, cx),
13556 "panel should be zoomed before switch"
13557 );
13558 assert!(
13559 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13560 "panel should be focused before switch"
13561 );
13562 });
13563
13564 // Switch to workspace B
13565 multi_workspace_handle
13566 .update(cx, |mw, window, cx| {
13567 mw.activate_index(1, window, cx);
13568 })
13569 .unwrap();
13570 cx.run_until_parked();
13571
13572 // Switch back to workspace A
13573 multi_workspace_handle
13574 .update(cx, |mw, window, cx| {
13575 mw.activate_index(0, window, cx);
13576 })
13577 .unwrap();
13578 cx.run_until_parked();
13579
13580 // Verify the panel is still zoomed and the dock is still open
13581 workspace_a.update_in(cx, |workspace, window, cx| {
13582 assert!(
13583 workspace.right_dock().read(cx).is_open(),
13584 "dock should still be open after switching back"
13585 );
13586 assert!(
13587 panel.is_zoomed(window, cx),
13588 "panel should still be zoomed after switching back"
13589 );
13590 });
13591 }
13592
13593 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13594 pane.read(cx)
13595 .items()
13596 .flat_map(|item| {
13597 item.project_paths(cx)
13598 .into_iter()
13599 .map(|path| path.path.display(PathStyle::local()).into_owned())
13600 })
13601 .collect()
13602 }
13603
13604 pub fn init_test(cx: &mut TestAppContext) {
13605 cx.update(|cx| {
13606 let settings_store = SettingsStore::test(cx);
13607 cx.set_global(settings_store);
13608 theme::init(theme::LoadThemes::JustBase, cx);
13609 });
13610 }
13611
13612 #[gpui::test]
13613 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
13614 use settings::{ThemeName, ThemeSelection};
13615 use theme::SystemAppearance;
13616 use zed_actions::theme::ToggleMode;
13617
13618 init_test(cx);
13619
13620 let fs = FakeFs::new(cx.executor());
13621 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
13622
13623 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
13624 .await;
13625
13626 // Build a test project and workspace view so the test can invoke
13627 // the workspace action handler the same way the UI would.
13628 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
13629 let (workspace, cx) =
13630 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13631
13632 // Seed the settings file with a plain static light theme so the
13633 // first toggle always starts from a known persisted state.
13634 workspace.update_in(cx, |_workspace, _window, cx| {
13635 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
13636 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
13637 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
13638 });
13639 });
13640 cx.executor().advance_clock(Duration::from_millis(200));
13641 cx.run_until_parked();
13642
13643 // Confirm the initial persisted settings contain the static theme
13644 // we just wrote before any toggling happens.
13645 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13646 assert!(settings_text.contains(r#""theme": "One Light""#));
13647
13648 // Toggle once. This should migrate the persisted theme settings
13649 // into light/dark slots and enable system mode.
13650 workspace.update_in(cx, |workspace, window, cx| {
13651 workspace.toggle_theme_mode(&ToggleMode, window, cx);
13652 });
13653 cx.executor().advance_clock(Duration::from_millis(200));
13654 cx.run_until_parked();
13655
13656 // 1. Static -> Dynamic
13657 // this assertion checks theme changed from static to dynamic.
13658 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13659 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
13660 assert_eq!(
13661 parsed["theme"],
13662 serde_json::json!({
13663 "mode": "system",
13664 "light": "One Light",
13665 "dark": "One Dark"
13666 })
13667 );
13668
13669 // 2. Toggle again, suppose it will change the mode to light
13670 workspace.update_in(cx, |workspace, window, cx| {
13671 workspace.toggle_theme_mode(&ToggleMode, window, cx);
13672 });
13673 cx.executor().advance_clock(Duration::from_millis(200));
13674 cx.run_until_parked();
13675
13676 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13677 assert!(settings_text.contains(r#""mode": "light""#));
13678 }
13679
13680 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13681 let item = TestProjectItem::new(id, path, cx);
13682 item.update(cx, |item, _| {
13683 item.is_dirty = true;
13684 });
13685 item
13686 }
13687
13688 #[gpui::test]
13689 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13690 cx: &mut gpui::TestAppContext,
13691 ) {
13692 init_test(cx);
13693 let fs = FakeFs::new(cx.executor());
13694
13695 let project = Project::test(fs, [], cx).await;
13696 let (workspace, cx) =
13697 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13698
13699 let panel = workspace.update_in(cx, |workspace, window, cx| {
13700 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13701 workspace.add_panel(panel.clone(), window, cx);
13702 workspace
13703 .right_dock()
13704 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13705 panel
13706 });
13707
13708 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13709 pane.update_in(cx, |pane, window, cx| {
13710 let item = cx.new(TestItem::new);
13711 pane.add_item(Box::new(item), true, true, None, window, cx);
13712 });
13713
13714 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13715 // mirrors the real-world flow and avoids side effects from directly
13716 // focusing the panel while the center pane is active.
13717 workspace.update_in(cx, |workspace, window, cx| {
13718 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13719 });
13720
13721 panel.update_in(cx, |panel, window, cx| {
13722 panel.set_zoomed(true, window, cx);
13723 });
13724
13725 workspace.update_in(cx, |workspace, window, cx| {
13726 assert!(workspace.right_dock().read(cx).is_open());
13727 assert!(panel.is_zoomed(window, cx));
13728 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13729 });
13730
13731 // Simulate a spurious pane::Event::Focus on the center pane while the
13732 // panel still has focus. This mirrors what happens during macOS window
13733 // activation: the center pane fires a focus event even though actual
13734 // focus remains on the dock panel.
13735 pane.update_in(cx, |_, _, cx| {
13736 cx.emit(pane::Event::Focus);
13737 });
13738
13739 // The dock must remain open because the panel had focus at the time the
13740 // event was processed. Before the fix, dock_to_preserve was None for
13741 // panels that don't implement pane(), causing the dock to close.
13742 workspace.update_in(cx, |workspace, window, cx| {
13743 assert!(
13744 workspace.right_dock().read(cx).is_open(),
13745 "Dock should stay open when its zoomed panel (without pane()) still has focus"
13746 );
13747 assert!(panel.is_zoomed(window, cx));
13748 });
13749 }
13750}