1pub mod active_file_name;
2pub mod dock;
3pub mod history_manager;
4pub mod invalid_item_view;
5pub mod item;
6mod modal_layer;
7mod multi_workspace;
8#[cfg(test)]
9mod multi_workspace_tests;
10pub mod notifications;
11pub mod pane;
12pub mod pane_group;
13pub mod path_list {
14 pub use util::path_list::{PathList, SerializedPathList};
15}
16mod persistence;
17pub mod searchable;
18mod security_modal;
19pub mod shared_screen;
20use db::smol::future::yield_now;
21pub use shared_screen::SharedScreen;
22pub mod focus_follows_mouse;
23mod status_bar;
24pub mod tasks;
25mod theme_preview;
26mod toast_layer;
27mod toolbar;
28pub mod welcome;
29mod workspace_settings;
30
31pub use crate::notifications::NotificationFrame;
32pub use dock::Panel;
33pub use multi_workspace::{
34 CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MoveProjectToNewWindow,
35 MultiWorkspace, MultiWorkspaceEvent, NewThread, NextProject, NextThread, PreviousProject,
36 PreviousThread, ProjectGroup, ProjectGroupKey, SerializedProjectGroupState, Sidebar,
37 SidebarEvent, SidebarHandle, SidebarRenderState, SidebarSide, ToggleWorkspaceSidebar,
38 sidebar_side_context_menu,
39};
40pub use path_list::{PathList, SerializedPathList};
41pub use remote::{
42 RemoteConnectionIdentity, remote_connection_identity, same_remote_connection_identity,
43};
44pub use toast_layer::{ToastAction, ToastLayer, ToastView};
45
46use anyhow::{Context as _, Result, anyhow};
47use client::{
48 ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
49 proto::{self, ErrorCode, PanelId, PeerId},
50};
51use collections::{HashMap, HashSet, hash_map};
52use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
53use fs::Fs;
54use futures::{
55 Future, FutureExt, StreamExt,
56 channel::{
57 mpsc::{self, UnboundedReceiver, UnboundedSender},
58 oneshot,
59 },
60 future::{Shared, try_join_all},
61};
62use gpui::{
63 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
64 Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
65 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
66 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
67 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
68 WindowOptions, actions, canvas, point, relative, size, transparent_black,
69};
70pub use history_manager::*;
71pub use item::{
72 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
73 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
74};
75use itertools::Itertools;
76use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
77pub use modal_layer::*;
78use node_runtime::NodeRuntime;
79use notifications::{
80 DetachAndPromptErr, Notifications, dismiss_app_notification,
81 simple_message_notification::MessageNotification,
82};
83pub use pane::*;
84pub use pane_group::{
85 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
86 SplitDirection,
87};
88use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
89pub use persistence::{
90 WorkspaceDb, delete_unloaded_items,
91 model::{
92 DockData, DockStructure, ItemId, MultiWorkspaceState, SerializedMultiWorkspace,
93 SerializedProjectGroup, SerializedWorkspaceLocation, SessionWorkspace,
94 },
95 read_serialized_multi_workspaces, resolve_worktree_workspaces,
96};
97use postage::stream::Stream;
98use project::{
99 DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
100 WorktreeSettings,
101 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
102 project_settings::ProjectSettings,
103 toolchain_store::ToolchainStoreEvent,
104 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
105};
106use remote::{
107 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
108 remote_client::ConnectionIdentifier,
109};
110use schemars::JsonSchema;
111use serde::Deserialize;
112use session::AppSession;
113use settings::{
114 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
115};
116
117use sqlez::{
118 bindable::{Bind, Column, StaticColumnCount},
119 statement::Statement,
120};
121use status_bar::StatusBar;
122pub use status_bar::StatusItemView;
123use std::{
124 any::TypeId,
125 borrow::Cow,
126 cell::RefCell,
127 cmp,
128 collections::VecDeque,
129 env,
130 hash::Hash,
131 path::{Path, PathBuf},
132 process::ExitStatus,
133 rc::Rc,
134 sync::{
135 Arc, LazyLock,
136 atomic::{AtomicBool, AtomicUsize},
137 },
138 time::Duration,
139};
140use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
141use theme::{ActiveTheme, SystemAppearance};
142use theme_settings::ThemeSettings;
143pub use toolbar::{
144 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
145};
146pub use ui;
147use ui::{Window, prelude::*};
148use util::{
149 ResultExt, TryFutureExt,
150 paths::{PathStyle, SanitizedPath},
151 rel_path::RelPath,
152 serde::default_true,
153};
154use uuid::Uuid;
155pub use workspace_settings::{
156 AutosaveSetting, BottomDockLayout, FocusFollowsMouse, RestoreOnStartupBehavior,
157 StatusBarSettings, TabBarSettings, WorkspaceSettings,
158};
159use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
160
161use crate::{dock::PanelSizeState, item::ItemBufferKind, notifications::NotificationId};
162use crate::{
163 persistence::{
164 SerializedAxis,
165 model::{SerializedItem, SerializedPane, SerializedPaneGroup},
166 },
167 security_modal::SecurityModal,
168};
169
170pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
171
172static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
173 env::var("ZED_WINDOW_SIZE")
174 .ok()
175 .as_deref()
176 .and_then(parse_pixel_size_env_var)
177});
178
179static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
180 env::var("ZED_WINDOW_POSITION")
181 .ok()
182 .as_deref()
183 .and_then(parse_pixel_position_env_var)
184});
185
186pub trait TerminalProvider {
187 fn spawn(
188 &self,
189 task: SpawnInTerminal,
190 window: &mut Window,
191 cx: &mut App,
192 ) -> Task<Option<Result<ExitStatus>>>;
193}
194
195pub trait DebuggerProvider {
196 // `active_buffer` is used to resolve build task's name against language-specific tasks.
197 fn start_session(
198 &self,
199 definition: DebugScenario,
200 task_context: SharedTaskContext,
201 active_buffer: Option<Entity<Buffer>>,
202 worktree_id: Option<WorktreeId>,
203 window: &mut Window,
204 cx: &mut App,
205 );
206
207 fn spawn_task_or_modal(
208 &self,
209 workspace: &mut Workspace,
210 action: &Spawn,
211 window: &mut Window,
212 cx: &mut Context<Workspace>,
213 );
214
215 fn task_scheduled(&self, cx: &mut App);
216 fn debug_scenario_scheduled(&self, cx: &mut App);
217 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
218
219 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
220}
221
222/// Opens a file or directory.
223#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
224#[action(namespace = workspace)]
225pub struct Open {
226 /// When true, opens in a new window. When false, adds to the current
227 /// window as a new workspace (multi-workspace).
228 #[serde(default = "Open::default_create_new_window")]
229 pub create_new_window: bool,
230}
231
232impl Open {
233 pub const DEFAULT: Self = Self {
234 create_new_window: false,
235 };
236
237 /// Used by `#[serde(default)]` on the `create_new_window` field so that
238 /// the serde default and `Open::DEFAULT` stay in sync.
239 fn default_create_new_window() -> bool {
240 Self::DEFAULT.create_new_window
241 }
242}
243
244impl Default for Open {
245 fn default() -> Self {
246 Self::DEFAULT
247 }
248}
249
250actions!(
251 workspace,
252 [
253 /// Activates the next pane in the workspace.
254 ActivateNextPane,
255 /// Activates the previous pane in the workspace.
256 ActivatePreviousPane,
257 /// Activates the last pane in the workspace.
258 ActivateLastPane,
259 /// Switches to the next window.
260 ActivateNextWindow,
261 /// Switches to the previous window.
262 ActivatePreviousWindow,
263 /// Adds a folder to the current project.
264 AddFolderToProject,
265 /// Clears all notifications.
266 ClearAllNotifications,
267 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
268 ClearNavigationHistory,
269 /// Closes the active dock.
270 CloseActiveDock,
271 /// Closes all docks.
272 CloseAllDocks,
273 /// Toggles all docks.
274 ToggleAllDocks,
275 /// Closes the current window.
276 CloseWindow,
277 /// Closes the current project.
278 CloseProject,
279 /// Opens the feedback dialog.
280 Feedback,
281 /// Follows the next collaborator in the session.
282 FollowNextCollaborator,
283 /// Moves the focused panel to the next position.
284 MoveFocusedPanelToNextPosition,
285 /// Creates a new file.
286 NewFile,
287 /// Creates a new file in a vertical split.
288 NewFileSplitVertical,
289 /// Creates a new file in a horizontal split.
290 NewFileSplitHorizontal,
291 /// Opens a new search.
292 NewSearch,
293 /// Opens a new window.
294 NewWindow,
295 /// Opens multiple files.
296 OpenFiles,
297 /// Opens the current location in terminal.
298 OpenInTerminal,
299 /// Opens the component preview.
300 OpenComponentPreview,
301 /// Reloads the active item.
302 ReloadActiveItem,
303 /// Resets the active dock to its default size.
304 ResetActiveDockSize,
305 /// Resets all open docks to their default sizes.
306 ResetOpenDocksSize,
307 /// Reloads the application
308 Reload,
309 /// Formats and saves the current file, regardless of the format_on_save setting.
310 FormatAndSave,
311 /// Saves the current file with a new name.
312 SaveAs,
313 /// Saves without formatting.
314 SaveWithoutFormat,
315 /// Shuts down all debug adapters.
316 ShutdownDebugAdapters,
317 /// Suppresses the current notification.
318 SuppressNotification,
319 /// Toggles the bottom dock.
320 ToggleBottomDock,
321 /// Toggles centered layout mode.
322 ToggleCenteredLayout,
323 /// Toggles edit prediction feature globally for all files.
324 ToggleEditPrediction,
325 /// Toggles the left dock.
326 ToggleLeftDock,
327 /// Toggles the right dock.
328 ToggleRightDock,
329 /// Toggles zoom on the active pane.
330 ToggleZoom,
331 /// Toggles read-only mode for the active item (if supported by that item).
332 ToggleReadOnlyFile,
333 /// Zooms in on the active pane.
334 ZoomIn,
335 /// Zooms out of the active pane.
336 ZoomOut,
337 /// If any worktrees are in restricted mode, shows a modal with possible actions.
338 /// If the modal is shown already, closes it without trusting any worktree.
339 ToggleWorktreeSecurity,
340 /// Clears all trusted worktrees, placing them in restricted mode on next open.
341 /// Requires restart to take effect on already opened projects.
342 ClearTrustedWorktrees,
343 /// Stops following a collaborator.
344 Unfollow,
345 /// Restores the banner.
346 RestoreBanner,
347 /// Toggles expansion of the selected item.
348 ToggleExpandItem,
349 ]
350);
351
352/// Activates a specific pane by its index.
353#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
354#[action(namespace = workspace)]
355pub struct ActivatePane(pub usize);
356
357/// Moves an item to a specific pane by index.
358#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
359#[action(namespace = workspace)]
360#[serde(deny_unknown_fields)]
361pub struct MoveItemToPane {
362 #[serde(default = "default_1")]
363 pub destination: usize,
364 #[serde(default = "default_true")]
365 pub focus: bool,
366 #[serde(default)]
367 pub clone: bool,
368}
369
370fn default_1() -> usize {
371 1
372}
373
374/// Moves an item to a pane in the specified direction.
375#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
376#[action(namespace = workspace)]
377#[serde(deny_unknown_fields)]
378pub struct MoveItemToPaneInDirection {
379 #[serde(default = "default_right")]
380 pub direction: SplitDirection,
381 #[serde(default = "default_true")]
382 pub focus: bool,
383 #[serde(default)]
384 pub clone: bool,
385}
386
387/// Creates a new file in a split of the desired direction.
388#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
389#[action(namespace = workspace)]
390#[serde(deny_unknown_fields)]
391pub struct NewFileSplit(pub SplitDirection);
392
393fn default_right() -> SplitDirection {
394 SplitDirection::Right
395}
396
397/// Saves all open files in the workspace.
398#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
399#[action(namespace = workspace)]
400#[serde(deny_unknown_fields)]
401pub struct SaveAll {
402 #[serde(default)]
403 pub save_intent: Option<SaveIntent>,
404}
405
406/// Saves the current file with the specified options.
407#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
408#[action(namespace = workspace)]
409#[serde(deny_unknown_fields)]
410pub struct Save {
411 #[serde(default)]
412 pub save_intent: Option<SaveIntent>,
413}
414
415/// Moves Focus to the central panes in the workspace.
416#[derive(Clone, Debug, PartialEq, Eq, Action)]
417#[action(namespace = workspace)]
418pub struct FocusCenterPane;
419
420/// Closes all items and panes in the workspace.
421#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
422#[action(namespace = workspace)]
423#[serde(deny_unknown_fields)]
424pub struct CloseAllItemsAndPanes {
425 #[serde(default)]
426 pub save_intent: Option<SaveIntent>,
427}
428
429/// Closes all inactive tabs and panes in the workspace.
430#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
431#[action(namespace = workspace)]
432#[serde(deny_unknown_fields)]
433pub struct CloseInactiveTabsAndPanes {
434 #[serde(default)]
435 pub save_intent: Option<SaveIntent>,
436}
437
438/// Closes the active item across all panes.
439#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
440#[action(namespace = workspace)]
441#[serde(deny_unknown_fields)]
442pub struct CloseItemInAllPanes {
443 #[serde(default)]
444 pub save_intent: Option<SaveIntent>,
445 #[serde(default)]
446 pub close_pinned: bool,
447}
448
449/// Sends a sequence of keystrokes to the active element.
450#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
451#[action(namespace = workspace)]
452pub struct SendKeystrokes(pub String);
453
454actions!(
455 project_symbols,
456 [
457 /// Toggles the project symbols search.
458 #[action(name = "Toggle")]
459 ToggleProjectSymbols
460 ]
461);
462
463/// Toggles the file finder interface.
464#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
465#[action(namespace = file_finder, name = "Toggle")]
466#[serde(deny_unknown_fields)]
467pub struct ToggleFileFinder {
468 #[serde(default)]
469 pub separate_history: bool,
470}
471
472/// Opens a new terminal in the center.
473#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
474#[action(namespace = workspace)]
475#[serde(deny_unknown_fields)]
476pub struct NewCenterTerminal {
477 /// If true, creates a local terminal even in remote projects.
478 #[serde(default)]
479 pub local: bool,
480}
481
482/// Opens a new terminal.
483#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
484#[action(namespace = workspace)]
485#[serde(deny_unknown_fields)]
486pub struct NewTerminal {
487 /// If true, creates a local terminal even in remote projects.
488 #[serde(default)]
489 pub local: bool,
490}
491
492/// Increases size of a currently focused dock by a given amount of pixels.
493#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
494#[action(namespace = workspace)]
495#[serde(deny_unknown_fields)]
496pub struct IncreaseActiveDockSize {
497 /// For 0px parameter, uses UI font size value.
498 #[serde(default)]
499 pub px: u32,
500}
501
502/// Decreases size of a currently focused dock by a given amount of pixels.
503#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
504#[action(namespace = workspace)]
505#[serde(deny_unknown_fields)]
506pub struct DecreaseActiveDockSize {
507 /// For 0px parameter, uses UI font size value.
508 #[serde(default)]
509 pub px: u32,
510}
511
512/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
513#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
514#[action(namespace = workspace)]
515#[serde(deny_unknown_fields)]
516pub struct IncreaseOpenDocksSize {
517 /// For 0px parameter, uses UI font size value.
518 #[serde(default)]
519 pub px: u32,
520}
521
522/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
523#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
524#[action(namespace = workspace)]
525#[serde(deny_unknown_fields)]
526pub struct DecreaseOpenDocksSize {
527 /// For 0px parameter, uses UI font size value.
528 #[serde(default)]
529 pub px: u32,
530}
531
532actions!(
533 workspace,
534 [
535 /// Activates the pane to the left.
536 ActivatePaneLeft,
537 /// Activates the pane to the right.
538 ActivatePaneRight,
539 /// Activates the pane above.
540 ActivatePaneUp,
541 /// Activates the pane below.
542 ActivatePaneDown,
543 /// Swaps the current pane with the one to the left.
544 SwapPaneLeft,
545 /// Swaps the current pane with the one to the right.
546 SwapPaneRight,
547 /// Swaps the current pane with the one above.
548 SwapPaneUp,
549 /// Swaps the current pane with the one below.
550 SwapPaneDown,
551 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
552 SwapPaneAdjacent,
553 /// Move the current pane to be at the far left.
554 MovePaneLeft,
555 /// Move the current pane to be at the far right.
556 MovePaneRight,
557 /// Move the current pane to be at the very top.
558 MovePaneUp,
559 /// Move the current pane to be at the very bottom.
560 MovePaneDown,
561 ]
562);
563
564#[derive(PartialEq, Eq, Debug)]
565pub enum CloseIntent {
566 /// Quit the program entirely.
567 Quit,
568 /// Close a window.
569 CloseWindow,
570 /// Replace the workspace in an existing window.
571 ReplaceWindow,
572}
573
574#[derive(Clone)]
575pub struct Toast {
576 id: NotificationId,
577 msg: Cow<'static, str>,
578 autohide: bool,
579 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
580}
581
582impl Toast {
583 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
584 Toast {
585 id,
586 msg: msg.into(),
587 on_click: None,
588 autohide: false,
589 }
590 }
591
592 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
593 where
594 M: Into<Cow<'static, str>>,
595 F: Fn(&mut Window, &mut App) + 'static,
596 {
597 self.on_click = Some((message.into(), Arc::new(on_click)));
598 self
599 }
600
601 pub fn autohide(mut self) -> Self {
602 self.autohide = true;
603 self
604 }
605}
606
607impl PartialEq for Toast {
608 fn eq(&self, other: &Self) -> bool {
609 self.id == other.id
610 && self.msg == other.msg
611 && self.on_click.is_some() == other.on_click.is_some()
612 }
613}
614
615/// Opens a new terminal with the specified working directory.
616#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
617#[action(namespace = workspace)]
618#[serde(deny_unknown_fields)]
619pub struct OpenTerminal {
620 pub working_directory: PathBuf,
621 /// If true, creates a local terminal even in remote projects.
622 #[serde(default)]
623 pub local: bool,
624}
625
626#[derive(
627 Clone,
628 Copy,
629 Debug,
630 Default,
631 Hash,
632 PartialEq,
633 Eq,
634 PartialOrd,
635 Ord,
636 serde::Serialize,
637 serde::Deserialize,
638)]
639pub struct WorkspaceId(i64);
640
641impl WorkspaceId {
642 pub fn from_i64(value: i64) -> Self {
643 Self(value)
644 }
645}
646
647impl StaticColumnCount for WorkspaceId {}
648impl Bind for WorkspaceId {
649 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
650 self.0.bind(statement, start_index)
651 }
652}
653impl Column for WorkspaceId {
654 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
655 i64::column(statement, start_index)
656 .map(|(i, next_index)| (Self(i), next_index))
657 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
658 }
659}
660impl From<WorkspaceId> for i64 {
661 fn from(val: WorkspaceId) -> Self {
662 val.0
663 }
664}
665
666fn prompt_and_open_paths(
667 app_state: Arc<AppState>,
668 options: PathPromptOptions,
669 create_new_window: bool,
670 cx: &mut App,
671) {
672 if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
673 workspace_window
674 .update(cx, |multi_workspace, window, cx| {
675 let workspace = multi_workspace.workspace().clone();
676 workspace.update(cx, |workspace, cx| {
677 prompt_for_open_path_and_open(
678 workspace,
679 app_state,
680 options,
681 create_new_window,
682 window,
683 cx,
684 );
685 });
686 })
687 .ok();
688 } else {
689 let task = Workspace::new_local(
690 Vec::new(),
691 app_state.clone(),
692 None,
693 None,
694 None,
695 OpenMode::Activate,
696 cx,
697 );
698 cx.spawn(async move |cx| {
699 let OpenResult { window, .. } = task.await?;
700 window.update(cx, |multi_workspace, window, cx| {
701 window.activate_window();
702 let workspace = multi_workspace.workspace().clone();
703 workspace.update(cx, |workspace, cx| {
704 prompt_for_open_path_and_open(
705 workspace,
706 app_state,
707 options,
708 create_new_window,
709 window,
710 cx,
711 );
712 });
713 })?;
714 anyhow::Ok(())
715 })
716 .detach_and_log_err(cx);
717 }
718}
719
720pub fn prompt_for_open_path_and_open(
721 workspace: &mut Workspace,
722 app_state: Arc<AppState>,
723 options: PathPromptOptions,
724 create_new_window: bool,
725 window: &mut Window,
726 cx: &mut Context<Workspace>,
727) {
728 let paths = workspace.prompt_for_open_path(
729 options,
730 DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
731 window,
732 cx,
733 );
734 let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
735 cx.spawn_in(window, async move |this, cx| {
736 let Some(paths) = paths.await.log_err().flatten() else {
737 return;
738 };
739 if !create_new_window {
740 if let Some(handle) = multi_workspace_handle {
741 if let Some(task) = handle
742 .update(cx, |multi_workspace, window, cx| {
743 multi_workspace.open_project(paths, OpenMode::Activate, window, cx)
744 })
745 .log_err()
746 {
747 task.await.log_err();
748 }
749 return;
750 }
751 }
752 if let Some(task) = this
753 .update_in(cx, |this, window, cx| {
754 this.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx)
755 })
756 .log_err()
757 {
758 task.await.log_err();
759 }
760 })
761 .detach();
762}
763
764pub fn init(app_state: Arc<AppState>, cx: &mut App) {
765 component::init();
766 theme_preview::init(cx);
767 toast_layer::init(cx);
768 history_manager::init(app_state.fs.clone(), cx);
769
770 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
771 .on_action(|_: &Reload, cx| reload(cx))
772 .on_action(|action: &Open, cx: &mut App| {
773 let app_state = AppState::global(cx);
774 prompt_and_open_paths(
775 app_state,
776 PathPromptOptions {
777 files: true,
778 directories: true,
779 multiple: true,
780 prompt: None,
781 },
782 action.create_new_window,
783 cx,
784 );
785 })
786 .on_action(|_: &OpenFiles, cx: &mut App| {
787 let directories = cx.can_select_mixed_files_and_dirs();
788 let app_state = AppState::global(cx);
789 prompt_and_open_paths(
790 app_state,
791 PathPromptOptions {
792 files: true,
793 directories,
794 multiple: true,
795 prompt: None,
796 },
797 true,
798 cx,
799 );
800 });
801}
802
803type BuildProjectItemFn =
804 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
805
806type BuildProjectItemForPathFn =
807 fn(
808 &Entity<Project>,
809 &ProjectPath,
810 &mut Window,
811 &mut App,
812 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
813
814#[derive(Clone, Default)]
815struct ProjectItemRegistry {
816 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
817 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
818}
819
820impl ProjectItemRegistry {
821 fn register<T: ProjectItem>(&mut self) {
822 self.build_project_item_fns_by_type.insert(
823 TypeId::of::<T::Item>(),
824 |item, project, pane, window, cx| {
825 let item = item.downcast().unwrap();
826 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
827 as Box<dyn ItemHandle>
828 },
829 );
830 self.build_project_item_for_path_fns
831 .push(|project, project_path, window, cx| {
832 let project_path = project_path.clone();
833 let is_file = project
834 .read(cx)
835 .entry_for_path(&project_path, cx)
836 .is_some_and(|entry| entry.is_file());
837 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
838 let is_local = project.read(cx).is_local();
839 let project_item =
840 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
841 let project = project.clone();
842 Some(window.spawn(cx, async move |cx| {
843 match project_item.await.with_context(|| {
844 format!(
845 "opening project path {:?}",
846 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
847 )
848 }) {
849 Ok(project_item) => {
850 let project_item = project_item;
851 let project_entry_id: Option<ProjectEntryId> =
852 project_item.read_with(cx, project::ProjectItem::entry_id);
853 let build_workspace_item = Box::new(
854 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
855 Box::new(cx.new(|cx| {
856 T::for_project_item(
857 project,
858 Some(pane),
859 project_item,
860 window,
861 cx,
862 )
863 })) as Box<dyn ItemHandle>
864 },
865 ) as Box<_>;
866 Ok((project_entry_id, build_workspace_item))
867 }
868 Err(e) => {
869 log::warn!("Failed to open a project item: {e:#}");
870 if e.error_code() == ErrorCode::Internal {
871 if let Some(abs_path) =
872 entry_abs_path.as_deref().filter(|_| is_file)
873 {
874 if let Some(broken_project_item_view) =
875 cx.update(|window, cx| {
876 T::for_broken_project_item(
877 abs_path, is_local, &e, window, cx,
878 )
879 })?
880 {
881 let build_workspace_item = Box::new(
882 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
883 cx.new(|_| broken_project_item_view).boxed_clone()
884 },
885 )
886 as Box<_>;
887 return Ok((None, build_workspace_item));
888 }
889 }
890 }
891 Err(e)
892 }
893 }
894 }))
895 });
896 }
897
898 fn open_path(
899 &self,
900 project: &Entity<Project>,
901 path: &ProjectPath,
902 window: &mut Window,
903 cx: &mut App,
904 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
905 let Some(open_project_item) = self
906 .build_project_item_for_path_fns
907 .iter()
908 .rev()
909 .find_map(|open_project_item| open_project_item(project, path, window, cx))
910 else {
911 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
912 };
913 open_project_item
914 }
915
916 fn build_item<T: project::ProjectItem>(
917 &self,
918 item: Entity<T>,
919 project: Entity<Project>,
920 pane: Option<&Pane>,
921 window: &mut Window,
922 cx: &mut App,
923 ) -> Option<Box<dyn ItemHandle>> {
924 let build = self
925 .build_project_item_fns_by_type
926 .get(&TypeId::of::<T>())?;
927 Some(build(item.into_any(), project, pane, window, cx))
928 }
929}
930
931type WorkspaceItemBuilder =
932 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
933
934impl Global for ProjectItemRegistry {}
935
936/// Registers a [ProjectItem] for the app. When opening a file, all the registered
937/// items will get a chance to open the file, starting from the project item that
938/// was added last.
939pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
940 cx.default_global::<ProjectItemRegistry>().register::<I>();
941}
942
943#[derive(Default)]
944pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
945
946struct FollowableViewDescriptor {
947 from_state_proto: fn(
948 Entity<Workspace>,
949 ViewId,
950 &mut Option<proto::view::Variant>,
951 &mut Window,
952 &mut App,
953 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
954 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
955}
956
957impl Global for FollowableViewRegistry {}
958
959impl FollowableViewRegistry {
960 pub fn register<I: FollowableItem>(cx: &mut App) {
961 cx.default_global::<Self>().0.insert(
962 TypeId::of::<I>(),
963 FollowableViewDescriptor {
964 from_state_proto: |workspace, id, state, window, cx| {
965 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
966 cx.foreground_executor()
967 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
968 })
969 },
970 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
971 },
972 );
973 }
974
975 pub fn from_state_proto(
976 workspace: Entity<Workspace>,
977 view_id: ViewId,
978 mut state: Option<proto::view::Variant>,
979 window: &mut Window,
980 cx: &mut App,
981 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
982 cx.update_default_global(|this: &mut Self, cx| {
983 this.0.values().find_map(|descriptor| {
984 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
985 })
986 })
987 }
988
989 pub fn to_followable_view(
990 view: impl Into<AnyView>,
991 cx: &App,
992 ) -> Option<Box<dyn FollowableItemHandle>> {
993 let this = cx.try_global::<Self>()?;
994 let view = view.into();
995 let descriptor = this.0.get(&view.entity_type())?;
996 Some((descriptor.to_followable_view)(&view))
997 }
998}
999
1000#[derive(Copy, Clone)]
1001struct SerializableItemDescriptor {
1002 deserialize: fn(
1003 Entity<Project>,
1004 WeakEntity<Workspace>,
1005 WorkspaceId,
1006 ItemId,
1007 &mut Window,
1008 &mut Context<Pane>,
1009 ) -> Task<Result<Box<dyn ItemHandle>>>,
1010 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
1011 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
1012}
1013
1014#[derive(Default)]
1015struct SerializableItemRegistry {
1016 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
1017 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
1018}
1019
1020impl Global for SerializableItemRegistry {}
1021
1022impl SerializableItemRegistry {
1023 fn deserialize(
1024 item_kind: &str,
1025 project: Entity<Project>,
1026 workspace: WeakEntity<Workspace>,
1027 workspace_id: WorkspaceId,
1028 item_item: ItemId,
1029 window: &mut Window,
1030 cx: &mut Context<Pane>,
1031 ) -> Task<Result<Box<dyn ItemHandle>>> {
1032 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1033 return Task::ready(Err(anyhow!(
1034 "cannot deserialize {}, descriptor not found",
1035 item_kind
1036 )));
1037 };
1038
1039 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
1040 }
1041
1042 fn cleanup(
1043 item_kind: &str,
1044 workspace_id: WorkspaceId,
1045 loaded_items: Vec<ItemId>,
1046 window: &mut Window,
1047 cx: &mut App,
1048 ) -> Task<Result<()>> {
1049 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1050 return Task::ready(Err(anyhow!(
1051 "cannot cleanup {}, descriptor not found",
1052 item_kind
1053 )));
1054 };
1055
1056 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
1057 }
1058
1059 fn view_to_serializable_item_handle(
1060 view: AnyView,
1061 cx: &App,
1062 ) -> Option<Box<dyn SerializableItemHandle>> {
1063 let this = cx.try_global::<Self>()?;
1064 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
1065 Some((descriptor.view_to_serializable_item)(view))
1066 }
1067
1068 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
1069 let this = cx.try_global::<Self>()?;
1070 this.descriptors_by_kind.get(item_kind).copied()
1071 }
1072}
1073
1074pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
1075 let serialized_item_kind = I::serialized_item_kind();
1076
1077 let registry = cx.default_global::<SerializableItemRegistry>();
1078 let descriptor = SerializableItemDescriptor {
1079 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
1080 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
1081 cx.foreground_executor()
1082 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
1083 },
1084 cleanup: |workspace_id, loaded_items, window, cx| {
1085 I::cleanup(workspace_id, loaded_items, window, cx)
1086 },
1087 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
1088 };
1089 registry
1090 .descriptors_by_kind
1091 .insert(Arc::from(serialized_item_kind), descriptor);
1092 registry
1093 .descriptors_by_type
1094 .insert(TypeId::of::<I>(), descriptor);
1095}
1096
1097pub struct AppState {
1098 pub languages: Arc<LanguageRegistry>,
1099 pub client: Arc<Client>,
1100 pub user_store: Entity<UserStore>,
1101 pub workspace_store: Entity<WorkspaceStore>,
1102 pub fs: Arc<dyn fs::Fs>,
1103 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1104 pub node_runtime: NodeRuntime,
1105 pub session: Entity<AppSession>,
1106}
1107
1108struct GlobalAppState(Arc<AppState>);
1109
1110impl Global for GlobalAppState {}
1111
1112pub struct WorkspaceStore {
1113 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1114 client: Arc<Client>,
1115 _subscriptions: Vec<client::Subscription>,
1116}
1117
1118#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1119pub enum CollaboratorId {
1120 PeerId(PeerId),
1121 Agent,
1122}
1123
1124impl From<PeerId> for CollaboratorId {
1125 fn from(peer_id: PeerId) -> Self {
1126 CollaboratorId::PeerId(peer_id)
1127 }
1128}
1129
1130impl From<&PeerId> for CollaboratorId {
1131 fn from(peer_id: &PeerId) -> Self {
1132 CollaboratorId::PeerId(*peer_id)
1133 }
1134}
1135
1136#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1137struct Follower {
1138 project_id: Option<u64>,
1139 peer_id: PeerId,
1140}
1141
1142impl AppState {
1143 #[track_caller]
1144 pub fn global(cx: &App) -> Arc<Self> {
1145 cx.global::<GlobalAppState>().0.clone()
1146 }
1147 pub fn try_global(cx: &App) -> Option<Arc<Self>> {
1148 cx.try_global::<GlobalAppState>()
1149 .map(|state| state.0.clone())
1150 }
1151 pub fn set_global(state: Arc<AppState>, cx: &mut App) {
1152 cx.set_global(GlobalAppState(state));
1153 }
1154
1155 #[cfg(any(test, feature = "test-support"))]
1156 pub fn test(cx: &mut App) -> Arc<Self> {
1157 use fs::Fs;
1158 use node_runtime::NodeRuntime;
1159 use session::Session;
1160 use settings::SettingsStore;
1161
1162 if !cx.has_global::<SettingsStore>() {
1163 let settings_store = SettingsStore::test(cx);
1164 cx.set_global(settings_store);
1165 }
1166
1167 let fs = fs::FakeFs::new(cx.background_executor().clone());
1168 <dyn Fs>::set_global(fs.clone(), cx);
1169 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1170 let clock = Arc::new(clock::FakeSystemClock::new());
1171 let http_client = http_client::FakeHttpClient::with_404_response();
1172 let client = Client::new(clock, http_client, cx);
1173 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1174 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1175 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1176
1177 theme_settings::init(theme::LoadThemes::JustBase, cx);
1178 client::init(&client, cx);
1179
1180 Arc::new(Self {
1181 client,
1182 fs,
1183 languages,
1184 user_store,
1185 workspace_store,
1186 node_runtime: NodeRuntime::unavailable(),
1187 build_window_options: |_, _| Default::default(),
1188 session,
1189 })
1190 }
1191}
1192
1193struct DelayedDebouncedEditAction {
1194 task: Option<Task<()>>,
1195 cancel_channel: Option<oneshot::Sender<()>>,
1196}
1197
1198impl DelayedDebouncedEditAction {
1199 fn new() -> DelayedDebouncedEditAction {
1200 DelayedDebouncedEditAction {
1201 task: None,
1202 cancel_channel: None,
1203 }
1204 }
1205
1206 fn fire_new<F>(
1207 &mut self,
1208 delay: Duration,
1209 window: &mut Window,
1210 cx: &mut Context<Workspace>,
1211 func: F,
1212 ) where
1213 F: 'static
1214 + Send
1215 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1216 {
1217 if let Some(channel) = self.cancel_channel.take() {
1218 _ = channel.send(());
1219 }
1220
1221 let (sender, mut receiver) = oneshot::channel::<()>();
1222 self.cancel_channel = Some(sender);
1223
1224 let previous_task = self.task.take();
1225 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1226 let mut timer = cx.background_executor().timer(delay).fuse();
1227 if let Some(previous_task) = previous_task {
1228 previous_task.await;
1229 }
1230
1231 futures::select_biased! {
1232 _ = receiver => return,
1233 _ = timer => {}
1234 }
1235
1236 if let Some(result) = workspace
1237 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1238 .log_err()
1239 {
1240 result.await.log_err();
1241 }
1242 }));
1243 }
1244}
1245
1246pub enum Event {
1247 PaneAdded(Entity<Pane>),
1248 PaneRemoved,
1249 ItemAdded {
1250 item: Box<dyn ItemHandle>,
1251 },
1252 ActiveItemChanged,
1253 ItemRemoved {
1254 item_id: EntityId,
1255 },
1256 UserSavedItem {
1257 pane: WeakEntity<Pane>,
1258 item: Box<dyn WeakItemHandle>,
1259 save_intent: SaveIntent,
1260 },
1261 ContactRequestedJoin(u64),
1262 WorkspaceCreated(WeakEntity<Workspace>),
1263 OpenBundledFile {
1264 text: Cow<'static, str>,
1265 title: &'static str,
1266 language: &'static str,
1267 },
1268 ZoomChanged,
1269 ModalOpened,
1270 Activate,
1271 PanelAdded(AnyView),
1272}
1273
1274#[derive(Debug, Clone)]
1275pub enum OpenVisible {
1276 All,
1277 None,
1278 OnlyFiles,
1279 OnlyDirectories,
1280}
1281
1282enum WorkspaceLocation {
1283 // Valid local paths or SSH project to serialize
1284 Location(SerializedWorkspaceLocation, PathList),
1285 // No valid location found hence clear session id
1286 DetachFromSession,
1287 // No valid location found to serialize
1288 None,
1289}
1290
1291type PromptForNewPath = Box<
1292 dyn Fn(
1293 &mut Workspace,
1294 DirectoryLister,
1295 Option<String>,
1296 &mut Window,
1297 &mut Context<Workspace>,
1298 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1299>;
1300
1301type PromptForOpenPath = Box<
1302 dyn Fn(
1303 &mut Workspace,
1304 DirectoryLister,
1305 &mut Window,
1306 &mut Context<Workspace>,
1307 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1308>;
1309
1310#[derive(Default)]
1311struct DispatchingKeystrokes {
1312 dispatched: HashSet<Vec<Keystroke>>,
1313 queue: VecDeque<Keystroke>,
1314 task: Option<Shared<Task<()>>>,
1315}
1316
1317/// Collects everything project-related for a certain window opened.
1318/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1319///
1320/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1321/// The `Workspace` owns everybody's state and serves as a default, "global context",
1322/// that can be used to register a global action to be triggered from any place in the window.
1323pub struct Workspace {
1324 weak_self: WeakEntity<Self>,
1325 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1326 zoomed: Option<AnyWeakView>,
1327 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1328 zoomed_position: Option<DockPosition>,
1329 center: PaneGroup,
1330 left_dock: Entity<Dock>,
1331 bottom_dock: Entity<Dock>,
1332 right_dock: Entity<Dock>,
1333 panes: Vec<Entity<Pane>>,
1334 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1335 active_pane: Entity<Pane>,
1336 last_active_center_pane: Option<WeakEntity<Pane>>,
1337 last_active_view_id: Option<proto::ViewId>,
1338 status_bar: Entity<StatusBar>,
1339 pub(crate) modal_layer: Entity<ModalLayer>,
1340 toast_layer: Entity<ToastLayer>,
1341 titlebar_item: Option<AnyView>,
1342 notifications: Notifications,
1343 suppressed_notifications: HashSet<NotificationId>,
1344 project: Entity<Project>,
1345 follower_states: HashMap<CollaboratorId, FollowerState>,
1346 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1347 window_edited: bool,
1348 last_window_title: Option<String>,
1349 dirty_items: HashMap<EntityId, Subscription>,
1350 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1351 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1352 database_id: Option<WorkspaceId>,
1353 app_state: Arc<AppState>,
1354 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1355 _subscriptions: Vec<Subscription>,
1356 _apply_leader_updates: Task<Result<()>>,
1357 _observe_current_user: Task<Result<()>>,
1358 _schedule_serialize_workspace: Option<Task<()>>,
1359 _serialize_workspace_task: Option<Task<()>>,
1360 _schedule_serialize_ssh_paths: Option<Task<()>>,
1361 pane_history_timestamp: Arc<AtomicUsize>,
1362 bounds: Bounds<Pixels>,
1363 pub centered_layout: bool,
1364 bounds_save_task_queued: Option<Task<()>>,
1365 on_prompt_for_new_path: Option<PromptForNewPath>,
1366 on_prompt_for_open_path: Option<PromptForOpenPath>,
1367 terminal_provider: Option<Box<dyn TerminalProvider>>,
1368 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1369 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1370 _items_serializer: Task<Result<()>>,
1371 session_id: Option<String>,
1372 scheduled_tasks: Vec<Task<()>>,
1373 last_open_dock_positions: Vec<DockPosition>,
1374 removing: bool,
1375 open_in_dev_container: bool,
1376 _dev_container_task: Option<Task<Result<()>>>,
1377 _panels_task: Option<Task<Result<()>>>,
1378 sidebar_focus_handle: Option<FocusHandle>,
1379 multi_workspace: Option<WeakEntity<MultiWorkspace>>,
1380}
1381
1382impl EventEmitter<Event> for Workspace {}
1383
1384#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1385pub struct ViewId {
1386 pub creator: CollaboratorId,
1387 pub id: u64,
1388}
1389
1390pub struct FollowerState {
1391 center_pane: Entity<Pane>,
1392 dock_pane: Option<Entity<Pane>>,
1393 active_view_id: Option<ViewId>,
1394 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1395}
1396
1397struct FollowerView {
1398 view: Box<dyn FollowableItemHandle>,
1399 location: Option<proto::PanelId>,
1400}
1401
1402#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1403pub enum OpenMode {
1404 /// Open the workspace in a new window.
1405 NewWindow,
1406 /// Add to the window's multi workspace without activating it (used during deserialization).
1407 Add,
1408 /// Add to the window's multi workspace and activate it.
1409 #[default]
1410 Activate,
1411}
1412
1413impl Workspace {
1414 pub fn new(
1415 workspace_id: Option<WorkspaceId>,
1416 project: Entity<Project>,
1417 app_state: Arc<AppState>,
1418 window: &mut Window,
1419 cx: &mut Context<Self>,
1420 ) -> Self {
1421 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1422 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1423 if let TrustedWorktreesEvent::Trusted(..) = e {
1424 // Do not persist auto trusted worktrees
1425 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1426 worktrees_store.update(cx, |worktrees_store, cx| {
1427 worktrees_store.schedule_serialization(
1428 cx,
1429 |new_trusted_worktrees, cx| {
1430 let timeout =
1431 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1432 let db = WorkspaceDb::global(cx);
1433 cx.background_spawn(async move {
1434 timeout.await;
1435 db.save_trusted_worktrees(new_trusted_worktrees)
1436 .await
1437 .log_err();
1438 })
1439 },
1440 )
1441 });
1442 }
1443 }
1444 })
1445 .detach();
1446
1447 cx.observe_global::<SettingsStore>(|_, cx| {
1448 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1449 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1450 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1451 trusted_worktrees.auto_trust_all(cx);
1452 })
1453 }
1454 }
1455 })
1456 .detach();
1457 }
1458
1459 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1460 match event {
1461 project::Event::RemoteIdChanged(_) => {
1462 this.update_window_title(window, cx);
1463 }
1464
1465 project::Event::CollaboratorLeft(peer_id) => {
1466 this.collaborator_left(*peer_id, window, cx);
1467 }
1468
1469 &project::Event::WorktreeRemoved(_) => {
1470 this.update_window_title(window, cx);
1471 this.serialize_workspace(window, cx);
1472 this.update_history(cx);
1473 }
1474
1475 &project::Event::WorktreeAdded(id) => {
1476 this.update_window_title(window, cx);
1477 if this
1478 .project()
1479 .read(cx)
1480 .worktree_for_id(id, cx)
1481 .is_some_and(|wt| wt.read(cx).is_visible())
1482 {
1483 this.serialize_workspace(window, cx);
1484 this.update_history(cx);
1485 }
1486 }
1487 project::Event::WorktreeUpdatedEntries(..) => {
1488 this.update_window_title(window, cx);
1489 this.serialize_workspace(window, cx);
1490 }
1491
1492 project::Event::DisconnectedFromHost => {
1493 this.update_window_edited(window, cx);
1494 let leaders_to_unfollow =
1495 this.follower_states.keys().copied().collect::<Vec<_>>();
1496 for leader_id in leaders_to_unfollow {
1497 this.unfollow(leader_id, window, cx);
1498 }
1499 }
1500
1501 project::Event::DisconnectedFromRemote {
1502 server_not_running: _,
1503 } => {
1504 this.update_window_edited(window, cx);
1505 }
1506
1507 project::Event::Closed => {
1508 window.remove_window();
1509 }
1510
1511 project::Event::DeletedEntry(_, entry_id) => {
1512 for pane in this.panes.iter() {
1513 pane.update(cx, |pane, cx| {
1514 pane.handle_deleted_project_item(*entry_id, window, cx)
1515 });
1516 }
1517 }
1518
1519 project::Event::Toast {
1520 notification_id,
1521 message,
1522 link,
1523 } => this.show_notification(
1524 NotificationId::named(notification_id.clone()),
1525 cx,
1526 |cx| {
1527 let mut notification = MessageNotification::new(message.clone(), cx);
1528 if let Some(link) = link {
1529 notification = notification
1530 .more_info_message(link.label)
1531 .more_info_url(link.url);
1532 }
1533
1534 cx.new(|_| notification)
1535 },
1536 ),
1537
1538 project::Event::HideToast { notification_id } => {
1539 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1540 }
1541
1542 project::Event::LanguageServerPrompt(request) => {
1543 struct LanguageServerPrompt;
1544
1545 this.show_notification(
1546 NotificationId::composite::<LanguageServerPrompt>(request.id),
1547 cx,
1548 |cx| {
1549 cx.new(|cx| {
1550 notifications::LanguageServerPrompt::new(request.clone(), cx)
1551 })
1552 },
1553 );
1554 }
1555
1556 project::Event::AgentLocationChanged => {
1557 this.handle_agent_location_changed(window, cx)
1558 }
1559
1560 _ => {}
1561 }
1562 cx.notify()
1563 })
1564 .detach();
1565
1566 cx.subscribe_in(
1567 &project.read(cx).breakpoint_store(),
1568 window,
1569 |workspace, _, event, window, cx| match event {
1570 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1571 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1572 workspace.serialize_workspace(window, cx);
1573 }
1574 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1575 },
1576 )
1577 .detach();
1578 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1579 cx.subscribe_in(
1580 &toolchain_store,
1581 window,
1582 |workspace, _, event, window, cx| match event {
1583 ToolchainStoreEvent::CustomToolchainsModified => {
1584 workspace.serialize_workspace(window, cx);
1585 }
1586 _ => {}
1587 },
1588 )
1589 .detach();
1590 }
1591
1592 cx.on_focus_lost(window, |this, window, cx| {
1593 let focus_handle = this.focus_handle(cx);
1594 window.focus(&focus_handle, cx);
1595 })
1596 .detach();
1597
1598 let weak_handle = cx.entity().downgrade();
1599 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1600
1601 let center_pane = cx.new(|cx| {
1602 let mut center_pane = Pane::new(
1603 weak_handle.clone(),
1604 project.clone(),
1605 pane_history_timestamp.clone(),
1606 None,
1607 NewFile.boxed_clone(),
1608 true,
1609 window,
1610 cx,
1611 );
1612 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1613 center_pane.set_should_display_welcome_page(true);
1614 center_pane
1615 });
1616 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1617 .detach();
1618
1619 window.focus(¢er_pane.focus_handle(cx), cx);
1620
1621 cx.emit(Event::PaneAdded(center_pane.clone()));
1622
1623 let any_window_handle = window.window_handle();
1624 app_state.workspace_store.update(cx, |store, _| {
1625 store
1626 .workspaces
1627 .insert((any_window_handle, weak_handle.clone()));
1628 });
1629
1630 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1631 let mut connection_status = app_state.client.status();
1632 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1633 current_user.next().await;
1634 connection_status.next().await;
1635 let mut stream =
1636 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1637
1638 while stream.recv().await.is_some() {
1639 this.update(cx, |_, cx| cx.notify())?;
1640 }
1641 anyhow::Ok(())
1642 });
1643
1644 // All leader updates are enqueued and then processed in a single task, so
1645 // that each asynchronous operation can be run in order.
1646 let (leader_updates_tx, mut leader_updates_rx) =
1647 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1648 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1649 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1650 Self::process_leader_update(&this, leader_id, update, cx)
1651 .await
1652 .log_err();
1653 }
1654
1655 Ok(())
1656 });
1657
1658 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1659 let modal_layer = cx.new(|_| ModalLayer::new());
1660 let toast_layer = cx.new(|_| ToastLayer::new());
1661 cx.subscribe(
1662 &modal_layer,
1663 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1664 cx.emit(Event::ModalOpened);
1665 },
1666 )
1667 .detach();
1668
1669 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1670 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1671 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1672 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1673 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1674 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1675 let multi_workspace = window
1676 .root::<MultiWorkspace>()
1677 .flatten()
1678 .map(|mw| mw.downgrade());
1679 let status_bar = cx.new(|cx| {
1680 let mut status_bar =
1681 StatusBar::new(¢er_pane.clone(), multi_workspace.clone(), window, cx);
1682 status_bar.add_left_item(left_dock_buttons, window, cx);
1683 status_bar.add_right_item(right_dock_buttons, window, cx);
1684 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1685 status_bar
1686 });
1687
1688 let session_id = app_state.session.read(cx).id().to_owned();
1689
1690 let mut active_call = None;
1691 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1692 let subscriptions =
1693 vec![
1694 call.0
1695 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1696 ];
1697 active_call = Some((call, subscriptions));
1698 }
1699
1700 let (serializable_items_tx, serializable_items_rx) =
1701 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1702 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1703 Self::serialize_items(&this, serializable_items_rx, cx).await
1704 });
1705
1706 let subscriptions = vec![
1707 cx.observe_window_activation(window, Self::on_window_activation_changed),
1708 cx.observe_window_bounds(window, move |this, window, cx| {
1709 if this.bounds_save_task_queued.is_some() {
1710 return;
1711 }
1712 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1713 cx.background_executor()
1714 .timer(Duration::from_millis(100))
1715 .await;
1716 this.update_in(cx, |this, window, cx| {
1717 this.save_window_bounds(window, cx).detach();
1718 this.bounds_save_task_queued.take();
1719 })
1720 .ok();
1721 }));
1722 cx.notify();
1723 }),
1724 cx.observe_window_appearance(window, |_, window, cx| {
1725 let window_appearance = window.appearance();
1726
1727 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1728
1729 theme_settings::reload_theme(cx);
1730 theme_settings::reload_icon_theme(cx);
1731 }),
1732 cx.on_release({
1733 let weak_handle = weak_handle.clone();
1734 move |this, cx| {
1735 this.app_state.workspace_store.update(cx, move |store, _| {
1736 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1737 })
1738 }
1739 }),
1740 ];
1741
1742 cx.defer_in(window, move |this, window, cx| {
1743 this.update_window_title(window, cx);
1744 this.show_initial_notifications(cx);
1745 });
1746
1747 let mut center = PaneGroup::new(center_pane.clone());
1748 center.set_is_center(true);
1749 center.mark_positions(cx);
1750
1751 Workspace {
1752 weak_self: weak_handle.clone(),
1753 zoomed: None,
1754 zoomed_position: None,
1755 previous_dock_drag_coordinates: None,
1756 center,
1757 panes: vec![center_pane.clone()],
1758 panes_by_item: Default::default(),
1759 active_pane: center_pane.clone(),
1760 last_active_center_pane: Some(center_pane.downgrade()),
1761 last_active_view_id: None,
1762 status_bar,
1763 modal_layer,
1764 toast_layer,
1765 titlebar_item: None,
1766 notifications: Notifications::default(),
1767 suppressed_notifications: HashSet::default(),
1768 left_dock,
1769 bottom_dock,
1770 right_dock,
1771 _panels_task: None,
1772 project: project.clone(),
1773 follower_states: Default::default(),
1774 last_leaders_by_pane: Default::default(),
1775 dispatching_keystrokes: Default::default(),
1776 window_edited: false,
1777 last_window_title: None,
1778 dirty_items: Default::default(),
1779 active_call,
1780 database_id: workspace_id,
1781 app_state,
1782 _observe_current_user,
1783 _apply_leader_updates,
1784 _schedule_serialize_workspace: None,
1785 _serialize_workspace_task: None,
1786 _schedule_serialize_ssh_paths: None,
1787 leader_updates_tx,
1788 _subscriptions: subscriptions,
1789 pane_history_timestamp,
1790 workspace_actions: Default::default(),
1791 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1792 bounds: Default::default(),
1793 centered_layout: false,
1794 bounds_save_task_queued: None,
1795 on_prompt_for_new_path: None,
1796 on_prompt_for_open_path: None,
1797 terminal_provider: None,
1798 debugger_provider: None,
1799 serializable_items_tx,
1800 _items_serializer,
1801 session_id: Some(session_id),
1802
1803 scheduled_tasks: Vec::new(),
1804 last_open_dock_positions: Vec::new(),
1805 removing: false,
1806 sidebar_focus_handle: None,
1807 multi_workspace,
1808 open_in_dev_container: false,
1809 _dev_container_task: None,
1810 }
1811 }
1812
1813 pub fn new_local(
1814 abs_paths: Vec<PathBuf>,
1815 app_state: Arc<AppState>,
1816 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1817 env: Option<HashMap<String, String>>,
1818 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1819 open_mode: OpenMode,
1820 cx: &mut App,
1821 ) -> Task<anyhow::Result<OpenResult>> {
1822 let project_handle = Project::local(
1823 app_state.client.clone(),
1824 app_state.node_runtime.clone(),
1825 app_state.user_store.clone(),
1826 app_state.languages.clone(),
1827 app_state.fs.clone(),
1828 env,
1829 Default::default(),
1830 cx,
1831 );
1832
1833 let db = WorkspaceDb::global(cx);
1834 let kvp = db::kvp::KeyValueStore::global(cx);
1835 cx.spawn(async move |cx| {
1836 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1837 for path in abs_paths.into_iter() {
1838 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1839 paths_to_open.push(canonical)
1840 } else {
1841 paths_to_open.push(path)
1842 }
1843 }
1844
1845 let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
1846
1847 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1848 paths_to_open = paths.ordered_paths().cloned().collect();
1849 if !paths.is_lexicographically_ordered() {
1850 project_handle.update(cx, |project, cx| {
1851 project.set_worktrees_reordered(true, cx);
1852 });
1853 }
1854 }
1855
1856 // Get project paths for all of the abs_paths
1857 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1858 Vec::with_capacity(paths_to_open.len());
1859
1860 for path in paths_to_open.into_iter() {
1861 if let Some((_, project_entry)) = cx
1862 .update(|cx| {
1863 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1864 })
1865 .await
1866 .log_err()
1867 {
1868 project_paths.push((path, Some(project_entry)));
1869 } else {
1870 project_paths.push((path, None));
1871 }
1872 }
1873
1874 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1875 serialized_workspace.id
1876 } else {
1877 db.next_id().await.unwrap_or_else(|_| Default::default())
1878 };
1879
1880 let toolchains = db.toolchains(workspace_id).await?;
1881
1882 for (toolchain, worktree_path, path) in toolchains {
1883 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1884 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1885 this.find_worktree(&worktree_path, cx)
1886 .and_then(|(worktree, rel_path)| {
1887 if rel_path.is_empty() {
1888 Some(worktree.read(cx).id())
1889 } else {
1890 None
1891 }
1892 })
1893 }) else {
1894 // We did not find a worktree with a given path, but that's whatever.
1895 continue;
1896 };
1897 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1898 continue;
1899 }
1900
1901 project_handle
1902 .update(cx, |this, cx| {
1903 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1904 })
1905 .await;
1906 }
1907 if let Some(workspace) = serialized_workspace.as_ref() {
1908 project_handle.update(cx, |this, cx| {
1909 for (scope, toolchains) in &workspace.user_toolchains {
1910 for toolchain in toolchains {
1911 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1912 }
1913 }
1914 });
1915 }
1916
1917 let window_to_replace = match open_mode {
1918 OpenMode::NewWindow => None,
1919 _ => requesting_window,
1920 };
1921
1922 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1923 if let Some(window) = window_to_replace {
1924 let centered_layout = serialized_workspace
1925 .as_ref()
1926 .map(|w| w.centered_layout)
1927 .unwrap_or(false);
1928
1929 let workspace = window.update(cx, |multi_workspace, window, cx| {
1930 let workspace = cx.new(|cx| {
1931 let mut workspace = Workspace::new(
1932 Some(workspace_id),
1933 project_handle.clone(),
1934 app_state.clone(),
1935 window,
1936 cx,
1937 );
1938
1939 workspace.centered_layout = centered_layout;
1940
1941 // Call init callback to add items before window renders
1942 if let Some(init) = init {
1943 init(&mut workspace, window, cx);
1944 }
1945
1946 workspace
1947 });
1948 match open_mode {
1949 OpenMode::Activate => {
1950 multi_workspace.activate(workspace.clone(), window, cx);
1951 }
1952 OpenMode::Add => {
1953 multi_workspace.add(workspace.clone(), &*window, cx);
1954 }
1955 OpenMode::NewWindow => {
1956 unreachable!()
1957 }
1958 }
1959 workspace
1960 })?;
1961 (window, workspace)
1962 } else {
1963 let window_bounds_override = window_bounds_env_override();
1964
1965 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1966 (Some(WindowBounds::Windowed(bounds)), None)
1967 } else if let Some(workspace) = serialized_workspace.as_ref()
1968 && let Some(display) = workspace.display
1969 && let Some(bounds) = workspace.window_bounds.as_ref()
1970 {
1971 // Reopening an existing workspace - restore its saved bounds
1972 (Some(bounds.0), Some(display))
1973 } else if let Some((display, bounds)) =
1974 persistence::read_default_window_bounds(&kvp)
1975 {
1976 // New or empty workspace - use the last known window bounds
1977 (Some(bounds), Some(display))
1978 } else {
1979 // New window - let GPUI's default_bounds() handle cascading
1980 (None, None)
1981 };
1982
1983 // Use the serialized workspace to construct the new window
1984 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1985 options.window_bounds = window_bounds;
1986 let centered_layout = serialized_workspace
1987 .as_ref()
1988 .map(|w| w.centered_layout)
1989 .unwrap_or(false);
1990 let window = cx.open_window(options, {
1991 let app_state = app_state.clone();
1992 let project_handle = project_handle.clone();
1993 move |window, cx| {
1994 let workspace = cx.new(|cx| {
1995 let mut workspace = Workspace::new(
1996 Some(workspace_id),
1997 project_handle,
1998 app_state,
1999 window,
2000 cx,
2001 );
2002 workspace.centered_layout = centered_layout;
2003
2004 // Call init callback to add items before window renders
2005 if let Some(init) = init {
2006 init(&mut workspace, window, cx);
2007 }
2008
2009 workspace
2010 });
2011 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
2012 }
2013 })?;
2014 let workspace =
2015 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
2016 multi_workspace.workspace().clone()
2017 })?;
2018 (window, workspace)
2019 };
2020
2021 notify_if_database_failed(window, cx);
2022 // Check if this is an empty workspace (no paths to open)
2023 // An empty workspace is one where project_paths is empty
2024 let is_empty_workspace = project_paths.is_empty();
2025 // Check if serialized workspace has paths before it's moved
2026 let serialized_workspace_has_paths = serialized_workspace
2027 .as_ref()
2028 .map(|ws| !ws.paths.is_empty())
2029 .unwrap_or(false);
2030
2031 let opened_items = window
2032 .update(cx, |_, window, cx| {
2033 workspace.update(cx, |_workspace: &mut Workspace, cx| {
2034 open_items(serialized_workspace, project_paths, window, cx)
2035 })
2036 })?
2037 .await
2038 .unwrap_or_default();
2039
2040 // Restore default dock state for empty workspaces
2041 // Only restore if:
2042 // 1. This is an empty workspace (no paths), AND
2043 // 2. The serialized workspace either doesn't exist or has no paths
2044 if is_empty_workspace && !serialized_workspace_has_paths {
2045 if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
2046 window
2047 .update(cx, |_, window, cx| {
2048 workspace.update(cx, |workspace, cx| {
2049 for (dock, serialized_dock) in [
2050 (&workspace.right_dock, &default_docks.right),
2051 (&workspace.left_dock, &default_docks.left),
2052 (&workspace.bottom_dock, &default_docks.bottom),
2053 ] {
2054 dock.update(cx, |dock, cx| {
2055 dock.serialized_dock = Some(serialized_dock.clone());
2056 dock.restore_state(window, cx);
2057 });
2058 }
2059 cx.notify();
2060 });
2061 })
2062 .log_err();
2063 }
2064 }
2065
2066 window
2067 .update(cx, |_, _window, cx| {
2068 workspace.update(cx, |this: &mut Workspace, cx| {
2069 this.update_history(cx);
2070 });
2071 })
2072 .log_err();
2073 Ok(OpenResult {
2074 window,
2075 workspace,
2076 opened_items,
2077 })
2078 })
2079 }
2080
2081 pub fn project_group_key(&self, cx: &App) -> ProjectGroupKey {
2082 self.project.read(cx).project_group_key(cx)
2083 }
2084
2085 pub fn weak_handle(&self) -> WeakEntity<Self> {
2086 self.weak_self.clone()
2087 }
2088
2089 pub fn left_dock(&self) -> &Entity<Dock> {
2090 &self.left_dock
2091 }
2092
2093 pub fn bottom_dock(&self) -> &Entity<Dock> {
2094 &self.bottom_dock
2095 }
2096
2097 pub fn set_bottom_dock_layout(
2098 &mut self,
2099 layout: BottomDockLayout,
2100 window: &mut Window,
2101 cx: &mut Context<Self>,
2102 ) {
2103 let fs = self.project().read(cx).fs();
2104 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2105 content.workspace.bottom_dock_layout = Some(layout);
2106 });
2107
2108 cx.notify();
2109 self.serialize_workspace(window, cx);
2110 }
2111
2112 pub fn right_dock(&self) -> &Entity<Dock> {
2113 &self.right_dock
2114 }
2115
2116 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2117 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2118 }
2119
2120 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2121 let left_dock = self.left_dock.read(cx);
2122 let left_visible = left_dock.is_open();
2123 let left_active_panel = left_dock
2124 .active_panel()
2125 .map(|panel| panel.persistent_name().to_string());
2126 // `zoomed_position` is kept in sync with individual panel zoom state
2127 // by the dock code in `Dock::new` and `Dock::add_panel`.
2128 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2129
2130 let right_dock = self.right_dock.read(cx);
2131 let right_visible = right_dock.is_open();
2132 let right_active_panel = right_dock
2133 .active_panel()
2134 .map(|panel| panel.persistent_name().to_string());
2135 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2136
2137 let bottom_dock = self.bottom_dock.read(cx);
2138 let bottom_visible = bottom_dock.is_open();
2139 let bottom_active_panel = bottom_dock
2140 .active_panel()
2141 .map(|panel| panel.persistent_name().to_string());
2142 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2143
2144 DockStructure {
2145 left: DockData {
2146 visible: left_visible,
2147 active_panel: left_active_panel,
2148 zoom: left_dock_zoom,
2149 },
2150 right: DockData {
2151 visible: right_visible,
2152 active_panel: right_active_panel,
2153 zoom: right_dock_zoom,
2154 },
2155 bottom: DockData {
2156 visible: bottom_visible,
2157 active_panel: bottom_active_panel,
2158 zoom: bottom_dock_zoom,
2159 },
2160 }
2161 }
2162
2163 pub fn set_dock_structure(
2164 &self,
2165 docks: DockStructure,
2166 window: &mut Window,
2167 cx: &mut Context<Self>,
2168 ) {
2169 for (dock, data) in [
2170 (&self.left_dock, docks.left),
2171 (&self.bottom_dock, docks.bottom),
2172 (&self.right_dock, docks.right),
2173 ] {
2174 dock.update(cx, |dock, cx| {
2175 dock.serialized_dock = Some(data);
2176 dock.restore_state(window, cx);
2177 });
2178 }
2179 }
2180
2181 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2182 self.items(cx)
2183 .filter_map(|item| {
2184 let project_path = item.project_path(cx)?;
2185 self.project.read(cx).absolute_path(&project_path, cx)
2186 })
2187 .collect()
2188 }
2189
2190 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2191 match position {
2192 DockPosition::Left => &self.left_dock,
2193 DockPosition::Bottom => &self.bottom_dock,
2194 DockPosition::Right => &self.right_dock,
2195 }
2196 }
2197
2198 pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
2199 self.all_docks().into_iter().find_map(|dock| {
2200 let dock = dock.read(cx);
2201 dock.has_agent_panel(cx).then_some(dock.position())
2202 })
2203 }
2204
2205 pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
2206 self.all_docks().into_iter().find_map(|dock| {
2207 let dock = dock.read(cx);
2208 let panel = dock.panel::<T>()?;
2209 dock.stored_panel_size_state(&panel)
2210 })
2211 }
2212
2213 pub fn persisted_panel_size_state(
2214 &self,
2215 panel_key: &'static str,
2216 cx: &App,
2217 ) -> Option<dock::PanelSizeState> {
2218 dock::Dock::load_persisted_size_state(self, panel_key, cx)
2219 }
2220
2221 pub fn persist_panel_size_state(
2222 &self,
2223 panel_key: &str,
2224 size_state: dock::PanelSizeState,
2225 cx: &mut App,
2226 ) {
2227 let Some(workspace_id) = self
2228 .database_id()
2229 .map(|id| i64::from(id).to_string())
2230 .or(self.session_id())
2231 else {
2232 return;
2233 };
2234
2235 let kvp = db::kvp::KeyValueStore::global(cx);
2236 let panel_key = panel_key.to_string();
2237 cx.background_spawn(async move {
2238 let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
2239 scope
2240 .write(
2241 format!("{workspace_id}:{panel_key}"),
2242 serde_json::to_string(&size_state)?,
2243 )
2244 .await
2245 })
2246 .detach_and_log_err(cx);
2247 }
2248
2249 pub fn set_panel_size_state<T: Panel>(
2250 &mut self,
2251 size_state: dock::PanelSizeState,
2252 window: &mut Window,
2253 cx: &mut Context<Self>,
2254 ) -> bool {
2255 let Some(panel) = self.panel::<T>(cx) else {
2256 return false;
2257 };
2258
2259 let dock = self.dock_at_position(panel.position(window, cx));
2260 let did_set = dock.update(cx, |dock, cx| {
2261 dock.set_panel_size_state(&panel, size_state, cx)
2262 });
2263
2264 if did_set {
2265 self.persist_panel_size_state(T::panel_key(), size_state, cx);
2266 }
2267
2268 did_set
2269 }
2270
2271 pub fn toggle_dock_panel_flexible_size(
2272 &self,
2273 dock: &Entity<Dock>,
2274 panel: &dyn PanelHandle,
2275 window: &mut Window,
2276 cx: &mut App,
2277 ) {
2278 let position = dock.read(cx).position();
2279 let current_size = self.dock_size(&dock.read(cx), window, cx);
2280 let current_flex =
2281 current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
2282 dock.update(cx, |dock, cx| {
2283 dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
2284 });
2285 }
2286
2287 fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
2288 let panel = dock.active_panel()?;
2289 let size_state = dock
2290 .stored_panel_size_state(panel.as_ref())
2291 .unwrap_or_default();
2292 let position = dock.position();
2293
2294 let use_flex = panel.has_flexible_size(window, cx);
2295
2296 if position.axis() == Axis::Horizontal
2297 && use_flex
2298 && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
2299 {
2300 let workspace_width = self.bounds.size.width;
2301 if workspace_width <= Pixels::ZERO {
2302 return None;
2303 }
2304 let flex = flex.max(0.001);
2305 let center_column_count = self.center_full_height_column_count();
2306 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2307 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2308 let total_flex = flex + center_column_count + opposite_flex;
2309 return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
2310 } else {
2311 let opposite_fixed = opposite
2312 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2313 .unwrap_or_default();
2314 let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
2315 return Some(
2316 (flex / (flex + center_column_count) * available).max(RESIZE_HANDLE_SIZE),
2317 );
2318 }
2319 }
2320
2321 Some(
2322 size_state
2323 .size
2324 .unwrap_or_else(|| panel.default_size(window, cx)),
2325 )
2326 }
2327
2328 pub fn dock_flex_for_size(
2329 &self,
2330 position: DockPosition,
2331 size: Pixels,
2332 window: &Window,
2333 cx: &App,
2334 ) -> Option<f32> {
2335 if position.axis() != Axis::Horizontal {
2336 return None;
2337 }
2338
2339 let workspace_width = self.bounds.size.width;
2340 if workspace_width <= Pixels::ZERO {
2341 return None;
2342 }
2343
2344 let center_column_count = self.center_full_height_column_count();
2345 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2346 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2347 let size = size.clamp(px(0.), workspace_width - px(1.));
2348 Some((size * (center_column_count + opposite_flex) / (workspace_width - size)).max(0.0))
2349 } else {
2350 let opposite_width = opposite
2351 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2352 .unwrap_or_default();
2353 let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
2354 let remaining = (available - size).max(px(1.));
2355 Some((size * center_column_count / remaining).max(0.0))
2356 }
2357 }
2358
2359 fn opposite_dock_panel_and_size_state(
2360 &self,
2361 position: DockPosition,
2362 window: &Window,
2363 cx: &App,
2364 ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
2365 let opposite_position = match position {
2366 DockPosition::Left => DockPosition::Right,
2367 DockPosition::Right => DockPosition::Left,
2368 DockPosition::Bottom => return None,
2369 };
2370
2371 let opposite_dock = self.dock_at_position(opposite_position).read(cx);
2372 let panel = opposite_dock.visible_panel()?;
2373 let mut size_state = opposite_dock
2374 .stored_panel_size_state(panel.as_ref())
2375 .unwrap_or_default();
2376 if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
2377 size_state.flex = self.default_dock_flex(opposite_position);
2378 }
2379 Some((panel.clone(), size_state))
2380 }
2381
2382 fn center_full_height_column_count(&self) -> f32 {
2383 self.center.full_height_column_count().max(1) as f32
2384 }
2385
2386 pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
2387 if position.axis() != Axis::Horizontal {
2388 return None;
2389 }
2390
2391 Some(1.0)
2392 }
2393
2394 pub fn is_edited(&self) -> bool {
2395 self.window_edited
2396 }
2397
2398 pub fn add_panel<T: Panel>(
2399 &mut self,
2400 panel: Entity<T>,
2401 window: &mut Window,
2402 cx: &mut Context<Self>,
2403 ) {
2404 let focus_handle = panel.panel_focus_handle(cx);
2405 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2406 .detach();
2407
2408 let dock_position = panel.position(window, cx);
2409 let dock = self.dock_at_position(dock_position);
2410 let any_panel = panel.to_any();
2411 let persisted_size_state =
2412 self.persisted_panel_size_state(T::panel_key(), cx)
2413 .or_else(|| {
2414 load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
2415 let state = dock::PanelSizeState {
2416 size: Some(size),
2417 flex: None,
2418 };
2419 self.persist_panel_size_state(T::panel_key(), state, cx);
2420 state
2421 })
2422 });
2423
2424 dock.update(cx, |dock, cx| {
2425 let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
2426 if let Some(size_state) = persisted_size_state {
2427 dock.set_panel_size_state(&panel, size_state, cx);
2428 }
2429 index
2430 });
2431
2432 cx.emit(Event::PanelAdded(any_panel));
2433 }
2434
2435 pub fn remove_panel<T: Panel>(
2436 &mut self,
2437 panel: &Entity<T>,
2438 window: &mut Window,
2439 cx: &mut Context<Self>,
2440 ) {
2441 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2442 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2443 }
2444 }
2445
2446 pub fn status_bar(&self) -> &Entity<StatusBar> {
2447 &self.status_bar
2448 }
2449
2450 pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
2451 self.sidebar_focus_handle = handle;
2452 }
2453
2454 pub fn status_bar_visible(&self, cx: &App) -> bool {
2455 StatusBarSettings::get_global(cx).show
2456 }
2457
2458 pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
2459 self.multi_workspace.as_ref()
2460 }
2461
2462 pub fn set_multi_workspace(
2463 &mut self,
2464 multi_workspace: WeakEntity<MultiWorkspace>,
2465 cx: &mut App,
2466 ) {
2467 self.status_bar.update(cx, |status_bar, cx| {
2468 status_bar.set_multi_workspace(multi_workspace.clone(), cx);
2469 });
2470 self.multi_workspace = Some(multi_workspace);
2471 }
2472
2473 pub fn app_state(&self) -> &Arc<AppState> {
2474 &self.app_state
2475 }
2476
2477 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2478 self._panels_task = Some(task);
2479 }
2480
2481 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2482 self._panels_task.take()
2483 }
2484
2485 pub fn user_store(&self) -> &Entity<UserStore> {
2486 &self.app_state.user_store
2487 }
2488
2489 pub fn project(&self) -> &Entity<Project> {
2490 &self.project
2491 }
2492
2493 pub fn path_style(&self, cx: &App) -> PathStyle {
2494 self.project.read(cx).path_style(cx)
2495 }
2496
2497 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2498 let mut history: HashMap<EntityId, usize> = HashMap::default();
2499
2500 for pane_handle in &self.panes {
2501 let pane = pane_handle.read(cx);
2502
2503 for entry in pane.activation_history() {
2504 history.insert(
2505 entry.entity_id,
2506 history
2507 .get(&entry.entity_id)
2508 .cloned()
2509 .unwrap_or(0)
2510 .max(entry.timestamp),
2511 );
2512 }
2513 }
2514
2515 history
2516 }
2517
2518 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2519 let mut recent_item: Option<Entity<T>> = None;
2520 let mut recent_timestamp = 0;
2521 for pane_handle in &self.panes {
2522 let pane = pane_handle.read(cx);
2523 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2524 pane.items().map(|item| (item.item_id(), item)).collect();
2525 for entry in pane.activation_history() {
2526 if entry.timestamp > recent_timestamp
2527 && let Some(&item) = item_map.get(&entry.entity_id)
2528 && let Some(typed_item) = item.act_as::<T>(cx)
2529 {
2530 recent_timestamp = entry.timestamp;
2531 recent_item = Some(typed_item);
2532 }
2533 }
2534 }
2535 recent_item
2536 }
2537
2538 pub fn recent_navigation_history_iter(
2539 &self,
2540 cx: &App,
2541 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2542 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2543 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2544
2545 for pane in &self.panes {
2546 let pane = pane.read(cx);
2547
2548 pane.nav_history()
2549 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2550 if let Some(fs_path) = &fs_path {
2551 abs_paths_opened
2552 .entry(fs_path.clone())
2553 .or_default()
2554 .insert(project_path.clone());
2555 }
2556 let timestamp = entry.timestamp;
2557 match history.entry(project_path) {
2558 hash_map::Entry::Occupied(mut entry) => {
2559 let (_, old_timestamp) = entry.get();
2560 if ×tamp > old_timestamp {
2561 entry.insert((fs_path, timestamp));
2562 }
2563 }
2564 hash_map::Entry::Vacant(entry) => {
2565 entry.insert((fs_path, timestamp));
2566 }
2567 }
2568 });
2569
2570 if let Some(item) = pane.active_item()
2571 && let Some(project_path) = item.project_path(cx)
2572 {
2573 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2574
2575 if let Some(fs_path) = &fs_path {
2576 abs_paths_opened
2577 .entry(fs_path.clone())
2578 .or_default()
2579 .insert(project_path.clone());
2580 }
2581
2582 history.insert(project_path, (fs_path, std::usize::MAX));
2583 }
2584 }
2585
2586 history
2587 .into_iter()
2588 .sorted_by_key(|(_, (_, order))| *order)
2589 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2590 .rev()
2591 .filter(move |(history_path, abs_path)| {
2592 let latest_project_path_opened = abs_path
2593 .as_ref()
2594 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2595 .and_then(|project_paths| {
2596 project_paths
2597 .iter()
2598 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2599 });
2600
2601 latest_project_path_opened.is_none_or(|path| path == history_path)
2602 })
2603 }
2604
2605 pub fn recent_navigation_history(
2606 &self,
2607 limit: Option<usize>,
2608 cx: &App,
2609 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2610 self.recent_navigation_history_iter(cx)
2611 .take(limit.unwrap_or(usize::MAX))
2612 .collect()
2613 }
2614
2615 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2616 for pane in &self.panes {
2617 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2618 }
2619 }
2620
2621 fn navigate_history(
2622 &mut self,
2623 pane: WeakEntity<Pane>,
2624 mode: NavigationMode,
2625 window: &mut Window,
2626 cx: &mut Context<Workspace>,
2627 ) -> Task<Result<()>> {
2628 self.navigate_history_impl(
2629 pane,
2630 mode,
2631 window,
2632 &mut |history, cx| history.pop(mode, cx),
2633 cx,
2634 )
2635 }
2636
2637 fn navigate_tag_history(
2638 &mut self,
2639 pane: WeakEntity<Pane>,
2640 mode: TagNavigationMode,
2641 window: &mut Window,
2642 cx: &mut Context<Workspace>,
2643 ) -> Task<Result<()>> {
2644 self.navigate_history_impl(
2645 pane,
2646 NavigationMode::Normal,
2647 window,
2648 &mut |history, _cx| history.pop_tag(mode),
2649 cx,
2650 )
2651 }
2652
2653 fn navigate_history_impl(
2654 &mut self,
2655 pane: WeakEntity<Pane>,
2656 mode: NavigationMode,
2657 window: &mut Window,
2658 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2659 cx: &mut Context<Workspace>,
2660 ) -> Task<Result<()>> {
2661 let to_load = if let Some(pane) = pane.upgrade() {
2662 pane.update(cx, |pane, cx| {
2663 window.focus(&pane.focus_handle(cx), cx);
2664 loop {
2665 // Retrieve the weak item handle from the history.
2666 let entry = cb(pane.nav_history_mut(), cx)?;
2667
2668 // If the item is still present in this pane, then activate it.
2669 if let Some(index) = entry
2670 .item
2671 .upgrade()
2672 .and_then(|v| pane.index_for_item(v.as_ref()))
2673 {
2674 let prev_active_item_index = pane.active_item_index();
2675 pane.nav_history_mut().set_mode(mode);
2676 pane.activate_item(index, true, true, window, cx);
2677 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2678
2679 let mut navigated = prev_active_item_index != pane.active_item_index();
2680 if let Some(data) = entry.data {
2681 navigated |= pane.active_item()?.navigate(data, window, cx);
2682 }
2683
2684 if navigated {
2685 break None;
2686 }
2687 } else {
2688 // If the item is no longer present in this pane, then retrieve its
2689 // path info in order to reopen it.
2690 break pane
2691 .nav_history()
2692 .path_for_item(entry.item.id())
2693 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2694 }
2695 }
2696 })
2697 } else {
2698 None
2699 };
2700
2701 if let Some((project_path, abs_path, entry)) = to_load {
2702 // If the item was no longer present, then load it again from its previous path, first try the local path
2703 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2704
2705 cx.spawn_in(window, async move |workspace, cx| {
2706 let open_by_project_path = open_by_project_path.await;
2707 let mut navigated = false;
2708 match open_by_project_path
2709 .with_context(|| format!("Navigating to {project_path:?}"))
2710 {
2711 Ok((project_entry_id, build_item)) => {
2712 let prev_active_item_id = pane.update(cx, |pane, _| {
2713 pane.nav_history_mut().set_mode(mode);
2714 pane.active_item().map(|p| p.item_id())
2715 })?;
2716
2717 pane.update_in(cx, |pane, window, cx| {
2718 let item = pane.open_item(
2719 project_entry_id,
2720 project_path,
2721 true,
2722 entry.is_preview,
2723 true,
2724 None,
2725 window, cx,
2726 build_item,
2727 );
2728 navigated |= Some(item.item_id()) != prev_active_item_id;
2729 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2730 if let Some(data) = entry.data {
2731 navigated |= item.navigate(data, window, cx);
2732 }
2733 })?;
2734 }
2735 Err(open_by_project_path_e) => {
2736 // Fall back to opening by abs path, in case an external file was opened and closed,
2737 // and its worktree is now dropped
2738 if let Some(abs_path) = abs_path {
2739 let prev_active_item_id = pane.update(cx, |pane, _| {
2740 pane.nav_history_mut().set_mode(mode);
2741 pane.active_item().map(|p| p.item_id())
2742 })?;
2743 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2744 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2745 })?;
2746 match open_by_abs_path
2747 .await
2748 .with_context(|| format!("Navigating to {abs_path:?}"))
2749 {
2750 Ok(item) => {
2751 pane.update_in(cx, |pane, window, cx| {
2752 navigated |= Some(item.item_id()) != prev_active_item_id;
2753 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2754 if let Some(data) = entry.data {
2755 navigated |= item.navigate(data, window, cx);
2756 }
2757 })?;
2758 }
2759 Err(open_by_abs_path_e) => {
2760 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2761 }
2762 }
2763 }
2764 }
2765 }
2766
2767 if !navigated {
2768 workspace
2769 .update_in(cx, |workspace, window, cx| {
2770 Self::navigate_history(workspace, pane, mode, window, cx)
2771 })?
2772 .await?;
2773 }
2774
2775 Ok(())
2776 })
2777 } else {
2778 Task::ready(Ok(()))
2779 }
2780 }
2781
2782 pub fn go_back(
2783 &mut self,
2784 pane: WeakEntity<Pane>,
2785 window: &mut Window,
2786 cx: &mut Context<Workspace>,
2787 ) -> Task<Result<()>> {
2788 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2789 }
2790
2791 pub fn go_forward(
2792 &mut self,
2793 pane: WeakEntity<Pane>,
2794 window: &mut Window,
2795 cx: &mut Context<Workspace>,
2796 ) -> Task<Result<()>> {
2797 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2798 }
2799
2800 pub fn reopen_closed_item(
2801 &mut self,
2802 window: &mut Window,
2803 cx: &mut Context<Workspace>,
2804 ) -> Task<Result<()>> {
2805 self.navigate_history(
2806 self.active_pane().downgrade(),
2807 NavigationMode::ReopeningClosedItem,
2808 window,
2809 cx,
2810 )
2811 }
2812
2813 pub fn client(&self) -> &Arc<Client> {
2814 &self.app_state.client
2815 }
2816
2817 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2818 self.titlebar_item = Some(item);
2819 cx.notify();
2820 }
2821
2822 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2823 self.on_prompt_for_new_path = Some(prompt)
2824 }
2825
2826 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2827 self.on_prompt_for_open_path = Some(prompt)
2828 }
2829
2830 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2831 self.terminal_provider = Some(Box::new(provider));
2832 }
2833
2834 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2835 self.debugger_provider = Some(Arc::new(provider));
2836 }
2837
2838 pub fn set_open_in_dev_container(&mut self, value: bool) {
2839 self.open_in_dev_container = value;
2840 }
2841
2842 pub fn open_in_dev_container(&self) -> bool {
2843 self.open_in_dev_container
2844 }
2845
2846 pub fn set_dev_container_task(&mut self, task: Task<Result<()>>) {
2847 self._dev_container_task = Some(task);
2848 }
2849
2850 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2851 self.debugger_provider.clone()
2852 }
2853
2854 pub fn prompt_for_open_path(
2855 &mut self,
2856 path_prompt_options: PathPromptOptions,
2857 lister: DirectoryLister,
2858 window: &mut Window,
2859 cx: &mut Context<Self>,
2860 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2861 // TODO: If `on_prompt_for_open_path` is set, we should always use it
2862 // rather than gating on `use_system_path_prompts`. This would let tests
2863 // inject a mock without also having to disable the setting.
2864 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2865 let prompt = self.on_prompt_for_open_path.take().unwrap();
2866 let rx = prompt(self, lister, window, cx);
2867 self.on_prompt_for_open_path = Some(prompt);
2868 rx
2869 } else {
2870 let (tx, rx) = oneshot::channel();
2871 let abs_path = cx.prompt_for_paths(path_prompt_options);
2872
2873 cx.spawn_in(window, async move |workspace, cx| {
2874 let Ok(result) = abs_path.await else {
2875 return Ok(());
2876 };
2877
2878 match result {
2879 Ok(result) => {
2880 tx.send(result).ok();
2881 }
2882 Err(err) => {
2883 let rx = workspace.update_in(cx, |workspace, window, cx| {
2884 workspace.show_portal_error(err.to_string(), cx);
2885 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2886 let rx = prompt(workspace, lister, window, cx);
2887 workspace.on_prompt_for_open_path = Some(prompt);
2888 rx
2889 })?;
2890 if let Ok(path) = rx.await {
2891 tx.send(path).ok();
2892 }
2893 }
2894 };
2895 anyhow::Ok(())
2896 })
2897 .detach();
2898
2899 rx
2900 }
2901 }
2902
2903 pub fn prompt_for_new_path(
2904 &mut self,
2905 lister: DirectoryLister,
2906 suggested_name: Option<String>,
2907 window: &mut Window,
2908 cx: &mut Context<Self>,
2909 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2910 if self.project.read(cx).is_via_collab()
2911 || self.project.read(cx).is_via_remote_server()
2912 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2913 {
2914 let prompt = self.on_prompt_for_new_path.take().unwrap();
2915 let rx = prompt(self, lister, suggested_name, window, cx);
2916 self.on_prompt_for_new_path = Some(prompt);
2917 return rx;
2918 }
2919
2920 let (tx, rx) = oneshot::channel();
2921 cx.spawn_in(window, async move |workspace, cx| {
2922 let abs_path = workspace.update(cx, |workspace, cx| {
2923 let relative_to = workspace
2924 .most_recent_active_path(cx)
2925 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2926 .or_else(|| {
2927 let project = workspace.project.read(cx);
2928 project.visible_worktrees(cx).find_map(|worktree| {
2929 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2930 })
2931 })
2932 .or_else(std::env::home_dir)
2933 .unwrap_or_else(|| PathBuf::from(""));
2934 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2935 })?;
2936 let abs_path = match abs_path.await? {
2937 Ok(path) => path,
2938 Err(err) => {
2939 let rx = workspace.update_in(cx, |workspace, window, cx| {
2940 workspace.show_portal_error(err.to_string(), cx);
2941
2942 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2943 let rx = prompt(workspace, lister, suggested_name, window, cx);
2944 workspace.on_prompt_for_new_path = Some(prompt);
2945 rx
2946 })?;
2947 if let Ok(path) = rx.await {
2948 tx.send(path).ok();
2949 }
2950 return anyhow::Ok(());
2951 }
2952 };
2953
2954 tx.send(abs_path.map(|path| vec![path])).ok();
2955 anyhow::Ok(())
2956 })
2957 .detach();
2958
2959 rx
2960 }
2961
2962 pub fn titlebar_item(&self) -> Option<AnyView> {
2963 self.titlebar_item.clone()
2964 }
2965
2966 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2967 ///
2968 /// If the given workspace has a local project, then it will be passed
2969 /// to the callback. Otherwise, a new empty window will be created.
2970 pub fn with_local_workspace<T, F>(
2971 &mut self,
2972 window: &mut Window,
2973 cx: &mut Context<Self>,
2974 callback: F,
2975 ) -> Task<Result<T>>
2976 where
2977 T: 'static,
2978 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2979 {
2980 if self.project.read(cx).is_local() {
2981 Task::ready(Ok(callback(self, window, cx)))
2982 } else {
2983 let env = self.project.read(cx).cli_environment(cx);
2984 let task = Self::new_local(
2985 Vec::new(),
2986 self.app_state.clone(),
2987 None,
2988 env,
2989 None,
2990 OpenMode::Activate,
2991 cx,
2992 );
2993 cx.spawn_in(window, async move |_vh, cx| {
2994 let OpenResult {
2995 window: multi_workspace_window,
2996 ..
2997 } = task.await?;
2998 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2999 let workspace = multi_workspace.workspace().clone();
3000 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
3001 })
3002 })
3003 }
3004 }
3005
3006 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
3007 ///
3008 /// If the given workspace has a local project, then it will be passed
3009 /// to the callback. Otherwise, a new empty window will be created.
3010 pub fn with_local_or_wsl_workspace<T, F>(
3011 &mut self,
3012 window: &mut Window,
3013 cx: &mut Context<Self>,
3014 callback: F,
3015 ) -> Task<Result<T>>
3016 where
3017 T: 'static,
3018 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
3019 {
3020 let project = self.project.read(cx);
3021 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
3022 Task::ready(Ok(callback(self, window, cx)))
3023 } else {
3024 let env = self.project.read(cx).cli_environment(cx);
3025 let task = Self::new_local(
3026 Vec::new(),
3027 self.app_state.clone(),
3028 None,
3029 env,
3030 None,
3031 OpenMode::Activate,
3032 cx,
3033 );
3034 cx.spawn_in(window, async move |_vh, cx| {
3035 let OpenResult {
3036 window: multi_workspace_window,
3037 ..
3038 } = task.await?;
3039 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
3040 let workspace = multi_workspace.workspace().clone();
3041 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
3042 })
3043 })
3044 }
3045 }
3046
3047 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3048 self.project.read(cx).worktrees(cx)
3049 }
3050
3051 pub fn visible_worktrees<'a>(
3052 &self,
3053 cx: &'a App,
3054 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3055 self.project.read(cx).visible_worktrees(cx)
3056 }
3057
3058 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
3059 let futures = self
3060 .worktrees(cx)
3061 .filter_map(|worktree| worktree.read(cx).as_local())
3062 .map(|worktree| worktree.scan_complete())
3063 .collect::<Vec<_>>();
3064 async move {
3065 for future in futures {
3066 future.await;
3067 }
3068 }
3069 }
3070
3071 pub fn close_global(cx: &mut App) {
3072 cx.defer(|cx| {
3073 cx.windows().iter().find(|window| {
3074 window
3075 .update(cx, |_, window, _| {
3076 if window.is_window_active() {
3077 //This can only get called when the window's project connection has been lost
3078 //so we don't need to prompt the user for anything and instead just close the window
3079 window.remove_window();
3080 true
3081 } else {
3082 false
3083 }
3084 })
3085 .unwrap_or(false)
3086 });
3087 });
3088 }
3089
3090 pub fn move_focused_panel_to_next_position(
3091 &mut self,
3092 _: &MoveFocusedPanelToNextPosition,
3093 window: &mut Window,
3094 cx: &mut Context<Self>,
3095 ) {
3096 let docks = self.all_docks();
3097 let active_dock = docks
3098 .into_iter()
3099 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
3100
3101 if let Some(dock) = active_dock {
3102 dock.update(cx, |dock, cx| {
3103 let active_panel = dock
3104 .active_panel()
3105 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
3106
3107 if let Some(panel) = active_panel {
3108 panel.move_to_next_position(window, cx);
3109 }
3110 })
3111 }
3112 }
3113
3114 pub fn prepare_to_close(
3115 &mut self,
3116 close_intent: CloseIntent,
3117 window: &mut Window,
3118 cx: &mut Context<Self>,
3119 ) -> Task<Result<bool>> {
3120 let active_call = self.active_global_call();
3121
3122 cx.spawn_in(window, async move |this, cx| {
3123 this.update(cx, |this, _| {
3124 if close_intent == CloseIntent::CloseWindow {
3125 this.removing = true;
3126 }
3127 })?;
3128
3129 let workspace_count = cx.update(|_window, cx| {
3130 cx.windows()
3131 .iter()
3132 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
3133 .count()
3134 })?;
3135
3136 #[cfg(target_os = "macos")]
3137 let save_last_workspace = false;
3138
3139 // On Linux and Windows, closing the last window should restore the last workspace.
3140 #[cfg(not(target_os = "macos"))]
3141 let save_last_workspace = {
3142 let remaining_workspaces = cx.update(|_window, cx| {
3143 cx.windows()
3144 .iter()
3145 .filter_map(|window| window.downcast::<MultiWorkspace>())
3146 .filter_map(|multi_workspace| {
3147 multi_workspace
3148 .update(cx, |multi_workspace, _, cx| {
3149 multi_workspace.workspace().read(cx).removing
3150 })
3151 .ok()
3152 })
3153 .filter(|removing| !removing)
3154 .count()
3155 })?;
3156
3157 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
3158 };
3159
3160 if let Some(active_call) = active_call
3161 && workspace_count == 1
3162 && cx
3163 .update(|_window, cx| active_call.0.is_in_room(cx))
3164 .unwrap_or(false)
3165 {
3166 if close_intent == CloseIntent::CloseWindow {
3167 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
3168 let answer = cx.update(|window, cx| {
3169 window.prompt(
3170 PromptLevel::Warning,
3171 "Do you want to leave the current call?",
3172 None,
3173 &["Close window and hang up", "Cancel"],
3174 cx,
3175 )
3176 })?;
3177
3178 if answer.await.log_err() == Some(1) {
3179 return anyhow::Ok(false);
3180 } else {
3181 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
3182 task.await.log_err();
3183 }
3184 }
3185 }
3186 if close_intent == CloseIntent::ReplaceWindow {
3187 _ = cx.update(|_window, cx| {
3188 let multi_workspace = cx
3189 .windows()
3190 .iter()
3191 .filter_map(|window| window.downcast::<MultiWorkspace>())
3192 .next()
3193 .unwrap();
3194 let project = multi_workspace
3195 .read(cx)?
3196 .workspace()
3197 .read(cx)
3198 .project
3199 .clone();
3200 if project.read(cx).is_shared() {
3201 active_call.0.unshare_project(project, cx)?;
3202 }
3203 Ok::<_, anyhow::Error>(())
3204 });
3205 }
3206 }
3207
3208 let save_result = this
3209 .update_in(cx, |this, window, cx| {
3210 this.save_all_internal(SaveIntent::Close, window, cx)
3211 })?
3212 .await;
3213
3214 // If we're not quitting, but closing, we remove the workspace from
3215 // the current session.
3216 if close_intent != CloseIntent::Quit
3217 && !save_last_workspace
3218 && save_result.as_ref().is_ok_and(|&res| res)
3219 {
3220 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
3221 .await;
3222 }
3223
3224 save_result
3225 })
3226 }
3227
3228 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
3229 self.save_all_internal(
3230 action.save_intent.unwrap_or(SaveIntent::SaveAll),
3231 window,
3232 cx,
3233 )
3234 .detach_and_log_err(cx);
3235 }
3236
3237 fn send_keystrokes(
3238 &mut self,
3239 action: &SendKeystrokes,
3240 window: &mut Window,
3241 cx: &mut Context<Self>,
3242 ) {
3243 let keystrokes: Vec<Keystroke> = action
3244 .0
3245 .split(' ')
3246 .flat_map(|k| Keystroke::parse(k).log_err())
3247 .map(|k| {
3248 cx.keyboard_mapper()
3249 .map_key_equivalent(k, false)
3250 .inner()
3251 .clone()
3252 })
3253 .collect();
3254 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
3255 }
3256
3257 pub fn send_keystrokes_impl(
3258 &mut self,
3259 keystrokes: Vec<Keystroke>,
3260 window: &mut Window,
3261 cx: &mut Context<Self>,
3262 ) -> Shared<Task<()>> {
3263 let mut state = self.dispatching_keystrokes.borrow_mut();
3264 if !state.dispatched.insert(keystrokes.clone()) {
3265 cx.propagate();
3266 return state.task.clone().unwrap();
3267 }
3268
3269 state.queue.extend(keystrokes);
3270
3271 let keystrokes = self.dispatching_keystrokes.clone();
3272 if state.task.is_none() {
3273 state.task = Some(
3274 window
3275 .spawn(cx, async move |cx| {
3276 // limit to 100 keystrokes to avoid infinite recursion.
3277 for _ in 0..100 {
3278 let keystroke = {
3279 let mut state = keystrokes.borrow_mut();
3280 let Some(keystroke) = state.queue.pop_front() else {
3281 state.dispatched.clear();
3282 state.task.take();
3283 return;
3284 };
3285 keystroke
3286 };
3287 cx.update(|window, cx| {
3288 let focused = window.focused(cx);
3289 window.dispatch_keystroke(keystroke.clone(), cx);
3290 if window.focused(cx) != focused {
3291 // dispatch_keystroke may cause the focus to change.
3292 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
3293 // And we need that to happen before the next keystroke to keep vim mode happy...
3294 // (Note that the tests always do this implicitly, so you must manually test with something like:
3295 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
3296 // )
3297 window.draw(cx).clear();
3298 }
3299 })
3300 .ok();
3301
3302 // Yield between synthetic keystrokes so deferred focus and
3303 // other effects can settle before dispatching the next key.
3304 yield_now().await;
3305 }
3306
3307 *keystrokes.borrow_mut() = Default::default();
3308 log::error!("over 100 keystrokes passed to send_keystrokes");
3309 })
3310 .shared(),
3311 );
3312 }
3313 state.task.clone().unwrap()
3314 }
3315
3316 /// Prompts the user to save or discard each dirty item, returning
3317 /// `true` if they confirmed (saved/discarded everything) or `false`
3318 /// if they cancelled. Used before removing worktree roots during
3319 /// thread archival.
3320 pub fn prompt_to_save_or_discard_dirty_items(
3321 &mut self,
3322 window: &mut Window,
3323 cx: &mut Context<Self>,
3324 ) -> Task<Result<bool>> {
3325 self.save_all_internal(SaveIntent::Close, window, cx)
3326 }
3327
3328 fn save_all_internal(
3329 &mut self,
3330 mut save_intent: SaveIntent,
3331 window: &mut Window,
3332 cx: &mut Context<Self>,
3333 ) -> Task<Result<bool>> {
3334 if self.project.read(cx).is_disconnected(cx) {
3335 return Task::ready(Ok(true));
3336 }
3337 let dirty_items = self
3338 .panes
3339 .iter()
3340 .flat_map(|pane| {
3341 pane.read(cx).items().filter_map(|item| {
3342 if item.is_dirty(cx) {
3343 item.tab_content_text(0, cx);
3344 Some((pane.downgrade(), item.boxed_clone()))
3345 } else {
3346 None
3347 }
3348 })
3349 })
3350 .collect::<Vec<_>>();
3351
3352 let project = self.project.clone();
3353 cx.spawn_in(window, async move |workspace, cx| {
3354 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3355 let (serialize_tasks, remaining_dirty_items) =
3356 workspace.update_in(cx, |workspace, window, cx| {
3357 let mut remaining_dirty_items = Vec::new();
3358 let mut serialize_tasks = Vec::new();
3359 for (pane, item) in dirty_items {
3360 if let Some(task) = item
3361 .to_serializable_item_handle(cx)
3362 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3363 {
3364 serialize_tasks.push(task);
3365 } else {
3366 remaining_dirty_items.push((pane, item));
3367 }
3368 }
3369 (serialize_tasks, remaining_dirty_items)
3370 })?;
3371
3372 futures::future::try_join_all(serialize_tasks).await?;
3373
3374 if !remaining_dirty_items.is_empty() {
3375 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3376 }
3377
3378 if remaining_dirty_items.len() > 1 {
3379 let answer = workspace.update_in(cx, |_, window, cx| {
3380 cx.emit(Event::Activate);
3381 let detail = Pane::file_names_for_prompt(
3382 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3383 cx,
3384 );
3385 window.prompt(
3386 PromptLevel::Warning,
3387 "Do you want to save all changes in the following files?",
3388 Some(&detail),
3389 &["Save all", "Discard all", "Cancel"],
3390 cx,
3391 )
3392 })?;
3393 match answer.await.log_err() {
3394 Some(0) => save_intent = SaveIntent::SaveAll,
3395 Some(1) => save_intent = SaveIntent::Skip,
3396 Some(2) => return Ok(false),
3397 _ => {}
3398 }
3399 }
3400
3401 remaining_dirty_items
3402 } else {
3403 dirty_items
3404 };
3405
3406 for (pane, item) in dirty_items {
3407 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3408 (
3409 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3410 item.project_entry_ids(cx),
3411 )
3412 })?;
3413 if (singleton || !project_entry_ids.is_empty())
3414 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3415 {
3416 return Ok(false);
3417 }
3418 }
3419 Ok(true)
3420 })
3421 }
3422
3423 pub fn open_workspace_for_paths(
3424 &mut self,
3425 // replace_current_window: bool,
3426 mut open_mode: OpenMode,
3427 paths: Vec<PathBuf>,
3428 window: &mut Window,
3429 cx: &mut Context<Self>,
3430 ) -> Task<Result<Entity<Workspace>>> {
3431 let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
3432 let is_remote = self.project.read(cx).is_via_collab();
3433 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3434 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3435
3436 let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
3437 if workspace_is_empty {
3438 open_mode = OpenMode::Activate;
3439 }
3440
3441 let app_state = self.app_state.clone();
3442
3443 cx.spawn(async move |_, cx| {
3444 let OpenResult { workspace, .. } = cx
3445 .update(|cx| {
3446 open_paths(
3447 &paths,
3448 app_state,
3449 OpenOptions {
3450 requesting_window,
3451 open_mode,
3452 ..Default::default()
3453 },
3454 cx,
3455 )
3456 })
3457 .await?;
3458 Ok(workspace)
3459 })
3460 }
3461
3462 #[allow(clippy::type_complexity)]
3463 pub fn open_paths(
3464 &mut self,
3465 mut abs_paths: Vec<PathBuf>,
3466 options: OpenOptions,
3467 pane: Option<WeakEntity<Pane>>,
3468 window: &mut Window,
3469 cx: &mut Context<Self>,
3470 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3471 let fs = self.app_state.fs.clone();
3472
3473 let caller_ordered_abs_paths = abs_paths.clone();
3474
3475 // Sort the paths to ensure we add worktrees for parents before their children.
3476 abs_paths.sort_unstable();
3477 cx.spawn_in(window, async move |this, cx| {
3478 let mut tasks = Vec::with_capacity(abs_paths.len());
3479
3480 for abs_path in &abs_paths {
3481 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3482 OpenVisible::All => Some(true),
3483 OpenVisible::None => Some(false),
3484 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3485 Some(Some(metadata)) => Some(!metadata.is_dir),
3486 Some(None) => Some(true),
3487 None => None,
3488 },
3489 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3490 Some(Some(metadata)) => Some(metadata.is_dir),
3491 Some(None) => Some(false),
3492 None => None,
3493 },
3494 };
3495 let project_path = match visible {
3496 Some(visible) => match this
3497 .update(cx, |this, cx| {
3498 Workspace::project_path_for_path(
3499 this.project.clone(),
3500 abs_path,
3501 visible,
3502 cx,
3503 )
3504 })
3505 .log_err()
3506 {
3507 Some(project_path) => project_path.await.log_err(),
3508 None => None,
3509 },
3510 None => None,
3511 };
3512
3513 let this = this.clone();
3514 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3515 let fs = fs.clone();
3516 let pane = pane.clone();
3517 let task = cx.spawn(async move |cx| {
3518 let (_worktree, project_path) = project_path?;
3519 if fs.is_dir(&abs_path).await {
3520 // Opening a directory should not race to update the active entry.
3521 // We'll select/reveal a deterministic final entry after all paths finish opening.
3522 None
3523 } else {
3524 Some(
3525 this.update_in(cx, |this, window, cx| {
3526 this.open_path(
3527 project_path,
3528 pane,
3529 options.focus.unwrap_or(true),
3530 window,
3531 cx,
3532 )
3533 })
3534 .ok()?
3535 .await,
3536 )
3537 }
3538 });
3539 tasks.push(task);
3540 }
3541
3542 let results = futures::future::join_all(tasks).await;
3543
3544 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3545 let mut winner: Option<(PathBuf, bool)> = None;
3546 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3547 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3548 if !metadata.is_dir {
3549 winner = Some((abs_path, false));
3550 break;
3551 }
3552 if winner.is_none() {
3553 winner = Some((abs_path, true));
3554 }
3555 } else if winner.is_none() {
3556 winner = Some((abs_path, false));
3557 }
3558 }
3559
3560 // Compute the winner entry id on the foreground thread and emit once, after all
3561 // paths finish opening. This avoids races between concurrently-opening paths
3562 // (directories in particular) and makes the resulting project panel selection
3563 // deterministic.
3564 if let Some((winner_abs_path, winner_is_dir)) = winner {
3565 'emit_winner: {
3566 let winner_abs_path: Arc<Path> =
3567 SanitizedPath::new(&winner_abs_path).as_path().into();
3568
3569 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3570 OpenVisible::All => true,
3571 OpenVisible::None => false,
3572 OpenVisible::OnlyFiles => !winner_is_dir,
3573 OpenVisible::OnlyDirectories => winner_is_dir,
3574 };
3575
3576 let Some(worktree_task) = this
3577 .update(cx, |workspace, cx| {
3578 workspace.project.update(cx, |project, cx| {
3579 project.find_or_create_worktree(
3580 winner_abs_path.as_ref(),
3581 visible,
3582 cx,
3583 )
3584 })
3585 })
3586 .ok()
3587 else {
3588 break 'emit_winner;
3589 };
3590
3591 let Ok((worktree, _)) = worktree_task.await else {
3592 break 'emit_winner;
3593 };
3594
3595 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3596 let worktree = worktree.read(cx);
3597 let worktree_abs_path = worktree.abs_path();
3598 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3599 worktree.root_entry()
3600 } else {
3601 winner_abs_path
3602 .strip_prefix(worktree_abs_path.as_ref())
3603 .ok()
3604 .and_then(|relative_path| {
3605 let relative_path =
3606 RelPath::new(relative_path, PathStyle::local())
3607 .log_err()?;
3608 worktree.entry_for_path(&relative_path)
3609 })
3610 }?;
3611 Some(entry.id)
3612 }) else {
3613 break 'emit_winner;
3614 };
3615
3616 this.update(cx, |workspace, cx| {
3617 workspace.project.update(cx, |_, cx| {
3618 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3619 });
3620 })
3621 .ok();
3622 }
3623 }
3624
3625 results
3626 })
3627 }
3628
3629 pub fn open_resolved_path(
3630 &mut self,
3631 path: ResolvedPath,
3632 window: &mut Window,
3633 cx: &mut Context<Self>,
3634 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3635 match path {
3636 ResolvedPath::ProjectPath { project_path, .. } => {
3637 self.open_path(project_path, None, true, window, cx)
3638 }
3639 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3640 PathBuf::from(path),
3641 OpenOptions {
3642 visible: Some(OpenVisible::None),
3643 ..Default::default()
3644 },
3645 window,
3646 cx,
3647 ),
3648 }
3649 }
3650
3651 pub fn absolute_path_of_worktree(
3652 &self,
3653 worktree_id: WorktreeId,
3654 cx: &mut Context<Self>,
3655 ) -> Option<PathBuf> {
3656 self.project
3657 .read(cx)
3658 .worktree_for_id(worktree_id, cx)
3659 // TODO: use `abs_path` or `root_dir`
3660 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3661 }
3662
3663 pub fn add_folder_to_project(
3664 &mut self,
3665 _: &AddFolderToProject,
3666 window: &mut Window,
3667 cx: &mut Context<Self>,
3668 ) {
3669 let project = self.project.read(cx);
3670 if project.is_via_collab() {
3671 self.show_error(
3672 &anyhow!("You cannot add folders to someone else's project"),
3673 cx,
3674 );
3675 return;
3676 }
3677 let paths = self.prompt_for_open_path(
3678 PathPromptOptions {
3679 files: false,
3680 directories: true,
3681 multiple: true,
3682 prompt: None,
3683 },
3684 DirectoryLister::Project(self.project.clone()),
3685 window,
3686 cx,
3687 );
3688 cx.spawn_in(window, async move |this, cx| {
3689 if let Some(paths) = paths.await.log_err().flatten() {
3690 let results = this
3691 .update_in(cx, |this, window, cx| {
3692 this.open_paths(
3693 paths,
3694 OpenOptions {
3695 visible: Some(OpenVisible::All),
3696 ..Default::default()
3697 },
3698 None,
3699 window,
3700 cx,
3701 )
3702 })?
3703 .await;
3704 for result in results.into_iter().flatten() {
3705 result.log_err();
3706 }
3707 }
3708 anyhow::Ok(())
3709 })
3710 .detach_and_log_err(cx);
3711 }
3712
3713 pub fn project_path_for_path(
3714 project: Entity<Project>,
3715 abs_path: &Path,
3716 visible: bool,
3717 cx: &mut App,
3718 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3719 let entry = project.update(cx, |project, cx| {
3720 project.find_or_create_worktree(abs_path, visible, cx)
3721 });
3722 cx.spawn(async move |cx| {
3723 let (worktree, path) = entry.await?;
3724 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3725 Ok((worktree, ProjectPath { worktree_id, path }))
3726 })
3727 }
3728
3729 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3730 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3731 }
3732
3733 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3734 self.items_of_type(cx).max_by_key(|item| item.item_id())
3735 }
3736
3737 pub fn items_of_type<'a, T: Item>(
3738 &'a self,
3739 cx: &'a App,
3740 ) -> impl 'a + Iterator<Item = Entity<T>> {
3741 self.panes
3742 .iter()
3743 .flat_map(|pane| pane.read(cx).items_of_type())
3744 }
3745
3746 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3747 self.active_pane().read(cx).active_item()
3748 }
3749
3750 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3751 let item = self.active_item(cx)?;
3752 item.to_any_view().downcast::<I>().ok()
3753 }
3754
3755 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3756 self.active_item(cx).and_then(|item| item.project_path(cx))
3757 }
3758
3759 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3760 self.recent_navigation_history_iter(cx)
3761 .filter_map(|(path, abs_path)| {
3762 let worktree = self
3763 .project
3764 .read(cx)
3765 .worktree_for_id(path.worktree_id, cx)?;
3766 if worktree.read(cx).is_visible() {
3767 abs_path
3768 } else {
3769 None
3770 }
3771 })
3772 .next()
3773 }
3774
3775 pub fn save_active_item(
3776 &mut self,
3777 save_intent: SaveIntent,
3778 window: &mut Window,
3779 cx: &mut App,
3780 ) -> Task<Result<()>> {
3781 let project = self.project.clone();
3782 let pane = self.active_pane();
3783 let item = pane.read(cx).active_item();
3784 let pane = pane.downgrade();
3785
3786 window.spawn(cx, async move |cx| {
3787 if let Some(item) = item {
3788 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3789 .await
3790 .map(|_| ())
3791 } else {
3792 Ok(())
3793 }
3794 })
3795 }
3796
3797 pub fn close_inactive_items_and_panes(
3798 &mut self,
3799 action: &CloseInactiveTabsAndPanes,
3800 window: &mut Window,
3801 cx: &mut Context<Self>,
3802 ) {
3803 if let Some(task) = self.close_all_internal(
3804 true,
3805 action.save_intent.unwrap_or(SaveIntent::Close),
3806 window,
3807 cx,
3808 ) {
3809 task.detach_and_log_err(cx)
3810 }
3811 }
3812
3813 pub fn close_all_items_and_panes(
3814 &mut self,
3815 action: &CloseAllItemsAndPanes,
3816 window: &mut Window,
3817 cx: &mut Context<Self>,
3818 ) {
3819 if let Some(task) = self.close_all_internal(
3820 false,
3821 action.save_intent.unwrap_or(SaveIntent::Close),
3822 window,
3823 cx,
3824 ) {
3825 task.detach_and_log_err(cx)
3826 }
3827 }
3828
3829 /// Closes the active item across all panes.
3830 pub fn close_item_in_all_panes(
3831 &mut self,
3832 action: &CloseItemInAllPanes,
3833 window: &mut Window,
3834 cx: &mut Context<Self>,
3835 ) {
3836 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3837 return;
3838 };
3839
3840 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3841 let close_pinned = action.close_pinned;
3842
3843 if let Some(project_path) = active_item.project_path(cx) {
3844 self.close_items_with_project_path(
3845 &project_path,
3846 save_intent,
3847 close_pinned,
3848 window,
3849 cx,
3850 );
3851 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3852 let item_id = active_item.item_id();
3853 self.active_pane().update(cx, |pane, cx| {
3854 pane.close_item_by_id(item_id, save_intent, window, cx)
3855 .detach_and_log_err(cx);
3856 });
3857 }
3858 }
3859
3860 /// Closes all items with the given project path across all panes.
3861 pub fn close_items_with_project_path(
3862 &mut self,
3863 project_path: &ProjectPath,
3864 save_intent: SaveIntent,
3865 close_pinned: bool,
3866 window: &mut Window,
3867 cx: &mut Context<Self>,
3868 ) {
3869 let panes = self.panes().to_vec();
3870 for pane in panes {
3871 pane.update(cx, |pane, cx| {
3872 pane.close_items_for_project_path(
3873 project_path,
3874 save_intent,
3875 close_pinned,
3876 window,
3877 cx,
3878 )
3879 .detach_and_log_err(cx);
3880 });
3881 }
3882 }
3883
3884 fn close_all_internal(
3885 &mut self,
3886 retain_active_pane: bool,
3887 save_intent: SaveIntent,
3888 window: &mut Window,
3889 cx: &mut Context<Self>,
3890 ) -> Option<Task<Result<()>>> {
3891 let current_pane = self.active_pane();
3892
3893 let mut tasks = Vec::new();
3894
3895 if retain_active_pane {
3896 let current_pane_close = current_pane.update(cx, |pane, cx| {
3897 pane.close_other_items(
3898 &CloseOtherItems {
3899 save_intent: None,
3900 close_pinned: false,
3901 },
3902 None,
3903 window,
3904 cx,
3905 )
3906 });
3907
3908 tasks.push(current_pane_close);
3909 }
3910
3911 for pane in self.panes() {
3912 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3913 continue;
3914 }
3915
3916 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3917 pane.close_all_items(
3918 &CloseAllItems {
3919 save_intent: Some(save_intent),
3920 close_pinned: false,
3921 },
3922 window,
3923 cx,
3924 )
3925 });
3926
3927 tasks.push(close_pane_items)
3928 }
3929
3930 if tasks.is_empty() {
3931 None
3932 } else {
3933 Some(cx.spawn_in(window, async move |_, _| {
3934 for task in tasks {
3935 task.await?
3936 }
3937 Ok(())
3938 }))
3939 }
3940 }
3941
3942 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3943 self.dock_at_position(position).read(cx).is_open()
3944 }
3945
3946 pub fn toggle_dock(
3947 &mut self,
3948 dock_side: DockPosition,
3949 window: &mut Window,
3950 cx: &mut Context<Self>,
3951 ) {
3952 let mut focus_center = false;
3953 let mut reveal_dock = false;
3954
3955 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3956 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3957
3958 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3959 telemetry::event!(
3960 "Panel Button Clicked",
3961 name = panel.persistent_name(),
3962 toggle_state = !was_visible
3963 );
3964 }
3965 if was_visible {
3966 self.save_open_dock_positions(cx);
3967 }
3968
3969 let dock = self.dock_at_position(dock_side);
3970 dock.update(cx, |dock, cx| {
3971 dock.set_open(!was_visible, window, cx);
3972
3973 if dock.active_panel().is_none() {
3974 let Some(panel_ix) = dock
3975 .first_enabled_panel_idx(cx)
3976 .log_with_level(log::Level::Info)
3977 else {
3978 return;
3979 };
3980 dock.activate_panel(panel_ix, window, cx);
3981 }
3982
3983 if let Some(active_panel) = dock.active_panel() {
3984 if was_visible {
3985 if active_panel
3986 .panel_focus_handle(cx)
3987 .contains_focused(window, cx)
3988 {
3989 focus_center = true;
3990 }
3991 } else {
3992 let focus_handle = &active_panel.panel_focus_handle(cx);
3993 window.focus(focus_handle, cx);
3994 reveal_dock = true;
3995 }
3996 }
3997 });
3998
3999 if reveal_dock {
4000 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
4001 }
4002
4003 if focus_center {
4004 self.active_pane
4005 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4006 }
4007
4008 cx.notify();
4009 self.serialize_workspace(window, cx);
4010 }
4011
4012 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
4013 self.all_docks().into_iter().find(|&dock| {
4014 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
4015 })
4016 }
4017
4018 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
4019 if let Some(dock) = self.active_dock(window, cx).cloned() {
4020 self.save_open_dock_positions(cx);
4021 dock.update(cx, |dock, cx| {
4022 dock.set_open(false, window, cx);
4023 });
4024 return true;
4025 }
4026 false
4027 }
4028
4029 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4030 self.save_open_dock_positions(cx);
4031 for dock in self.all_docks() {
4032 dock.update(cx, |dock, cx| {
4033 dock.set_open(false, window, cx);
4034 });
4035 }
4036
4037 cx.focus_self(window);
4038 cx.notify();
4039 self.serialize_workspace(window, cx);
4040 }
4041
4042 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
4043 self.all_docks()
4044 .into_iter()
4045 .filter_map(|dock| {
4046 let dock_ref = dock.read(cx);
4047 if dock_ref.is_open() {
4048 Some(dock_ref.position())
4049 } else {
4050 None
4051 }
4052 })
4053 .collect()
4054 }
4055
4056 /// Saves the positions of currently open docks.
4057 ///
4058 /// Updates `last_open_dock_positions` with positions of all currently open
4059 /// docks, to later be restored by the 'Toggle All Docks' action.
4060 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
4061 let open_dock_positions = self.get_open_dock_positions(cx);
4062 if !open_dock_positions.is_empty() {
4063 self.last_open_dock_positions = open_dock_positions;
4064 }
4065 }
4066
4067 /// Toggles all docks between open and closed states.
4068 ///
4069 /// If any docks are open, closes all and remembers their positions. If all
4070 /// docks are closed, restores the last remembered dock configuration.
4071 fn toggle_all_docks(
4072 &mut self,
4073 _: &ToggleAllDocks,
4074 window: &mut Window,
4075 cx: &mut Context<Self>,
4076 ) {
4077 let open_dock_positions = self.get_open_dock_positions(cx);
4078
4079 if !open_dock_positions.is_empty() {
4080 self.close_all_docks(window, cx);
4081 } else if !self.last_open_dock_positions.is_empty() {
4082 self.restore_last_open_docks(window, cx);
4083 }
4084 }
4085
4086 /// Reopens docks from the most recently remembered configuration.
4087 ///
4088 /// Opens all docks whose positions are stored in `last_open_dock_positions`
4089 /// and clears the stored positions.
4090 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4091 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
4092
4093 for position in positions_to_open {
4094 let dock = self.dock_at_position(position);
4095 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
4096 }
4097
4098 cx.focus_self(window);
4099 cx.notify();
4100 self.serialize_workspace(window, cx);
4101 }
4102
4103 /// Transfer focus to the panel of the given type.
4104 pub fn focus_panel<T: Panel>(
4105 &mut self,
4106 window: &mut Window,
4107 cx: &mut Context<Self>,
4108 ) -> Option<Entity<T>> {
4109 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
4110 panel.to_any().downcast().ok()
4111 }
4112
4113 /// Focus the panel of the given type if it isn't already focused. If it is
4114 /// already focused, then transfer focus back to the workspace center.
4115 /// When the `close_panel_on_toggle` setting is enabled, also closes the
4116 /// panel when transferring focus back to the center.
4117 pub fn toggle_panel_focus<T: Panel>(
4118 &mut self,
4119 window: &mut Window,
4120 cx: &mut Context<Self>,
4121 ) -> bool {
4122 let mut did_focus_panel = false;
4123 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
4124 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
4125 did_focus_panel
4126 });
4127
4128 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
4129 self.close_panel::<T>(window, cx);
4130 }
4131
4132 telemetry::event!(
4133 "Panel Button Clicked",
4134 name = T::persistent_name(),
4135 toggle_state = did_focus_panel
4136 );
4137
4138 did_focus_panel
4139 }
4140
4141 pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4142 if let Some(item) = self.active_item(cx) {
4143 item.item_focus_handle(cx).focus(window, cx);
4144 } else {
4145 log::error!("Could not find a focus target when switching focus to the center panes",);
4146 }
4147 }
4148
4149 pub fn activate_panel_for_proto_id(
4150 &mut self,
4151 panel_id: PanelId,
4152 window: &mut Window,
4153 cx: &mut Context<Self>,
4154 ) -> Option<Arc<dyn PanelHandle>> {
4155 let mut panel = None;
4156 for dock in self.all_docks() {
4157 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
4158 panel = dock.update(cx, |dock, cx| {
4159 dock.activate_panel(panel_index, window, cx);
4160 dock.set_open(true, window, cx);
4161 dock.active_panel().cloned()
4162 });
4163 break;
4164 }
4165 }
4166
4167 if panel.is_some() {
4168 cx.notify();
4169 self.serialize_workspace(window, cx);
4170 }
4171
4172 panel
4173 }
4174
4175 /// Focus or unfocus the given panel type, depending on the given callback.
4176 fn focus_or_unfocus_panel<T: Panel>(
4177 &mut self,
4178 window: &mut Window,
4179 cx: &mut Context<Self>,
4180 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
4181 ) -> Option<Arc<dyn PanelHandle>> {
4182 let mut result_panel = None;
4183 let mut serialize = false;
4184 for dock in self.all_docks() {
4185 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4186 let mut focus_center = false;
4187 let panel = dock.update(cx, |dock, cx| {
4188 dock.activate_panel(panel_index, window, cx);
4189
4190 let panel = dock.active_panel().cloned();
4191 if let Some(panel) = panel.as_ref() {
4192 if should_focus(&**panel, window, cx) {
4193 dock.set_open(true, window, cx);
4194 panel.panel_focus_handle(cx).focus(window, cx);
4195 } else {
4196 focus_center = true;
4197 }
4198 }
4199 panel
4200 });
4201
4202 if focus_center {
4203 self.active_pane
4204 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4205 }
4206
4207 result_panel = panel;
4208 serialize = true;
4209 break;
4210 }
4211 }
4212
4213 if serialize {
4214 self.serialize_workspace(window, cx);
4215 }
4216
4217 cx.notify();
4218 result_panel
4219 }
4220
4221 /// Open the panel of the given type
4222 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4223 for dock in self.all_docks() {
4224 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4225 dock.update(cx, |dock, cx| {
4226 dock.activate_panel(panel_index, window, cx);
4227 dock.set_open(true, window, cx);
4228 });
4229 }
4230 }
4231 }
4232
4233 /// Open the panel of the given type, dismissing any zoomed items that
4234 /// would obscure it (e.g. a zoomed terminal).
4235 pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4236 let dock_position = self.all_docks().iter().find_map(|dock| {
4237 let dock = dock.read(cx);
4238 dock.panel_index_for_type::<T>().map(|_| dock.position())
4239 });
4240 self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
4241 self.open_panel::<T>(window, cx);
4242 }
4243
4244 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
4245 for dock in self.all_docks().iter() {
4246 dock.update(cx, |dock, cx| {
4247 if dock.panel::<T>().is_some() {
4248 dock.set_open(false, window, cx)
4249 }
4250 })
4251 }
4252 }
4253
4254 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
4255 self.all_docks()
4256 .iter()
4257 .find_map(|dock| dock.read(cx).panel::<T>())
4258 }
4259
4260 fn dismiss_zoomed_items_to_reveal(
4261 &mut self,
4262 dock_to_reveal: Option<DockPosition>,
4263 window: &mut Window,
4264 cx: &mut Context<Self>,
4265 ) {
4266 // If a center pane is zoomed, unzoom it.
4267 for pane in &self.panes {
4268 if pane != &self.active_pane || dock_to_reveal.is_some() {
4269 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4270 }
4271 }
4272
4273 // If another dock is zoomed, hide it.
4274 let mut focus_center = false;
4275 for dock in self.all_docks() {
4276 dock.update(cx, |dock, cx| {
4277 if Some(dock.position()) != dock_to_reveal
4278 && let Some(panel) = dock.active_panel()
4279 && panel.is_zoomed(window, cx)
4280 {
4281 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
4282 dock.set_open(false, window, cx);
4283 }
4284 });
4285 }
4286
4287 if focus_center {
4288 self.active_pane
4289 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4290 }
4291
4292 if self.zoomed_position != dock_to_reveal {
4293 self.zoomed = None;
4294 self.zoomed_position = None;
4295 cx.emit(Event::ZoomChanged);
4296 }
4297
4298 cx.notify();
4299 }
4300
4301 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4302 let pane = cx.new(|cx| {
4303 let mut pane = Pane::new(
4304 self.weak_handle(),
4305 self.project.clone(),
4306 self.pane_history_timestamp.clone(),
4307 None,
4308 NewFile.boxed_clone(),
4309 true,
4310 window,
4311 cx,
4312 );
4313 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
4314 pane
4315 });
4316 cx.subscribe_in(&pane, window, Self::handle_pane_event)
4317 .detach();
4318 self.panes.push(pane.clone());
4319
4320 window.focus(&pane.focus_handle(cx), cx);
4321
4322 cx.emit(Event::PaneAdded(pane.clone()));
4323 pane
4324 }
4325
4326 pub fn add_item_to_center(
4327 &mut self,
4328 item: Box<dyn ItemHandle>,
4329 window: &mut Window,
4330 cx: &mut Context<Self>,
4331 ) -> bool {
4332 if let Some(center_pane) = self.last_active_center_pane.clone() {
4333 if let Some(center_pane) = center_pane.upgrade() {
4334 center_pane.update(cx, |pane, cx| {
4335 pane.add_item(item, true, true, None, window, cx)
4336 });
4337 true
4338 } else {
4339 false
4340 }
4341 } else {
4342 false
4343 }
4344 }
4345
4346 pub fn add_item_to_active_pane(
4347 &mut self,
4348 item: Box<dyn ItemHandle>,
4349 destination_index: Option<usize>,
4350 focus_item: bool,
4351 window: &mut Window,
4352 cx: &mut App,
4353 ) {
4354 self.add_item(
4355 self.active_pane.clone(),
4356 item,
4357 destination_index,
4358 false,
4359 focus_item,
4360 window,
4361 cx,
4362 )
4363 }
4364
4365 pub fn add_item(
4366 &mut self,
4367 pane: Entity<Pane>,
4368 item: Box<dyn ItemHandle>,
4369 destination_index: Option<usize>,
4370 activate_pane: bool,
4371 focus_item: bool,
4372 window: &mut Window,
4373 cx: &mut App,
4374 ) {
4375 pane.update(cx, |pane, cx| {
4376 pane.add_item(
4377 item,
4378 activate_pane,
4379 focus_item,
4380 destination_index,
4381 window,
4382 cx,
4383 )
4384 });
4385 }
4386
4387 pub fn split_item(
4388 &mut self,
4389 split_direction: SplitDirection,
4390 item: Box<dyn ItemHandle>,
4391 window: &mut Window,
4392 cx: &mut Context<Self>,
4393 ) {
4394 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4395 self.add_item(new_pane, item, None, true, true, window, cx);
4396 }
4397
4398 pub fn open_abs_path(
4399 &mut self,
4400 abs_path: PathBuf,
4401 options: OpenOptions,
4402 window: &mut Window,
4403 cx: &mut Context<Self>,
4404 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4405 cx.spawn_in(window, async move |workspace, cx| {
4406 let open_paths_task_result = workspace
4407 .update_in(cx, |workspace, window, cx| {
4408 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4409 })
4410 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4411 .await;
4412 anyhow::ensure!(
4413 open_paths_task_result.len() == 1,
4414 "open abs path {abs_path:?} task returned incorrect number of results"
4415 );
4416 match open_paths_task_result
4417 .into_iter()
4418 .next()
4419 .expect("ensured single task result")
4420 {
4421 Some(open_result) => {
4422 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4423 }
4424 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4425 }
4426 })
4427 }
4428
4429 pub fn split_abs_path(
4430 &mut self,
4431 abs_path: PathBuf,
4432 visible: bool,
4433 window: &mut Window,
4434 cx: &mut Context<Self>,
4435 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4436 let project_path_task =
4437 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4438 cx.spawn_in(window, async move |this, cx| {
4439 let (_, path) = project_path_task.await?;
4440 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4441 .await
4442 })
4443 }
4444
4445 pub fn open_path(
4446 &mut self,
4447 path: impl Into<ProjectPath>,
4448 pane: Option<WeakEntity<Pane>>,
4449 focus_item: bool,
4450 window: &mut Window,
4451 cx: &mut App,
4452 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4453 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4454 }
4455
4456 pub fn open_path_preview(
4457 &mut self,
4458 path: impl Into<ProjectPath>,
4459 pane: Option<WeakEntity<Pane>>,
4460 focus_item: bool,
4461 allow_preview: bool,
4462 activate: bool,
4463 window: &mut Window,
4464 cx: &mut App,
4465 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4466 let pane = pane.unwrap_or_else(|| {
4467 self.last_active_center_pane.clone().unwrap_or_else(|| {
4468 self.panes
4469 .first()
4470 .expect("There must be an active pane")
4471 .downgrade()
4472 })
4473 });
4474
4475 let project_path = path.into();
4476 let task = self.load_path(project_path.clone(), window, cx);
4477 window.spawn(cx, async move |cx| {
4478 let (project_entry_id, build_item) = task.await?;
4479
4480 pane.update_in(cx, |pane, window, cx| {
4481 pane.open_item(
4482 project_entry_id,
4483 project_path,
4484 focus_item,
4485 allow_preview,
4486 activate,
4487 None,
4488 window,
4489 cx,
4490 build_item,
4491 )
4492 })
4493 })
4494 }
4495
4496 pub fn split_path(
4497 &mut self,
4498 path: impl Into<ProjectPath>,
4499 window: &mut Window,
4500 cx: &mut Context<Self>,
4501 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4502 self.split_path_preview(path, false, None, window, cx)
4503 }
4504
4505 pub fn split_path_preview(
4506 &mut self,
4507 path: impl Into<ProjectPath>,
4508 allow_preview: bool,
4509 split_direction: Option<SplitDirection>,
4510 window: &mut Window,
4511 cx: &mut Context<Self>,
4512 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4513 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4514 self.panes
4515 .first()
4516 .expect("There must be an active pane")
4517 .downgrade()
4518 });
4519
4520 if let Member::Pane(center_pane) = &self.center.root
4521 && center_pane.read(cx).items_len() == 0
4522 {
4523 return self.open_path(path, Some(pane), true, window, cx);
4524 }
4525
4526 let project_path = path.into();
4527 let task = self.load_path(project_path.clone(), window, cx);
4528 cx.spawn_in(window, async move |this, cx| {
4529 let (project_entry_id, build_item) = task.await?;
4530 this.update_in(cx, move |this, window, cx| -> Option<_> {
4531 let pane = pane.upgrade()?;
4532 let new_pane = this.split_pane(
4533 pane,
4534 split_direction.unwrap_or(SplitDirection::Right),
4535 window,
4536 cx,
4537 );
4538 new_pane.update(cx, |new_pane, cx| {
4539 Some(new_pane.open_item(
4540 project_entry_id,
4541 project_path,
4542 true,
4543 allow_preview,
4544 true,
4545 None,
4546 window,
4547 cx,
4548 build_item,
4549 ))
4550 })
4551 })
4552 .map(|option| option.context("pane was dropped"))?
4553 })
4554 }
4555
4556 fn load_path(
4557 &mut self,
4558 path: ProjectPath,
4559 window: &mut Window,
4560 cx: &mut App,
4561 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4562 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4563 registry.open_path(self.project(), &path, window, cx)
4564 }
4565
4566 pub fn find_project_item<T>(
4567 &self,
4568 pane: &Entity<Pane>,
4569 project_item: &Entity<T::Item>,
4570 cx: &App,
4571 ) -> Option<Entity<T>>
4572 where
4573 T: ProjectItem,
4574 {
4575 use project::ProjectItem as _;
4576 let project_item = project_item.read(cx);
4577 let entry_id = project_item.entry_id(cx);
4578 let project_path = project_item.project_path(cx);
4579
4580 let mut item = None;
4581 if let Some(entry_id) = entry_id {
4582 item = pane.read(cx).item_for_entry(entry_id, cx);
4583 }
4584 if item.is_none()
4585 && let Some(project_path) = project_path
4586 {
4587 item = pane.read(cx).item_for_path(project_path, cx);
4588 }
4589
4590 item.and_then(|item| item.downcast::<T>())
4591 }
4592
4593 pub fn is_project_item_open<T>(
4594 &self,
4595 pane: &Entity<Pane>,
4596 project_item: &Entity<T::Item>,
4597 cx: &App,
4598 ) -> bool
4599 where
4600 T: ProjectItem,
4601 {
4602 self.find_project_item::<T>(pane, project_item, cx)
4603 .is_some()
4604 }
4605
4606 pub fn open_project_item<T>(
4607 &mut self,
4608 pane: Entity<Pane>,
4609 project_item: Entity<T::Item>,
4610 activate_pane: bool,
4611 focus_item: bool,
4612 keep_old_preview: bool,
4613 allow_new_preview: bool,
4614 window: &mut Window,
4615 cx: &mut Context<Self>,
4616 ) -> Entity<T>
4617 where
4618 T: ProjectItem,
4619 {
4620 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4621
4622 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4623 if !keep_old_preview
4624 && let Some(old_id) = old_item_id
4625 && old_id != item.item_id()
4626 {
4627 // switching to a different item, so unpreview old active item
4628 pane.update(cx, |pane, _| {
4629 pane.unpreview_item_if_preview(old_id);
4630 });
4631 }
4632
4633 self.activate_item(&item, activate_pane, focus_item, window, cx);
4634 if !allow_new_preview {
4635 pane.update(cx, |pane, _| {
4636 pane.unpreview_item_if_preview(item.item_id());
4637 });
4638 }
4639 return item;
4640 }
4641
4642 let item = pane.update(cx, |pane, cx| {
4643 cx.new(|cx| {
4644 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4645 })
4646 });
4647 let mut destination_index = None;
4648 pane.update(cx, |pane, cx| {
4649 if !keep_old_preview && let Some(old_id) = old_item_id {
4650 pane.unpreview_item_if_preview(old_id);
4651 }
4652 if allow_new_preview {
4653 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4654 }
4655 });
4656
4657 self.add_item(
4658 pane,
4659 Box::new(item.clone()),
4660 destination_index,
4661 activate_pane,
4662 focus_item,
4663 window,
4664 cx,
4665 );
4666 item
4667 }
4668
4669 pub fn open_shared_screen(
4670 &mut self,
4671 peer_id: PeerId,
4672 window: &mut Window,
4673 cx: &mut Context<Self>,
4674 ) {
4675 if let Some(shared_screen) =
4676 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4677 {
4678 self.active_pane.update(cx, |pane, cx| {
4679 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4680 });
4681 }
4682 }
4683
4684 pub fn activate_item(
4685 &mut self,
4686 item: &dyn ItemHandle,
4687 activate_pane: bool,
4688 focus_item: bool,
4689 window: &mut Window,
4690 cx: &mut App,
4691 ) -> bool {
4692 let result = self.panes.iter().find_map(|pane| {
4693 pane.read(cx)
4694 .index_for_item(item)
4695 .map(|ix| (pane.clone(), ix))
4696 });
4697 if let Some((pane, ix)) = result {
4698 pane.update(cx, |pane, cx| {
4699 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4700 });
4701 true
4702 } else {
4703 false
4704 }
4705 }
4706
4707 fn activate_pane_at_index(
4708 &mut self,
4709 action: &ActivatePane,
4710 window: &mut Window,
4711 cx: &mut Context<Self>,
4712 ) {
4713 let panes = self.center.panes();
4714 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4715 window.focus(&pane.focus_handle(cx), cx);
4716 } else {
4717 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4718 .detach();
4719 }
4720 }
4721
4722 fn move_item_to_pane_at_index(
4723 &mut self,
4724 action: &MoveItemToPane,
4725 window: &mut Window,
4726 cx: &mut Context<Self>,
4727 ) {
4728 let panes = self.center.panes();
4729 let destination = match panes.get(action.destination) {
4730 Some(&destination) => destination.clone(),
4731 None => {
4732 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4733 return;
4734 }
4735 let direction = SplitDirection::Right;
4736 let split_off_pane = self
4737 .find_pane_in_direction(direction, cx)
4738 .unwrap_or_else(|| self.active_pane.clone());
4739 let new_pane = self.add_pane(window, cx);
4740 self.center.split(&split_off_pane, &new_pane, direction, cx);
4741 new_pane
4742 }
4743 };
4744
4745 if action.clone {
4746 if self
4747 .active_pane
4748 .read(cx)
4749 .active_item()
4750 .is_some_and(|item| item.can_split(cx))
4751 {
4752 clone_active_item(
4753 self.database_id(),
4754 &self.active_pane,
4755 &destination,
4756 action.focus,
4757 window,
4758 cx,
4759 );
4760 return;
4761 }
4762 }
4763 move_active_item(
4764 &self.active_pane,
4765 &destination,
4766 action.focus,
4767 true,
4768 window,
4769 cx,
4770 )
4771 }
4772
4773 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4774 let panes = self.center.panes();
4775 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4776 let next_ix = (ix + 1) % panes.len();
4777 let next_pane = panes[next_ix].clone();
4778 window.focus(&next_pane.focus_handle(cx), cx);
4779 }
4780 }
4781
4782 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4783 let panes = self.center.panes();
4784 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4785 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4786 let prev_pane = panes[prev_ix].clone();
4787 window.focus(&prev_pane.focus_handle(cx), cx);
4788 }
4789 }
4790
4791 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4792 let last_pane = self.center.last_pane();
4793 window.focus(&last_pane.focus_handle(cx), cx);
4794 }
4795
4796 pub fn activate_pane_in_direction(
4797 &mut self,
4798 direction: SplitDirection,
4799 window: &mut Window,
4800 cx: &mut App,
4801 ) {
4802 use ActivateInDirectionTarget as Target;
4803 enum Origin {
4804 Sidebar,
4805 LeftDock,
4806 RightDock,
4807 BottomDock,
4808 Center,
4809 }
4810
4811 let origin: Origin = if self
4812 .sidebar_focus_handle
4813 .as_ref()
4814 .is_some_and(|h| h.contains_focused(window, cx))
4815 {
4816 Origin::Sidebar
4817 } else {
4818 [
4819 (&self.left_dock, Origin::LeftDock),
4820 (&self.right_dock, Origin::RightDock),
4821 (&self.bottom_dock, Origin::BottomDock),
4822 ]
4823 .into_iter()
4824 .find_map(|(dock, origin)| {
4825 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4826 Some(origin)
4827 } else {
4828 None
4829 }
4830 })
4831 .unwrap_or(Origin::Center)
4832 };
4833
4834 let get_last_active_pane = || {
4835 let pane = self
4836 .last_active_center_pane
4837 .clone()
4838 .unwrap_or_else(|| {
4839 self.panes
4840 .first()
4841 .expect("There must be an active pane")
4842 .downgrade()
4843 })
4844 .upgrade()?;
4845 (pane.read(cx).items_len() != 0).then_some(pane)
4846 };
4847
4848 let try_dock =
4849 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4850
4851 let sidebar_target = self
4852 .sidebar_focus_handle
4853 .as_ref()
4854 .map(|h| Target::Sidebar(h.clone()));
4855
4856 let sidebar_on_right = self
4857 .multi_workspace
4858 .as_ref()
4859 .and_then(|mw| mw.upgrade())
4860 .map_or(false, |mw| {
4861 mw.read(cx).sidebar_side(cx) == SidebarSide::Right
4862 });
4863
4864 let away_from_sidebar = if sidebar_on_right {
4865 SplitDirection::Left
4866 } else {
4867 SplitDirection::Right
4868 };
4869
4870 let (near_dock, far_dock) = if sidebar_on_right {
4871 (&self.right_dock, &self.left_dock)
4872 } else {
4873 (&self.left_dock, &self.right_dock)
4874 };
4875
4876 let target = match (origin, direction) {
4877 (Origin::Sidebar, dir) if dir == away_from_sidebar => try_dock(near_dock)
4878 .or_else(|| get_last_active_pane().map(Target::Pane))
4879 .or_else(|| try_dock(&self.bottom_dock))
4880 .or_else(|| try_dock(far_dock)),
4881
4882 (Origin::Sidebar, _) => None,
4883
4884 // We're in the center, so we first try to go to a different pane,
4885 // otherwise try to go to a dock.
4886 (Origin::Center, direction) => {
4887 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4888 Some(Target::Pane(pane))
4889 } else {
4890 match direction {
4891 SplitDirection::Up => None,
4892 SplitDirection::Down => try_dock(&self.bottom_dock),
4893 SplitDirection::Left => {
4894 let dock_target = try_dock(&self.left_dock);
4895 if sidebar_on_right {
4896 dock_target
4897 } else {
4898 dock_target.or(sidebar_target)
4899 }
4900 }
4901 SplitDirection::Right => {
4902 let dock_target = try_dock(&self.right_dock);
4903 if sidebar_on_right {
4904 dock_target.or(sidebar_target)
4905 } else {
4906 dock_target
4907 }
4908 }
4909 }
4910 }
4911 }
4912
4913 (Origin::LeftDock, SplitDirection::Right) => {
4914 if let Some(last_active_pane) = get_last_active_pane() {
4915 Some(Target::Pane(last_active_pane))
4916 } else {
4917 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4918 }
4919 }
4920
4921 (Origin::LeftDock, SplitDirection::Left) => {
4922 if sidebar_on_right {
4923 None
4924 } else {
4925 sidebar_target
4926 }
4927 }
4928
4929 (Origin::LeftDock, SplitDirection::Down)
4930 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4931
4932 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4933 (Origin::BottomDock, SplitDirection::Left) => {
4934 let dock_target = try_dock(&self.left_dock);
4935 if sidebar_on_right {
4936 dock_target
4937 } else {
4938 dock_target.or(sidebar_target)
4939 }
4940 }
4941 (Origin::BottomDock, SplitDirection::Right) => {
4942 let dock_target = try_dock(&self.right_dock);
4943 if sidebar_on_right {
4944 dock_target.or(sidebar_target)
4945 } else {
4946 dock_target
4947 }
4948 }
4949
4950 (Origin::RightDock, SplitDirection::Left) => {
4951 if let Some(last_active_pane) = get_last_active_pane() {
4952 Some(Target::Pane(last_active_pane))
4953 } else {
4954 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
4955 }
4956 }
4957
4958 (Origin::RightDock, SplitDirection::Right) => {
4959 if sidebar_on_right {
4960 sidebar_target
4961 } else {
4962 None
4963 }
4964 }
4965
4966 _ => None,
4967 };
4968
4969 match target {
4970 Some(ActivateInDirectionTarget::Pane(pane)) => {
4971 let pane = pane.read(cx);
4972 if let Some(item) = pane.active_item() {
4973 item.item_focus_handle(cx).focus(window, cx);
4974 } else {
4975 log::error!(
4976 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4977 );
4978 }
4979 }
4980 Some(ActivateInDirectionTarget::Dock(dock)) => {
4981 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4982 window.defer(cx, move |window, cx| {
4983 let dock = dock.read(cx);
4984 if let Some(panel) = dock.active_panel() {
4985 panel.panel_focus_handle(cx).focus(window, cx);
4986 } else {
4987 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4988 }
4989 })
4990 }
4991 Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
4992 focus_handle.focus(window, cx);
4993 }
4994 None => {}
4995 }
4996 }
4997
4998 pub fn move_item_to_pane_in_direction(
4999 &mut self,
5000 action: &MoveItemToPaneInDirection,
5001 window: &mut Window,
5002 cx: &mut Context<Self>,
5003 ) {
5004 let destination = match self.find_pane_in_direction(action.direction, cx) {
5005 Some(destination) => destination,
5006 None => {
5007 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
5008 return;
5009 }
5010 let new_pane = self.add_pane(window, cx);
5011 self.center
5012 .split(&self.active_pane, &new_pane, action.direction, cx);
5013 new_pane
5014 }
5015 };
5016
5017 if action.clone {
5018 if self
5019 .active_pane
5020 .read(cx)
5021 .active_item()
5022 .is_some_and(|item| item.can_split(cx))
5023 {
5024 clone_active_item(
5025 self.database_id(),
5026 &self.active_pane,
5027 &destination,
5028 action.focus,
5029 window,
5030 cx,
5031 );
5032 return;
5033 }
5034 }
5035 move_active_item(
5036 &self.active_pane,
5037 &destination,
5038 action.focus,
5039 true,
5040 window,
5041 cx,
5042 );
5043 }
5044
5045 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
5046 self.center.bounding_box_for_pane(pane)
5047 }
5048
5049 pub fn find_pane_in_direction(
5050 &mut self,
5051 direction: SplitDirection,
5052 cx: &App,
5053 ) -> Option<Entity<Pane>> {
5054 self.center
5055 .find_pane_in_direction(&self.active_pane, direction, cx)
5056 .cloned()
5057 }
5058
5059 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
5060 if let Some(to) = self.find_pane_in_direction(direction, cx) {
5061 self.center.swap(&self.active_pane, &to, cx);
5062 cx.notify();
5063 }
5064 }
5065
5066 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
5067 if self
5068 .center
5069 .move_to_border(&self.active_pane, direction, cx)
5070 .unwrap()
5071 {
5072 cx.notify();
5073 }
5074 }
5075
5076 pub fn resize_pane(
5077 &mut self,
5078 axis: gpui::Axis,
5079 amount: Pixels,
5080 window: &mut Window,
5081 cx: &mut Context<Self>,
5082 ) {
5083 let docks = self.all_docks();
5084 let active_dock = docks
5085 .into_iter()
5086 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
5087
5088 if let Some(dock_entity) = active_dock {
5089 let dock = dock_entity.read(cx);
5090 let Some(panel_size) = self.dock_size(&dock, window, cx) else {
5091 return;
5092 };
5093 match dock.position() {
5094 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
5095 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
5096 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
5097 }
5098 } else {
5099 self.center
5100 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
5101 }
5102 cx.notify();
5103 }
5104
5105 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
5106 self.center.reset_pane_sizes(cx);
5107 cx.notify();
5108 }
5109
5110 fn handle_pane_focused(
5111 &mut self,
5112 pane: Entity<Pane>,
5113 window: &mut Window,
5114 cx: &mut Context<Self>,
5115 ) {
5116 // This is explicitly hoisted out of the following check for pane identity as
5117 // terminal panel panes are not registered as a center panes.
5118 self.status_bar.update(cx, |status_bar, cx| {
5119 status_bar.set_active_pane(&pane, window, cx);
5120 });
5121 if self.active_pane != pane {
5122 self.set_active_pane(&pane, window, cx);
5123 }
5124
5125 if self.last_active_center_pane.is_none() {
5126 self.last_active_center_pane = Some(pane.downgrade());
5127 }
5128
5129 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
5130 // This prevents the dock from closing when focus events fire during window activation.
5131 // We also preserve any dock whose active panel itself has focus — this covers
5132 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
5133 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
5134 let dock_read = dock.read(cx);
5135 if let Some(panel) = dock_read.active_panel() {
5136 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
5137 || panel.panel_focus_handle(cx).contains_focused(window, cx)
5138 {
5139 return Some(dock_read.position());
5140 }
5141 }
5142 None
5143 });
5144
5145 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
5146 if pane.read(cx).is_zoomed() {
5147 self.zoomed = Some(pane.downgrade().into());
5148 } else {
5149 self.zoomed = None;
5150 }
5151 self.zoomed_position = None;
5152 cx.emit(Event::ZoomChanged);
5153 self.update_active_view_for_followers(window, cx);
5154 pane.update(cx, |pane, _| {
5155 pane.track_alternate_file_items();
5156 });
5157
5158 cx.notify();
5159 }
5160
5161 fn set_active_pane(
5162 &mut self,
5163 pane: &Entity<Pane>,
5164 window: &mut Window,
5165 cx: &mut Context<Self>,
5166 ) {
5167 self.active_pane = pane.clone();
5168 self.active_item_path_changed(true, window, cx);
5169 self.last_active_center_pane = Some(pane.downgrade());
5170 }
5171
5172 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5173 self.update_active_view_for_followers(window, cx);
5174 }
5175
5176 fn handle_pane_event(
5177 &mut self,
5178 pane: &Entity<Pane>,
5179 event: &pane::Event,
5180 window: &mut Window,
5181 cx: &mut Context<Self>,
5182 ) {
5183 let mut serialize_workspace = true;
5184 match event {
5185 pane::Event::AddItem { item } => {
5186 item.added_to_pane(self, pane.clone(), window, cx);
5187 cx.emit(Event::ItemAdded {
5188 item: item.boxed_clone(),
5189 });
5190 }
5191 pane::Event::Split { direction, mode } => {
5192 match mode {
5193 SplitMode::ClonePane => {
5194 self.split_and_clone(pane.clone(), *direction, window, cx)
5195 .detach();
5196 }
5197 SplitMode::EmptyPane => {
5198 self.split_pane(pane.clone(), *direction, window, cx);
5199 }
5200 SplitMode::MovePane => {
5201 self.split_and_move(pane.clone(), *direction, window, cx);
5202 }
5203 };
5204 }
5205 pane::Event::JoinIntoNext => {
5206 self.join_pane_into_next(pane.clone(), window, cx);
5207 }
5208 pane::Event::JoinAll => {
5209 self.join_all_panes(window, cx);
5210 }
5211 pane::Event::Remove { focus_on_pane } => {
5212 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
5213 }
5214 pane::Event::ActivateItem {
5215 local,
5216 focus_changed,
5217 } => {
5218 window.invalidate_character_coordinates();
5219
5220 pane.update(cx, |pane, _| {
5221 pane.track_alternate_file_items();
5222 });
5223 if *local {
5224 self.unfollow_in_pane(pane, window, cx);
5225 }
5226 serialize_workspace = *focus_changed || pane != self.active_pane();
5227 if pane == self.active_pane() {
5228 self.active_item_path_changed(*focus_changed, window, cx);
5229 self.update_active_view_for_followers(window, cx);
5230 } else if *local {
5231 self.set_active_pane(pane, window, cx);
5232 }
5233 }
5234 pane::Event::UserSavedItem { item, save_intent } => {
5235 cx.emit(Event::UserSavedItem {
5236 pane: pane.downgrade(),
5237 item: item.boxed_clone(),
5238 save_intent: *save_intent,
5239 });
5240 serialize_workspace = false;
5241 }
5242 pane::Event::ChangeItemTitle => {
5243 if *pane == self.active_pane {
5244 self.active_item_path_changed(false, window, cx);
5245 }
5246 serialize_workspace = false;
5247 }
5248 pane::Event::RemovedItem { item } => {
5249 cx.emit(Event::ActiveItemChanged);
5250 self.update_window_edited(window, cx);
5251 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
5252 && entry.get().entity_id() == pane.entity_id()
5253 {
5254 entry.remove();
5255 }
5256 cx.emit(Event::ItemRemoved {
5257 item_id: item.item_id(),
5258 });
5259 }
5260 pane::Event::Focus => {
5261 window.invalidate_character_coordinates();
5262 self.handle_pane_focused(pane.clone(), window, cx);
5263 }
5264 pane::Event::ZoomIn => {
5265 if *pane == self.active_pane {
5266 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
5267 if pane.read(cx).has_focus(window, cx) {
5268 self.zoomed = Some(pane.downgrade().into());
5269 self.zoomed_position = None;
5270 cx.emit(Event::ZoomChanged);
5271 }
5272 cx.notify();
5273 }
5274 }
5275 pane::Event::ZoomOut => {
5276 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
5277 if self.zoomed_position.is_none() {
5278 self.zoomed = None;
5279 cx.emit(Event::ZoomChanged);
5280 }
5281 cx.notify();
5282 }
5283 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
5284 }
5285
5286 if serialize_workspace {
5287 self.serialize_workspace(window, cx);
5288 }
5289 }
5290
5291 pub fn unfollow_in_pane(
5292 &mut self,
5293 pane: &Entity<Pane>,
5294 window: &mut Window,
5295 cx: &mut Context<Workspace>,
5296 ) -> Option<CollaboratorId> {
5297 let leader_id = self.leader_for_pane(pane)?;
5298 self.unfollow(leader_id, window, cx);
5299 Some(leader_id)
5300 }
5301
5302 pub fn split_pane(
5303 &mut self,
5304 pane_to_split: Entity<Pane>,
5305 split_direction: SplitDirection,
5306 window: &mut Window,
5307 cx: &mut Context<Self>,
5308 ) -> Entity<Pane> {
5309 let new_pane = self.add_pane(window, cx);
5310 self.center
5311 .split(&pane_to_split, &new_pane, split_direction, cx);
5312 cx.notify();
5313 new_pane
5314 }
5315
5316 pub fn split_and_move(
5317 &mut self,
5318 pane: Entity<Pane>,
5319 direction: SplitDirection,
5320 window: &mut Window,
5321 cx: &mut Context<Self>,
5322 ) {
5323 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
5324 return;
5325 };
5326 let new_pane = self.add_pane(window, cx);
5327 new_pane.update(cx, |pane, cx| {
5328 pane.add_item(item, true, true, None, window, cx)
5329 });
5330 self.center.split(&pane, &new_pane, direction, cx);
5331 cx.notify();
5332 }
5333
5334 pub fn split_and_clone(
5335 &mut self,
5336 pane: Entity<Pane>,
5337 direction: SplitDirection,
5338 window: &mut Window,
5339 cx: &mut Context<Self>,
5340 ) -> Task<Option<Entity<Pane>>> {
5341 let Some(item) = pane.read(cx).active_item() else {
5342 return Task::ready(None);
5343 };
5344 if !item.can_split(cx) {
5345 return Task::ready(None);
5346 }
5347 let task = item.clone_on_split(self.database_id(), window, cx);
5348 cx.spawn_in(window, async move |this, cx| {
5349 if let Some(clone) = task.await {
5350 this.update_in(cx, |this, window, cx| {
5351 let new_pane = this.add_pane(window, cx);
5352 let nav_history = pane.read(cx).fork_nav_history();
5353 new_pane.update(cx, |pane, cx| {
5354 pane.set_nav_history(nav_history, cx);
5355 pane.add_item(clone, true, true, None, window, cx)
5356 });
5357 this.center.split(&pane, &new_pane, direction, cx);
5358 cx.notify();
5359 new_pane
5360 })
5361 .ok()
5362 } else {
5363 None
5364 }
5365 })
5366 }
5367
5368 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5369 let active_item = self.active_pane.read(cx).active_item();
5370 for pane in &self.panes {
5371 join_pane_into_active(&self.active_pane, pane, window, cx);
5372 }
5373 if let Some(active_item) = active_item {
5374 self.activate_item(active_item.as_ref(), true, true, window, cx);
5375 }
5376 cx.notify();
5377 }
5378
5379 pub fn join_pane_into_next(
5380 &mut self,
5381 pane: Entity<Pane>,
5382 window: &mut Window,
5383 cx: &mut Context<Self>,
5384 ) {
5385 let next_pane = self
5386 .find_pane_in_direction(SplitDirection::Right, cx)
5387 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
5388 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
5389 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
5390 let Some(next_pane) = next_pane else {
5391 return;
5392 };
5393 move_all_items(&pane, &next_pane, window, cx);
5394 cx.notify();
5395 }
5396
5397 fn remove_pane(
5398 &mut self,
5399 pane: Entity<Pane>,
5400 focus_on: Option<Entity<Pane>>,
5401 window: &mut Window,
5402 cx: &mut Context<Self>,
5403 ) {
5404 if self.center.remove(&pane, cx).unwrap() {
5405 self.force_remove_pane(&pane, &focus_on, window, cx);
5406 self.unfollow_in_pane(&pane, window, cx);
5407 self.last_leaders_by_pane.remove(&pane.downgrade());
5408 for removed_item in pane.read(cx).items() {
5409 self.panes_by_item.remove(&removed_item.item_id());
5410 }
5411
5412 cx.notify();
5413 } else {
5414 self.active_item_path_changed(true, window, cx);
5415 }
5416 cx.emit(Event::PaneRemoved);
5417 }
5418
5419 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5420 &mut self.panes
5421 }
5422
5423 pub fn panes(&self) -> &[Entity<Pane>] {
5424 &self.panes
5425 }
5426
5427 pub fn active_pane(&self) -> &Entity<Pane> {
5428 &self.active_pane
5429 }
5430
5431 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5432 for dock in self.all_docks() {
5433 if dock.focus_handle(cx).contains_focused(window, cx)
5434 && let Some(pane) = dock
5435 .read(cx)
5436 .active_panel()
5437 .and_then(|panel| panel.pane(cx))
5438 {
5439 return pane;
5440 }
5441 }
5442 self.active_pane().clone()
5443 }
5444
5445 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5446 self.find_pane_in_direction(SplitDirection::Right, cx)
5447 .unwrap_or_else(|| {
5448 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5449 })
5450 }
5451
5452 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5453 self.pane_for_item_id(handle.item_id())
5454 }
5455
5456 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5457 let weak_pane = self.panes_by_item.get(&item_id)?;
5458 weak_pane.upgrade()
5459 }
5460
5461 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5462 self.panes
5463 .iter()
5464 .find(|pane| pane.entity_id() == entity_id)
5465 .cloned()
5466 }
5467
5468 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5469 self.follower_states.retain(|leader_id, state| {
5470 if *leader_id == CollaboratorId::PeerId(peer_id) {
5471 for item in state.items_by_leader_view_id.values() {
5472 item.view.set_leader_id(None, window, cx);
5473 }
5474 false
5475 } else {
5476 true
5477 }
5478 });
5479 cx.notify();
5480 }
5481
5482 pub fn start_following(
5483 &mut self,
5484 leader_id: impl Into<CollaboratorId>,
5485 window: &mut Window,
5486 cx: &mut Context<Self>,
5487 ) -> Option<Task<Result<()>>> {
5488 let leader_id = leader_id.into();
5489 let pane = self.active_pane().clone();
5490
5491 self.last_leaders_by_pane
5492 .insert(pane.downgrade(), leader_id);
5493 self.unfollow(leader_id, window, cx);
5494 self.unfollow_in_pane(&pane, window, cx);
5495 self.follower_states.insert(
5496 leader_id,
5497 FollowerState {
5498 center_pane: pane.clone(),
5499 dock_pane: None,
5500 active_view_id: None,
5501 items_by_leader_view_id: Default::default(),
5502 },
5503 );
5504 cx.notify();
5505
5506 match leader_id {
5507 CollaboratorId::PeerId(leader_peer_id) => {
5508 let room_id = self.active_call()?.room_id(cx)?;
5509 let project_id = self.project.read(cx).remote_id();
5510 let request = self.app_state.client.request(proto::Follow {
5511 room_id,
5512 project_id,
5513 leader_id: Some(leader_peer_id),
5514 });
5515
5516 Some(cx.spawn_in(window, async move |this, cx| {
5517 let response = request.await?;
5518 this.update(cx, |this, _| {
5519 let state = this
5520 .follower_states
5521 .get_mut(&leader_id)
5522 .context("following interrupted")?;
5523 state.active_view_id = response
5524 .active_view
5525 .as_ref()
5526 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5527 anyhow::Ok(())
5528 })??;
5529 if let Some(view) = response.active_view {
5530 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5531 }
5532 this.update_in(cx, |this, window, cx| {
5533 this.leader_updated(leader_id, window, cx)
5534 })?;
5535 Ok(())
5536 }))
5537 }
5538 CollaboratorId::Agent => {
5539 self.leader_updated(leader_id, window, cx)?;
5540 Some(Task::ready(Ok(())))
5541 }
5542 }
5543 }
5544
5545 pub fn follow_next_collaborator(
5546 &mut self,
5547 _: &FollowNextCollaborator,
5548 window: &mut Window,
5549 cx: &mut Context<Self>,
5550 ) {
5551 let collaborators = self.project.read(cx).collaborators();
5552 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5553 let mut collaborators = collaborators.keys().copied();
5554 for peer_id in collaborators.by_ref() {
5555 if CollaboratorId::PeerId(peer_id) == leader_id {
5556 break;
5557 }
5558 }
5559 collaborators.next().map(CollaboratorId::PeerId)
5560 } else if let Some(last_leader_id) =
5561 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5562 {
5563 match last_leader_id {
5564 CollaboratorId::PeerId(peer_id) => {
5565 if collaborators.contains_key(peer_id) {
5566 Some(*last_leader_id)
5567 } else {
5568 None
5569 }
5570 }
5571 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5572 }
5573 } else {
5574 None
5575 };
5576
5577 let pane = self.active_pane.clone();
5578 let Some(leader_id) = next_leader_id.or_else(|| {
5579 Some(CollaboratorId::PeerId(
5580 collaborators.keys().copied().next()?,
5581 ))
5582 }) else {
5583 return;
5584 };
5585 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5586 return;
5587 }
5588 if let Some(task) = self.start_following(leader_id, window, cx) {
5589 task.detach_and_log_err(cx)
5590 }
5591 }
5592
5593 pub fn follow(
5594 &mut self,
5595 leader_id: impl Into<CollaboratorId>,
5596 window: &mut Window,
5597 cx: &mut Context<Self>,
5598 ) {
5599 let leader_id = leader_id.into();
5600
5601 if let CollaboratorId::PeerId(peer_id) = leader_id {
5602 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5603 return;
5604 };
5605 let Some(remote_participant) =
5606 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5607 else {
5608 return;
5609 };
5610
5611 let project = self.project.read(cx);
5612
5613 let other_project_id = match remote_participant.location {
5614 ParticipantLocation::External => None,
5615 ParticipantLocation::UnsharedProject => None,
5616 ParticipantLocation::SharedProject { project_id } => {
5617 if Some(project_id) == project.remote_id() {
5618 None
5619 } else {
5620 Some(project_id)
5621 }
5622 }
5623 };
5624
5625 // if they are active in another project, follow there.
5626 if let Some(project_id) = other_project_id {
5627 let app_state = self.app_state.clone();
5628 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5629 .detach_and_prompt_err("Failed to join project", window, cx, |error, _, _| {
5630 Some(format!("{error:#}"))
5631 });
5632 }
5633 }
5634
5635 // if you're already following, find the right pane and focus it.
5636 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5637 window.focus(&follower_state.pane().focus_handle(cx), cx);
5638
5639 return;
5640 }
5641
5642 // Otherwise, follow.
5643 if let Some(task) = self.start_following(leader_id, window, cx) {
5644 task.detach_and_log_err(cx)
5645 }
5646 }
5647
5648 pub fn unfollow(
5649 &mut self,
5650 leader_id: impl Into<CollaboratorId>,
5651 window: &mut Window,
5652 cx: &mut Context<Self>,
5653 ) -> Option<()> {
5654 cx.notify();
5655
5656 let leader_id = leader_id.into();
5657 let state = self.follower_states.remove(&leader_id)?;
5658 for (_, item) in state.items_by_leader_view_id {
5659 item.view.set_leader_id(None, window, cx);
5660 }
5661
5662 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5663 let project_id = self.project.read(cx).remote_id();
5664 let room_id = self.active_call()?.room_id(cx)?;
5665 self.app_state
5666 .client
5667 .send(proto::Unfollow {
5668 room_id,
5669 project_id,
5670 leader_id: Some(leader_peer_id),
5671 })
5672 .log_err();
5673 }
5674
5675 Some(())
5676 }
5677
5678 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5679 self.follower_states.contains_key(&id.into())
5680 }
5681
5682 fn active_item_path_changed(
5683 &mut self,
5684 focus_changed: bool,
5685 window: &mut Window,
5686 cx: &mut Context<Self>,
5687 ) {
5688 cx.emit(Event::ActiveItemChanged);
5689 let active_entry = self.active_project_path(cx);
5690 self.project.update(cx, |project, cx| {
5691 project.set_active_path(active_entry.clone(), cx)
5692 });
5693
5694 if focus_changed && let Some(project_path) = &active_entry {
5695 let git_store_entity = self.project.read(cx).git_store().clone();
5696 git_store_entity.update(cx, |git_store, cx| {
5697 git_store.set_active_repo_for_path(project_path, cx);
5698 });
5699 }
5700
5701 self.update_window_title(window, cx);
5702 }
5703
5704 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5705 let project = self.project().read(cx);
5706 let mut title = String::new();
5707
5708 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5709 let name = {
5710 let settings_location = SettingsLocation {
5711 worktree_id: worktree.read(cx).id(),
5712 path: RelPath::empty(),
5713 };
5714
5715 let settings = WorktreeSettings::get(Some(settings_location), cx);
5716 match &settings.project_name {
5717 Some(name) => name.as_str(),
5718 None => worktree.read(cx).root_name_str(),
5719 }
5720 };
5721 if i > 0 {
5722 title.push_str(", ");
5723 }
5724 title.push_str(name);
5725 }
5726
5727 if title.is_empty() {
5728 title = "empty project".to_string();
5729 }
5730
5731 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5732 let filename = path.path.file_name().or_else(|| {
5733 Some(
5734 project
5735 .worktree_for_id(path.worktree_id, cx)?
5736 .read(cx)
5737 .root_name_str(),
5738 )
5739 });
5740
5741 if let Some(filename) = filename {
5742 title.push_str(" — ");
5743 title.push_str(filename.as_ref());
5744 }
5745 }
5746
5747 if project.is_via_collab() {
5748 title.push_str(" ↙");
5749 } else if project.is_shared() {
5750 title.push_str(" ↗");
5751 }
5752
5753 if let Some(last_title) = self.last_window_title.as_ref()
5754 && &title == last_title
5755 {
5756 return;
5757 }
5758 window.set_window_title(&title);
5759 SystemWindowTabController::update_tab_title(
5760 cx,
5761 window.window_handle().window_id(),
5762 SharedString::from(&title),
5763 );
5764 self.last_window_title = Some(title);
5765 }
5766
5767 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5768 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5769 if is_edited != self.window_edited {
5770 self.window_edited = is_edited;
5771 window.set_window_edited(self.window_edited)
5772 }
5773 }
5774
5775 fn update_item_dirty_state(
5776 &mut self,
5777 item: &dyn ItemHandle,
5778 window: &mut Window,
5779 cx: &mut App,
5780 ) {
5781 let is_dirty = item.is_dirty(cx);
5782 let item_id = item.item_id();
5783 let was_dirty = self.dirty_items.contains_key(&item_id);
5784 if is_dirty == was_dirty {
5785 return;
5786 }
5787 if was_dirty {
5788 self.dirty_items.remove(&item_id);
5789 self.update_window_edited(window, cx);
5790 return;
5791 }
5792
5793 let workspace = self.weak_handle();
5794 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5795 return;
5796 };
5797 let on_release_callback = Box::new(move |cx: &mut App| {
5798 window_handle
5799 .update(cx, |_, window, cx| {
5800 workspace
5801 .update(cx, |workspace, cx| {
5802 workspace.dirty_items.remove(&item_id);
5803 workspace.update_window_edited(window, cx)
5804 })
5805 .ok();
5806 })
5807 .ok();
5808 });
5809
5810 let s = item.on_release(cx, on_release_callback);
5811 self.dirty_items.insert(item_id, s);
5812 self.update_window_edited(window, cx);
5813 }
5814
5815 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5816 if self.notifications.is_empty() {
5817 None
5818 } else {
5819 Some(
5820 div()
5821 .absolute()
5822 .right_3()
5823 .bottom_3()
5824 .w_112()
5825 .h_full()
5826 .flex()
5827 .flex_col()
5828 .justify_end()
5829 .gap_2()
5830 .children(
5831 self.notifications
5832 .iter()
5833 .map(|(_, notification)| notification.clone().into_any()),
5834 ),
5835 )
5836 }
5837 }
5838
5839 // RPC handlers
5840
5841 fn active_view_for_follower(
5842 &self,
5843 follower_project_id: Option<u64>,
5844 window: &mut Window,
5845 cx: &mut Context<Self>,
5846 ) -> Option<proto::View> {
5847 let (item, panel_id) = self.active_item_for_followers(window, cx);
5848 let item = item?;
5849 let leader_id = self
5850 .pane_for(&*item)
5851 .and_then(|pane| self.leader_for_pane(&pane));
5852 let leader_peer_id = match leader_id {
5853 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5854 Some(CollaboratorId::Agent) | None => None,
5855 };
5856
5857 let item_handle = item.to_followable_item_handle(cx)?;
5858 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5859 let variant = item_handle.to_state_proto(window, cx)?;
5860
5861 if item_handle.is_project_item(window, cx)
5862 && (follower_project_id.is_none()
5863 || follower_project_id != self.project.read(cx).remote_id())
5864 {
5865 return None;
5866 }
5867
5868 Some(proto::View {
5869 id: id.to_proto(),
5870 leader_id: leader_peer_id,
5871 variant: Some(variant),
5872 panel_id: panel_id.map(|id| id as i32),
5873 })
5874 }
5875
5876 fn handle_follow(
5877 &mut self,
5878 follower_project_id: Option<u64>,
5879 window: &mut Window,
5880 cx: &mut Context<Self>,
5881 ) -> proto::FollowResponse {
5882 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5883
5884 cx.notify();
5885 proto::FollowResponse {
5886 views: active_view.iter().cloned().collect(),
5887 active_view,
5888 }
5889 }
5890
5891 fn handle_update_followers(
5892 &mut self,
5893 leader_id: PeerId,
5894 message: proto::UpdateFollowers,
5895 _window: &mut Window,
5896 _cx: &mut Context<Self>,
5897 ) {
5898 self.leader_updates_tx
5899 .unbounded_send((leader_id, message))
5900 .ok();
5901 }
5902
5903 async fn process_leader_update(
5904 this: &WeakEntity<Self>,
5905 leader_id: PeerId,
5906 update: proto::UpdateFollowers,
5907 cx: &mut AsyncWindowContext,
5908 ) -> Result<()> {
5909 match update.variant.context("invalid update")? {
5910 proto::update_followers::Variant::CreateView(view) => {
5911 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5912 let should_add_view = this.update(cx, |this, _| {
5913 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5914 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5915 } else {
5916 anyhow::Ok(false)
5917 }
5918 })??;
5919
5920 if should_add_view {
5921 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5922 }
5923 }
5924 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5925 let should_add_view = this.update(cx, |this, _| {
5926 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5927 state.active_view_id = update_active_view
5928 .view
5929 .as_ref()
5930 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5931
5932 if state.active_view_id.is_some_and(|view_id| {
5933 !state.items_by_leader_view_id.contains_key(&view_id)
5934 }) {
5935 anyhow::Ok(true)
5936 } else {
5937 anyhow::Ok(false)
5938 }
5939 } else {
5940 anyhow::Ok(false)
5941 }
5942 })??;
5943
5944 if should_add_view && let Some(view) = update_active_view.view {
5945 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5946 }
5947 }
5948 proto::update_followers::Variant::UpdateView(update_view) => {
5949 let variant = update_view.variant.context("missing update view variant")?;
5950 let id = update_view.id.context("missing update view id")?;
5951 let mut tasks = Vec::new();
5952 this.update_in(cx, |this, window, cx| {
5953 let project = this.project.clone();
5954 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5955 let view_id = ViewId::from_proto(id.clone())?;
5956 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5957 tasks.push(item.view.apply_update_proto(
5958 &project,
5959 variant.clone(),
5960 window,
5961 cx,
5962 ));
5963 }
5964 }
5965 anyhow::Ok(())
5966 })??;
5967 try_join_all(tasks).await.log_err();
5968 }
5969 }
5970 this.update_in(cx, |this, window, cx| {
5971 this.leader_updated(leader_id, window, cx)
5972 })?;
5973 Ok(())
5974 }
5975
5976 async fn add_view_from_leader(
5977 this: WeakEntity<Self>,
5978 leader_id: PeerId,
5979 view: &proto::View,
5980 cx: &mut AsyncWindowContext,
5981 ) -> Result<()> {
5982 let this = this.upgrade().context("workspace dropped")?;
5983
5984 let Some(id) = view.id.clone() else {
5985 anyhow::bail!("no id for view");
5986 };
5987 let id = ViewId::from_proto(id)?;
5988 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5989
5990 let pane = this.update(cx, |this, _cx| {
5991 let state = this
5992 .follower_states
5993 .get(&leader_id.into())
5994 .context("stopped following")?;
5995 anyhow::Ok(state.pane().clone())
5996 })?;
5997 let existing_item = pane.update_in(cx, |pane, window, cx| {
5998 let client = this.read(cx).client().clone();
5999 pane.items().find_map(|item| {
6000 let item = item.to_followable_item_handle(cx)?;
6001 if item.remote_id(&client, window, cx) == Some(id) {
6002 Some(item)
6003 } else {
6004 None
6005 }
6006 })
6007 })?;
6008 let item = if let Some(existing_item) = existing_item {
6009 existing_item
6010 } else {
6011 let variant = view.variant.clone();
6012 anyhow::ensure!(variant.is_some(), "missing view variant");
6013
6014 let task = cx.update(|window, cx| {
6015 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
6016 })?;
6017
6018 let Some(task) = task else {
6019 anyhow::bail!(
6020 "failed to construct view from leader (maybe from a different version of zed?)"
6021 );
6022 };
6023
6024 let mut new_item = task.await?;
6025 pane.update_in(cx, |pane, window, cx| {
6026 let mut item_to_remove = None;
6027 for (ix, item) in pane.items().enumerate() {
6028 if let Some(item) = item.to_followable_item_handle(cx) {
6029 match new_item.dedup(item.as_ref(), window, cx) {
6030 Some(item::Dedup::KeepExisting) => {
6031 new_item =
6032 item.boxed_clone().to_followable_item_handle(cx).unwrap();
6033 break;
6034 }
6035 Some(item::Dedup::ReplaceExisting) => {
6036 item_to_remove = Some((ix, item.item_id()));
6037 break;
6038 }
6039 None => {}
6040 }
6041 }
6042 }
6043
6044 if let Some((ix, id)) = item_to_remove {
6045 pane.remove_item(id, false, false, window, cx);
6046 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
6047 }
6048 })?;
6049
6050 new_item
6051 };
6052
6053 this.update_in(cx, |this, window, cx| {
6054 let state = this.follower_states.get_mut(&leader_id.into())?;
6055 item.set_leader_id(Some(leader_id.into()), window, cx);
6056 state.items_by_leader_view_id.insert(
6057 id,
6058 FollowerView {
6059 view: item,
6060 location: panel_id,
6061 },
6062 );
6063
6064 Some(())
6065 })
6066 .context("no follower state")?;
6067
6068 Ok(())
6069 }
6070
6071 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6072 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
6073 return;
6074 };
6075
6076 if let Some(agent_location) = self.project.read(cx).agent_location() {
6077 let buffer_entity_id = agent_location.buffer.entity_id();
6078 let view_id = ViewId {
6079 creator: CollaboratorId::Agent,
6080 id: buffer_entity_id.as_u64(),
6081 };
6082 follower_state.active_view_id = Some(view_id);
6083
6084 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
6085 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
6086 hash_map::Entry::Vacant(entry) => {
6087 let existing_view =
6088 follower_state
6089 .center_pane
6090 .read(cx)
6091 .items()
6092 .find_map(|item| {
6093 let item = item.to_followable_item_handle(cx)?;
6094 if item.buffer_kind(cx) == ItemBufferKind::Singleton
6095 && item.project_item_model_ids(cx).as_slice()
6096 == [buffer_entity_id]
6097 {
6098 Some(item)
6099 } else {
6100 None
6101 }
6102 });
6103 let view = existing_view.or_else(|| {
6104 agent_location.buffer.upgrade().and_then(|buffer| {
6105 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
6106 registry.build_item(buffer, self.project.clone(), None, window, cx)
6107 })?
6108 .to_followable_item_handle(cx)
6109 })
6110 });
6111
6112 view.map(|view| {
6113 entry.insert(FollowerView {
6114 view,
6115 location: None,
6116 })
6117 })
6118 }
6119 };
6120
6121 if let Some(item) = item {
6122 item.view
6123 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
6124 item.view
6125 .update_agent_location(agent_location.position, window, cx);
6126 }
6127 } else {
6128 follower_state.active_view_id = None;
6129 }
6130
6131 self.leader_updated(CollaboratorId::Agent, window, cx);
6132 }
6133
6134 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
6135 let mut is_project_item = true;
6136 let mut update = proto::UpdateActiveView::default();
6137 if window.is_window_active() {
6138 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
6139
6140 if let Some(item) = active_item
6141 && item.item_focus_handle(cx).contains_focused(window, cx)
6142 {
6143 let leader_id = self
6144 .pane_for(&*item)
6145 .and_then(|pane| self.leader_for_pane(&pane));
6146 let leader_peer_id = match leader_id {
6147 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
6148 Some(CollaboratorId::Agent) | None => None,
6149 };
6150
6151 if let Some(item) = item.to_followable_item_handle(cx) {
6152 let id = item
6153 .remote_id(&self.app_state.client, window, cx)
6154 .map(|id| id.to_proto());
6155
6156 if let Some(id) = id
6157 && let Some(variant) = item.to_state_proto(window, cx)
6158 {
6159 let view = Some(proto::View {
6160 id,
6161 leader_id: leader_peer_id,
6162 variant: Some(variant),
6163 panel_id: panel_id.map(|id| id as i32),
6164 });
6165
6166 is_project_item = item.is_project_item(window, cx);
6167 update = proto::UpdateActiveView { view };
6168 };
6169 }
6170 }
6171 }
6172
6173 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
6174 if active_view_id != self.last_active_view_id.as_ref() {
6175 self.last_active_view_id = active_view_id.cloned();
6176 self.update_followers(
6177 is_project_item,
6178 proto::update_followers::Variant::UpdateActiveView(update),
6179 window,
6180 cx,
6181 );
6182 }
6183 }
6184
6185 fn active_item_for_followers(
6186 &self,
6187 window: &mut Window,
6188 cx: &mut App,
6189 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
6190 let mut active_item = None;
6191 let mut panel_id = None;
6192 for dock in self.all_docks() {
6193 if dock.focus_handle(cx).contains_focused(window, cx)
6194 && let Some(panel) = dock.read(cx).active_panel()
6195 && let Some(pane) = panel.pane(cx)
6196 && let Some(item) = pane.read(cx).active_item()
6197 {
6198 active_item = Some(item);
6199 panel_id = panel.remote_id();
6200 break;
6201 }
6202 }
6203
6204 if active_item.is_none() {
6205 active_item = self.active_pane().read(cx).active_item();
6206 }
6207 (active_item, panel_id)
6208 }
6209
6210 fn update_followers(
6211 &self,
6212 project_only: bool,
6213 update: proto::update_followers::Variant,
6214 _: &mut Window,
6215 cx: &mut App,
6216 ) -> Option<()> {
6217 // If this update only applies to for followers in the current project,
6218 // then skip it unless this project is shared. If it applies to all
6219 // followers, regardless of project, then set `project_id` to none,
6220 // indicating that it goes to all followers.
6221 let project_id = if project_only {
6222 Some(self.project.read(cx).remote_id()?)
6223 } else {
6224 None
6225 };
6226 self.app_state().workspace_store.update(cx, |store, cx| {
6227 store.update_followers(project_id, update, cx)
6228 })
6229 }
6230
6231 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
6232 self.follower_states.iter().find_map(|(leader_id, state)| {
6233 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
6234 Some(*leader_id)
6235 } else {
6236 None
6237 }
6238 })
6239 }
6240
6241 fn leader_updated(
6242 &mut self,
6243 leader_id: impl Into<CollaboratorId>,
6244 window: &mut Window,
6245 cx: &mut Context<Self>,
6246 ) -> Option<Box<dyn ItemHandle>> {
6247 cx.notify();
6248
6249 let leader_id = leader_id.into();
6250 let (panel_id, item) = match leader_id {
6251 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
6252 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
6253 };
6254
6255 let state = self.follower_states.get(&leader_id)?;
6256 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
6257 let pane;
6258 if let Some(panel_id) = panel_id {
6259 pane = self
6260 .activate_panel_for_proto_id(panel_id, window, cx)?
6261 .pane(cx)?;
6262 let state = self.follower_states.get_mut(&leader_id)?;
6263 state.dock_pane = Some(pane.clone());
6264 } else {
6265 pane = state.center_pane.clone();
6266 let state = self.follower_states.get_mut(&leader_id)?;
6267 if let Some(dock_pane) = state.dock_pane.take() {
6268 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
6269 }
6270 }
6271
6272 pane.update(cx, |pane, cx| {
6273 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
6274 if let Some(index) = pane.index_for_item(item.as_ref()) {
6275 pane.activate_item(index, false, false, window, cx);
6276 } else {
6277 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
6278 }
6279
6280 if focus_active_item {
6281 pane.focus_active_item(window, cx)
6282 }
6283 });
6284
6285 Some(item)
6286 }
6287
6288 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
6289 let state = self.follower_states.get(&CollaboratorId::Agent)?;
6290 let active_view_id = state.active_view_id?;
6291 Some(
6292 state
6293 .items_by_leader_view_id
6294 .get(&active_view_id)?
6295 .view
6296 .boxed_clone(),
6297 )
6298 }
6299
6300 fn active_item_for_peer(
6301 &self,
6302 peer_id: PeerId,
6303 window: &mut Window,
6304 cx: &mut Context<Self>,
6305 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
6306 let call = self.active_call()?;
6307 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
6308 let leader_in_this_app;
6309 let leader_in_this_project;
6310 match participant.location {
6311 ParticipantLocation::SharedProject { project_id } => {
6312 leader_in_this_app = true;
6313 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
6314 }
6315 ParticipantLocation::UnsharedProject => {
6316 leader_in_this_app = true;
6317 leader_in_this_project = false;
6318 }
6319 ParticipantLocation::External => {
6320 leader_in_this_app = false;
6321 leader_in_this_project = false;
6322 }
6323 };
6324 let state = self.follower_states.get(&peer_id.into())?;
6325 let mut item_to_activate = None;
6326 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
6327 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
6328 && (leader_in_this_project || !item.view.is_project_item(window, cx))
6329 {
6330 item_to_activate = Some((item.location, item.view.boxed_clone()));
6331 }
6332 } else if let Some(shared_screen) =
6333 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
6334 {
6335 item_to_activate = Some((None, Box::new(shared_screen)));
6336 }
6337 item_to_activate
6338 }
6339
6340 fn shared_screen_for_peer(
6341 &self,
6342 peer_id: PeerId,
6343 pane: &Entity<Pane>,
6344 window: &mut Window,
6345 cx: &mut App,
6346 ) -> Option<Entity<SharedScreen>> {
6347 self.active_call()?
6348 .create_shared_screen(peer_id, pane, window, cx)
6349 }
6350
6351 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6352 if window.is_window_active() {
6353 self.update_active_view_for_followers(window, cx);
6354
6355 if let Some(database_id) = self.database_id {
6356 let db = WorkspaceDb::global(cx);
6357 cx.background_spawn(async move { db.update_timestamp(database_id).await })
6358 .detach();
6359 }
6360 } else {
6361 for pane in &self.panes {
6362 pane.update(cx, |pane, cx| {
6363 if let Some(item) = pane.active_item() {
6364 item.workspace_deactivated(window, cx);
6365 }
6366 for item in pane.items() {
6367 if matches!(
6368 item.workspace_settings(cx).autosave,
6369 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
6370 ) {
6371 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
6372 .detach_and_log_err(cx);
6373 }
6374 }
6375 });
6376 }
6377 }
6378 }
6379
6380 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
6381 self.active_call.as_ref().map(|(call, _)| &*call.0)
6382 }
6383
6384 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
6385 self.active_call.as_ref().map(|(call, _)| call.clone())
6386 }
6387
6388 fn on_active_call_event(
6389 &mut self,
6390 event: &ActiveCallEvent,
6391 window: &mut Window,
6392 cx: &mut Context<Self>,
6393 ) {
6394 match event {
6395 ActiveCallEvent::ParticipantLocationChanged { participant_id }
6396 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
6397 self.leader_updated(participant_id, window, cx);
6398 }
6399 }
6400 }
6401
6402 pub fn database_id(&self) -> Option<WorkspaceId> {
6403 self.database_id
6404 }
6405
6406 #[cfg(any(test, feature = "test-support"))]
6407 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
6408 self.database_id = Some(id);
6409 }
6410
6411 pub fn session_id(&self) -> Option<String> {
6412 self.session_id.clone()
6413 }
6414
6415 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6416 let Some(display) = window.display(cx) else {
6417 return Task::ready(());
6418 };
6419 let Ok(display_uuid) = display.uuid() else {
6420 return Task::ready(());
6421 };
6422
6423 let window_bounds = window.inner_window_bounds();
6424 let database_id = self.database_id;
6425 let has_paths = !self.root_paths(cx).is_empty();
6426 let db = WorkspaceDb::global(cx);
6427 let kvp = db::kvp::KeyValueStore::global(cx);
6428
6429 cx.background_executor().spawn(async move {
6430 if !has_paths {
6431 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6432 .await
6433 .log_err();
6434 }
6435 if let Some(database_id) = database_id {
6436 db.set_window_open_status(
6437 database_id,
6438 SerializedWindowBounds(window_bounds),
6439 display_uuid,
6440 )
6441 .await
6442 .log_err();
6443 } else {
6444 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6445 .await
6446 .log_err();
6447 }
6448 })
6449 }
6450
6451 /// Bypass the 200ms serialization throttle and write workspace state to
6452 /// the DB immediately. Returns a task the caller can await to ensure the
6453 /// write completes. Used by the quit handler so the most recent state
6454 /// isn't lost to a pending throttle timer when the process exits.
6455 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6456 self._schedule_serialize_workspace.take();
6457 self._serialize_workspace_task.take();
6458 self.bounds_save_task_queued.take();
6459
6460 let bounds_task = self.save_window_bounds(window, cx);
6461 let serialize_task = self.serialize_workspace_internal(window, cx);
6462 cx.spawn(async move |_| {
6463 bounds_task.await;
6464 serialize_task.await;
6465 })
6466 }
6467
6468 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6469 let project = self.project().read(cx);
6470 project
6471 .visible_worktrees(cx)
6472 .map(|worktree| worktree.read(cx).abs_path())
6473 .collect::<Vec<_>>()
6474 }
6475
6476 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6477 match member {
6478 Member::Axis(PaneAxis { members, .. }) => {
6479 for child in members.iter() {
6480 self.remove_panes(child.clone(), window, cx)
6481 }
6482 }
6483 Member::Pane(pane) => {
6484 self.force_remove_pane(&pane, &None, window, cx);
6485 }
6486 }
6487 }
6488
6489 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6490 self.session_id.take();
6491 self.serialize_workspace_internal(window, cx)
6492 }
6493
6494 fn force_remove_pane(
6495 &mut self,
6496 pane: &Entity<Pane>,
6497 focus_on: &Option<Entity<Pane>>,
6498 window: &mut Window,
6499 cx: &mut Context<Workspace>,
6500 ) {
6501 self.panes.retain(|p| p != pane);
6502 if let Some(focus_on) = focus_on {
6503 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6504 } else if self.active_pane() == pane {
6505 let fallback_pane = self.panes.last().unwrap().clone();
6506 if self.has_active_modal(window, cx) {
6507 self.set_active_pane(&fallback_pane, window, cx);
6508 } else {
6509 fallback_pane.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6510 }
6511 }
6512 if self.last_active_center_pane == Some(pane.downgrade()) {
6513 self.last_active_center_pane = None;
6514 }
6515 cx.notify();
6516 }
6517
6518 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6519 if self._schedule_serialize_workspace.is_none() {
6520 self._schedule_serialize_workspace =
6521 Some(cx.spawn_in(window, async move |this, cx| {
6522 cx.background_executor()
6523 .timer(SERIALIZATION_THROTTLE_TIME)
6524 .await;
6525 this.update_in(cx, |this, window, cx| {
6526 this._serialize_workspace_task =
6527 Some(this.serialize_workspace_internal(window, cx));
6528 this._schedule_serialize_workspace.take();
6529 })
6530 .log_err();
6531 }));
6532 }
6533 }
6534
6535 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6536 let Some(database_id) = self.database_id() else {
6537 return Task::ready(());
6538 };
6539
6540 fn serialize_pane_handle(
6541 pane_handle: &Entity<Pane>,
6542 window: &mut Window,
6543 cx: &mut App,
6544 ) -> SerializedPane {
6545 let (items, active, pinned_count) = {
6546 let pane = pane_handle.read(cx);
6547 let active_item_id = pane.active_item().map(|item| item.item_id());
6548 (
6549 pane.items()
6550 .filter_map(|handle| {
6551 let handle = handle.to_serializable_item_handle(cx)?;
6552
6553 Some(SerializedItem {
6554 kind: Arc::from(handle.serialized_item_kind()),
6555 item_id: handle.item_id().as_u64(),
6556 active: Some(handle.item_id()) == active_item_id,
6557 preview: pane.is_active_preview_item(handle.item_id()),
6558 })
6559 })
6560 .collect::<Vec<_>>(),
6561 pane.has_focus(window, cx),
6562 pane.pinned_count(),
6563 )
6564 };
6565
6566 SerializedPane::new(items, active, pinned_count)
6567 }
6568
6569 fn build_serialized_pane_group(
6570 pane_group: &Member,
6571 window: &mut Window,
6572 cx: &mut App,
6573 ) -> SerializedPaneGroup {
6574 match pane_group {
6575 Member::Axis(PaneAxis {
6576 axis,
6577 members,
6578 flexes,
6579 bounding_boxes: _,
6580 }) => SerializedPaneGroup::Group {
6581 axis: SerializedAxis(*axis),
6582 children: members
6583 .iter()
6584 .map(|member| build_serialized_pane_group(member, window, cx))
6585 .collect::<Vec<_>>(),
6586 flexes: Some(flexes.lock().clone()),
6587 },
6588 Member::Pane(pane_handle) => {
6589 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6590 }
6591 }
6592 }
6593
6594 fn build_serialized_docks(
6595 this: &Workspace,
6596 window: &mut Window,
6597 cx: &mut App,
6598 ) -> DockStructure {
6599 this.capture_dock_state(window, cx)
6600 }
6601
6602 match self.workspace_location(cx) {
6603 WorkspaceLocation::Location(location, paths) => {
6604 let breakpoints = self.project.update(cx, |project, cx| {
6605 project
6606 .breakpoint_store()
6607 .read(cx)
6608 .all_source_breakpoints(cx)
6609 });
6610 let user_toolchains = self
6611 .project
6612 .read(cx)
6613 .user_toolchains(cx)
6614 .unwrap_or_default();
6615
6616 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6617 let docks = build_serialized_docks(self, window, cx);
6618 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6619
6620 let serialized_workspace = SerializedWorkspace {
6621 id: database_id,
6622 location,
6623 paths,
6624 center_group,
6625 window_bounds,
6626 display: Default::default(),
6627 docks,
6628 centered_layout: self.centered_layout,
6629 session_id: self.session_id.clone(),
6630 breakpoints,
6631 window_id: Some(window.window_handle().window_id().as_u64()),
6632 user_toolchains,
6633 };
6634
6635 let db = WorkspaceDb::global(cx);
6636 window.spawn(cx, async move |_| {
6637 db.save_workspace(serialized_workspace).await;
6638 })
6639 }
6640 WorkspaceLocation::DetachFromSession => {
6641 let window_bounds = SerializedWindowBounds(window.window_bounds());
6642 let display = window.display(cx).and_then(|d| d.uuid().ok());
6643 // Save dock state for empty local workspaces
6644 let docks = build_serialized_docks(self, window, cx);
6645 let db = WorkspaceDb::global(cx);
6646 let kvp = db::kvp::KeyValueStore::global(cx);
6647 window.spawn(cx, async move |_| {
6648 db.set_window_open_status(
6649 database_id,
6650 window_bounds,
6651 display.unwrap_or_default(),
6652 )
6653 .await
6654 .log_err();
6655 db.set_session_id(database_id, None).await.log_err();
6656 persistence::write_default_dock_state(&kvp, docks)
6657 .await
6658 .log_err();
6659 })
6660 }
6661 WorkspaceLocation::None => {
6662 // Save dock state for empty non-local workspaces
6663 let docks = build_serialized_docks(self, window, cx);
6664 let kvp = db::kvp::KeyValueStore::global(cx);
6665 window.spawn(cx, async move |_| {
6666 persistence::write_default_dock_state(&kvp, docks)
6667 .await
6668 .log_err();
6669 })
6670 }
6671 }
6672 }
6673
6674 fn has_any_items_open(&self, cx: &App) -> bool {
6675 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6676 }
6677
6678 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6679 let paths = PathList::new(&self.root_paths(cx));
6680 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6681 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6682 } else if self.project.read(cx).is_local() {
6683 if !paths.is_empty() || self.has_any_items_open(cx) {
6684 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6685 } else {
6686 WorkspaceLocation::DetachFromSession
6687 }
6688 } else {
6689 WorkspaceLocation::None
6690 }
6691 }
6692
6693 fn update_history(&self, cx: &mut App) {
6694 let Some(id) = self.database_id() else {
6695 return;
6696 };
6697 if !self.project.read(cx).is_local() {
6698 return;
6699 }
6700 if let Some(manager) = HistoryManager::global(cx) {
6701 let paths = PathList::new(&self.root_paths(cx));
6702 manager.update(cx, |this, cx| {
6703 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6704 });
6705 }
6706 }
6707
6708 async fn serialize_items(
6709 this: &WeakEntity<Self>,
6710 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6711 cx: &mut AsyncWindowContext,
6712 ) -> Result<()> {
6713 const CHUNK_SIZE: usize = 200;
6714
6715 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6716
6717 while let Some(items_received) = serializable_items.next().await {
6718 let unique_items =
6719 items_received
6720 .into_iter()
6721 .fold(HashMap::default(), |mut acc, item| {
6722 acc.entry(item.item_id()).or_insert(item);
6723 acc
6724 });
6725
6726 // We use into_iter() here so that the references to the items are moved into
6727 // the tasks and not kept alive while we're sleeping.
6728 for (_, item) in unique_items.into_iter() {
6729 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6730 item.serialize(workspace, false, window, cx)
6731 }) {
6732 cx.background_spawn(async move { task.await.log_err() })
6733 .detach();
6734 }
6735 }
6736
6737 cx.background_executor()
6738 .timer(SERIALIZATION_THROTTLE_TIME)
6739 .await;
6740 }
6741
6742 Ok(())
6743 }
6744
6745 pub(crate) fn enqueue_item_serialization(
6746 &mut self,
6747 item: Box<dyn SerializableItemHandle>,
6748 ) -> Result<()> {
6749 self.serializable_items_tx
6750 .unbounded_send(item)
6751 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6752 }
6753
6754 pub(crate) fn load_workspace(
6755 serialized_workspace: SerializedWorkspace,
6756 paths_to_open: Vec<Option<ProjectPath>>,
6757 window: &mut Window,
6758 cx: &mut Context<Workspace>,
6759 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6760 cx.spawn_in(window, async move |workspace, cx| {
6761 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6762
6763 let mut center_group = None;
6764 let mut center_items = None;
6765
6766 // Traverse the splits tree and add to things
6767 if let Some((group, active_pane, items)) = serialized_workspace
6768 .center_group
6769 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6770 .await
6771 {
6772 center_items = Some(items);
6773 center_group = Some((group, active_pane))
6774 }
6775
6776 let mut items_by_project_path = HashMap::default();
6777 let mut item_ids_by_kind = HashMap::default();
6778 let mut all_deserialized_items = Vec::default();
6779 cx.update(|_, cx| {
6780 for item in center_items.unwrap_or_default().into_iter().flatten() {
6781 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6782 item_ids_by_kind
6783 .entry(serializable_item_handle.serialized_item_kind())
6784 .or_insert(Vec::new())
6785 .push(item.item_id().as_u64() as ItemId);
6786 }
6787
6788 if let Some(project_path) = item.project_path(cx) {
6789 items_by_project_path.insert(project_path, item.clone());
6790 }
6791 all_deserialized_items.push(item);
6792 }
6793 })?;
6794
6795 let opened_items = paths_to_open
6796 .into_iter()
6797 .map(|path_to_open| {
6798 path_to_open
6799 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6800 })
6801 .collect::<Vec<_>>();
6802
6803 // Remove old panes from workspace panes list
6804 workspace.update_in(cx, |workspace, window, cx| {
6805 if let Some((center_group, active_pane)) = center_group {
6806 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6807
6808 // Swap workspace center group
6809 workspace.center = PaneGroup::with_root(center_group);
6810 workspace.center.set_is_center(true);
6811 workspace.center.mark_positions(cx);
6812
6813 if let Some(active_pane) = active_pane {
6814 workspace.set_active_pane(&active_pane, window, cx);
6815 cx.focus_self(window);
6816 } else {
6817 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6818 }
6819 }
6820
6821 let docks = serialized_workspace.docks;
6822
6823 for (dock, serialized_dock) in [
6824 (&mut workspace.right_dock, docks.right),
6825 (&mut workspace.left_dock, docks.left),
6826 (&mut workspace.bottom_dock, docks.bottom),
6827 ]
6828 .iter_mut()
6829 {
6830 dock.update(cx, |dock, cx| {
6831 dock.serialized_dock = Some(serialized_dock.clone());
6832 dock.restore_state(window, cx);
6833 });
6834 }
6835
6836 cx.notify();
6837 })?;
6838
6839 let _ = project
6840 .update(cx, |project, cx| {
6841 project
6842 .breakpoint_store()
6843 .update(cx, |breakpoint_store, cx| {
6844 breakpoint_store
6845 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6846 })
6847 })
6848 .await;
6849
6850 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6851 // after loading the items, we might have different items and in order to avoid
6852 // the database filling up, we delete items that haven't been loaded now.
6853 //
6854 // The items that have been loaded, have been saved after they've been added to the workspace.
6855 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6856 item_ids_by_kind
6857 .into_iter()
6858 .map(|(item_kind, loaded_items)| {
6859 SerializableItemRegistry::cleanup(
6860 item_kind,
6861 serialized_workspace.id,
6862 loaded_items,
6863 window,
6864 cx,
6865 )
6866 .log_err()
6867 })
6868 .collect::<Vec<_>>()
6869 })?;
6870
6871 futures::future::join_all(clean_up_tasks).await;
6872
6873 workspace
6874 .update_in(cx, |workspace, window, cx| {
6875 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6876 workspace.serialize_workspace_internal(window, cx).detach();
6877
6878 // Ensure that we mark the window as edited if we did load dirty items
6879 workspace.update_window_edited(window, cx);
6880 })
6881 .ok();
6882
6883 Ok(opened_items)
6884 })
6885 }
6886
6887 pub fn key_context(&self, cx: &App) -> KeyContext {
6888 let mut context = KeyContext::new_with_defaults();
6889 context.add("Workspace");
6890 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6891 if let Some(status) = self
6892 .debugger_provider
6893 .as_ref()
6894 .and_then(|provider| provider.active_thread_state(cx))
6895 {
6896 match status {
6897 ThreadStatus::Running | ThreadStatus::Stepping => {
6898 context.add("debugger_running");
6899 }
6900 ThreadStatus::Stopped => context.add("debugger_stopped"),
6901 ThreadStatus::Exited | ThreadStatus::Ended => {}
6902 }
6903 }
6904
6905 if self.left_dock.read(cx).is_open() {
6906 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6907 context.set("left_dock", active_panel.panel_key());
6908 }
6909 }
6910
6911 if self.right_dock.read(cx).is_open() {
6912 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6913 context.set("right_dock", active_panel.panel_key());
6914 }
6915 }
6916
6917 if self.bottom_dock.read(cx).is_open() {
6918 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6919 context.set("bottom_dock", active_panel.panel_key());
6920 }
6921 }
6922
6923 context
6924 }
6925
6926 /// Multiworkspace uses this to add workspace action handling to itself
6927 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6928 self.add_workspace_actions_listeners(div, window, cx)
6929 .on_action(cx.listener(
6930 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6931 for action in &action_sequence.0 {
6932 window.dispatch_action(action.boxed_clone(), cx);
6933 }
6934 },
6935 ))
6936 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6937 .on_action(cx.listener(Self::close_all_items_and_panes))
6938 .on_action(cx.listener(Self::close_item_in_all_panes))
6939 .on_action(cx.listener(Self::save_all))
6940 .on_action(cx.listener(Self::send_keystrokes))
6941 .on_action(cx.listener(Self::add_folder_to_project))
6942 .on_action(cx.listener(Self::follow_next_collaborator))
6943 .on_action(cx.listener(Self::activate_pane_at_index))
6944 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6945 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6946 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6947 .on_action(cx.listener(Self::toggle_theme_mode))
6948 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6949 let pane = workspace.active_pane().clone();
6950 workspace.unfollow_in_pane(&pane, window, cx);
6951 }))
6952 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6953 workspace
6954 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6955 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6956 }))
6957 .on_action(cx.listener(|workspace, _: &FormatAndSave, window, cx| {
6958 workspace
6959 .save_active_item(SaveIntent::FormatAndSave, window, cx)
6960 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6961 }))
6962 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6963 workspace
6964 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6965 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6966 }))
6967 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6968 workspace
6969 .save_active_item(SaveIntent::SaveAs, window, cx)
6970 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6971 }))
6972 .on_action(
6973 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6974 workspace.activate_previous_pane(window, cx)
6975 }),
6976 )
6977 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6978 workspace.activate_next_pane(window, cx)
6979 }))
6980 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6981 workspace.activate_last_pane(window, cx)
6982 }))
6983 .on_action(
6984 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6985 workspace.activate_next_window(cx)
6986 }),
6987 )
6988 .on_action(
6989 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6990 workspace.activate_previous_window(cx)
6991 }),
6992 )
6993 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6994 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6995 }))
6996 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6997 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6998 }))
6999 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
7000 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
7001 }))
7002 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
7003 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
7004 }))
7005 .on_action(cx.listener(
7006 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
7007 workspace.move_item_to_pane_in_direction(action, window, cx)
7008 },
7009 ))
7010 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
7011 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
7012 }))
7013 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
7014 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
7015 }))
7016 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
7017 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
7018 }))
7019 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
7020 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
7021 }))
7022 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
7023 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
7024 SplitDirection::Down,
7025 SplitDirection::Up,
7026 SplitDirection::Right,
7027 SplitDirection::Left,
7028 ];
7029 for dir in DIRECTION_PRIORITY {
7030 if workspace.find_pane_in_direction(dir, cx).is_some() {
7031 workspace.swap_pane_in_direction(dir, cx);
7032 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
7033 break;
7034 }
7035 }
7036 }))
7037 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
7038 workspace.move_pane_to_border(SplitDirection::Left, cx)
7039 }))
7040 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
7041 workspace.move_pane_to_border(SplitDirection::Right, cx)
7042 }))
7043 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
7044 workspace.move_pane_to_border(SplitDirection::Up, cx)
7045 }))
7046 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
7047 workspace.move_pane_to_border(SplitDirection::Down, cx)
7048 }))
7049 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
7050 this.toggle_dock(DockPosition::Left, window, cx);
7051 }))
7052 .on_action(cx.listener(
7053 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
7054 workspace.toggle_dock(DockPosition::Right, window, cx);
7055 },
7056 ))
7057 .on_action(cx.listener(
7058 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
7059 workspace.toggle_dock(DockPosition::Bottom, window, cx);
7060 },
7061 ))
7062 .on_action(cx.listener(
7063 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
7064 if !workspace.close_active_dock(window, cx) {
7065 cx.propagate();
7066 }
7067 },
7068 ))
7069 .on_action(
7070 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
7071 workspace.close_all_docks(window, cx);
7072 }),
7073 )
7074 .on_action(cx.listener(Self::toggle_all_docks))
7075 .on_action(cx.listener(
7076 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
7077 workspace.clear_all_notifications(cx);
7078 },
7079 ))
7080 .on_action(cx.listener(
7081 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
7082 workspace.clear_navigation_history(window, cx);
7083 },
7084 ))
7085 .on_action(cx.listener(
7086 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
7087 if let Some((notification_id, _)) = workspace.notifications.pop() {
7088 workspace.suppress_notification(¬ification_id, cx);
7089 }
7090 },
7091 ))
7092 .on_action(cx.listener(
7093 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
7094 workspace.show_worktree_trust_security_modal(true, window, cx);
7095 },
7096 ))
7097 .on_action(
7098 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
7099 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
7100 trusted_worktrees.update(cx, |trusted_worktrees, _| {
7101 trusted_worktrees.clear_trusted_paths()
7102 });
7103 let db = WorkspaceDb::global(cx);
7104 cx.spawn(async move |_, cx| {
7105 if db.clear_trusted_worktrees().await.log_err().is_some() {
7106 cx.update(|cx| reload(cx));
7107 }
7108 })
7109 .detach();
7110 }
7111 }),
7112 )
7113 .on_action(cx.listener(
7114 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
7115 workspace.reopen_closed_item(window, cx).detach();
7116 },
7117 ))
7118 .on_action(cx.listener(
7119 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
7120 for dock in workspace.all_docks() {
7121 if dock.focus_handle(cx).contains_focused(window, cx) {
7122 let panel = dock.read(cx).active_panel().cloned();
7123 if let Some(panel) = panel {
7124 dock.update(cx, |dock, cx| {
7125 dock.set_panel_size_state(
7126 panel.as_ref(),
7127 dock::PanelSizeState::default(),
7128 cx,
7129 );
7130 });
7131 }
7132 return;
7133 }
7134 }
7135 },
7136 ))
7137 .on_action(cx.listener(
7138 |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
7139 for dock in workspace.all_docks() {
7140 let panel = dock.read(cx).visible_panel().cloned();
7141 if let Some(panel) = panel {
7142 dock.update(cx, |dock, cx| {
7143 dock.set_panel_size_state(
7144 panel.as_ref(),
7145 dock::PanelSizeState::default(),
7146 cx,
7147 );
7148 });
7149 }
7150 }
7151 },
7152 ))
7153 .on_action(cx.listener(
7154 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
7155 adjust_active_dock_size_by_px(
7156 px_with_ui_font_fallback(act.px, cx),
7157 workspace,
7158 window,
7159 cx,
7160 );
7161 },
7162 ))
7163 .on_action(cx.listener(
7164 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
7165 adjust_active_dock_size_by_px(
7166 px_with_ui_font_fallback(act.px, cx) * -1.,
7167 workspace,
7168 window,
7169 cx,
7170 );
7171 },
7172 ))
7173 .on_action(cx.listener(
7174 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
7175 adjust_open_docks_size_by_px(
7176 px_with_ui_font_fallback(act.px, cx),
7177 workspace,
7178 window,
7179 cx,
7180 );
7181 },
7182 ))
7183 .on_action(cx.listener(
7184 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
7185 adjust_open_docks_size_by_px(
7186 px_with_ui_font_fallback(act.px, cx) * -1.,
7187 workspace,
7188 window,
7189 cx,
7190 );
7191 },
7192 ))
7193 .on_action(cx.listener(Workspace::toggle_centered_layout))
7194 .on_action(cx.listener(
7195 |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
7196 if let Some(active_dock) = workspace.active_dock(window, cx) {
7197 let dock = active_dock.read(cx);
7198 if let Some(active_panel) = dock.active_panel() {
7199 if active_panel.pane(cx).is_none() {
7200 let mut recent_pane: Option<Entity<Pane>> = None;
7201 let mut recent_timestamp = 0;
7202 for pane_handle in workspace.panes() {
7203 let pane = pane_handle.read(cx);
7204 for entry in pane.activation_history() {
7205 if entry.timestamp > recent_timestamp {
7206 recent_timestamp = entry.timestamp;
7207 recent_pane = Some(pane_handle.clone());
7208 }
7209 }
7210 }
7211
7212 if let Some(pane) = recent_pane {
7213 let wrap_around = action.wrap_around;
7214 pane.update(cx, |pane, cx| {
7215 let current_index = pane.active_item_index();
7216 let items_len = pane.items_len();
7217 if items_len > 0 {
7218 let next_index = if current_index + 1 < items_len {
7219 current_index + 1
7220 } else if wrap_around {
7221 0
7222 } else {
7223 return;
7224 };
7225 pane.activate_item(
7226 next_index, false, false, window, cx,
7227 );
7228 }
7229 });
7230 return;
7231 }
7232 }
7233 }
7234 }
7235 cx.propagate();
7236 },
7237 ))
7238 .on_action(cx.listener(
7239 |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
7240 if let Some(active_dock) = workspace.active_dock(window, cx) {
7241 let dock = active_dock.read(cx);
7242 if let Some(active_panel) = dock.active_panel() {
7243 if active_panel.pane(cx).is_none() {
7244 let mut recent_pane: Option<Entity<Pane>> = None;
7245 let mut recent_timestamp = 0;
7246 for pane_handle in workspace.panes() {
7247 let pane = pane_handle.read(cx);
7248 for entry in pane.activation_history() {
7249 if entry.timestamp > recent_timestamp {
7250 recent_timestamp = entry.timestamp;
7251 recent_pane = Some(pane_handle.clone());
7252 }
7253 }
7254 }
7255
7256 if let Some(pane) = recent_pane {
7257 let wrap_around = action.wrap_around;
7258 pane.update(cx, |pane, cx| {
7259 let current_index = pane.active_item_index();
7260 let items_len = pane.items_len();
7261 if items_len > 0 {
7262 let prev_index = if current_index > 0 {
7263 current_index - 1
7264 } else if wrap_around {
7265 items_len.saturating_sub(1)
7266 } else {
7267 return;
7268 };
7269 pane.activate_item(
7270 prev_index, false, false, window, cx,
7271 );
7272 }
7273 });
7274 return;
7275 }
7276 }
7277 }
7278 }
7279 cx.propagate();
7280 },
7281 ))
7282 .on_action(cx.listener(
7283 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
7284 if let Some(active_dock) = workspace.active_dock(window, cx) {
7285 let dock = active_dock.read(cx);
7286 if let Some(active_panel) = dock.active_panel() {
7287 if active_panel.pane(cx).is_none() {
7288 let active_pane = workspace.active_pane().clone();
7289 active_pane.update(cx, |pane, cx| {
7290 pane.close_active_item(action, window, cx)
7291 .detach_and_log_err(cx);
7292 });
7293 return;
7294 }
7295 }
7296 }
7297 cx.propagate();
7298 },
7299 ))
7300 .on_action(
7301 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
7302 let pane = workspace.active_pane().clone();
7303 if let Some(item) = pane.read(cx).active_item() {
7304 item.toggle_read_only(window, cx);
7305 }
7306 }),
7307 )
7308 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
7309 workspace.focus_center_pane(window, cx);
7310 }))
7311 .on_action(cx.listener(Workspace::cancel))
7312 }
7313
7314 #[cfg(any(test, feature = "test-support"))]
7315 pub fn set_random_database_id(&mut self) {
7316 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
7317 }
7318
7319 #[cfg(any(test, feature = "test-support"))]
7320 pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
7321 use node_runtime::NodeRuntime;
7322 use session::Session;
7323
7324 let client = project.read(cx).client();
7325 let user_store = project.read(cx).user_store();
7326 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
7327 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
7328 window.activate_window();
7329 let app_state = Arc::new(AppState {
7330 languages: project.read(cx).languages().clone(),
7331 workspace_store,
7332 client,
7333 user_store,
7334 fs: project.read(cx).fs().clone(),
7335 build_window_options: |_, _| Default::default(),
7336 node_runtime: NodeRuntime::unavailable(),
7337 session,
7338 });
7339 let workspace = Self::new(Default::default(), project, app_state, window, cx);
7340 workspace
7341 .active_pane
7342 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
7343 workspace
7344 }
7345
7346 pub fn register_action<A: Action>(
7347 &mut self,
7348 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
7349 ) -> &mut Self {
7350 let callback = Arc::new(callback);
7351
7352 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
7353 let callback = callback.clone();
7354 div.on_action(cx.listener(move |workspace, event, window, cx| {
7355 (callback)(workspace, event, window, cx)
7356 }))
7357 }));
7358 self
7359 }
7360 pub fn register_action_renderer(
7361 &mut self,
7362 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
7363 ) -> &mut Self {
7364 self.workspace_actions.push(Box::new(callback));
7365 self
7366 }
7367
7368 fn add_workspace_actions_listeners(
7369 &self,
7370 mut div: Div,
7371 window: &mut Window,
7372 cx: &mut Context<Self>,
7373 ) -> Div {
7374 for action in self.workspace_actions.iter() {
7375 div = (action)(div, self, window, cx)
7376 }
7377 div
7378 }
7379
7380 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
7381 self.modal_layer.read(cx).has_active_modal()
7382 }
7383
7384 pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
7385 self.modal_layer
7386 .read(cx)
7387 .is_active_modal_command_palette(cx)
7388 }
7389
7390 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
7391 self.modal_layer.read(cx).active_modal()
7392 }
7393
7394 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
7395 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
7396 /// If no modal is active, the new modal will be shown.
7397 ///
7398 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
7399 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
7400 /// will not be shown.
7401 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
7402 where
7403 B: FnOnce(&mut Window, &mut Context<V>) -> V,
7404 {
7405 self.modal_layer.update(cx, |modal_layer, cx| {
7406 modal_layer.toggle_modal(window, cx, build)
7407 })
7408 }
7409
7410 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
7411 self.modal_layer
7412 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
7413 }
7414
7415 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
7416 self.toast_layer
7417 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
7418 }
7419
7420 pub fn toggle_centered_layout(
7421 &mut self,
7422 _: &ToggleCenteredLayout,
7423 _: &mut Window,
7424 cx: &mut Context<Self>,
7425 ) {
7426 self.centered_layout = !self.centered_layout;
7427 if let Some(database_id) = self.database_id() {
7428 let db = WorkspaceDb::global(cx);
7429 let centered_layout = self.centered_layout;
7430 cx.background_spawn(async move {
7431 db.set_centered_layout(database_id, centered_layout).await
7432 })
7433 .detach_and_log_err(cx);
7434 }
7435 cx.notify();
7436 }
7437
7438 fn adjust_padding(padding: Option<f32>) -> f32 {
7439 padding
7440 .unwrap_or(CenteredPaddingSettings::default().0)
7441 .clamp(
7442 CenteredPaddingSettings::MIN_PADDING,
7443 CenteredPaddingSettings::MAX_PADDING,
7444 )
7445 }
7446
7447 fn render_dock(
7448 &self,
7449 position: DockPosition,
7450 dock: &Entity<Dock>,
7451 window: &mut Window,
7452 cx: &mut App,
7453 ) -> Option<Div> {
7454 if self.zoomed_position == Some(position) {
7455 return None;
7456 }
7457
7458 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7459 let pane = panel.pane(cx)?;
7460 let follower_states = &self.follower_states;
7461 leader_border_for_pane(follower_states, &pane, window, cx)
7462 });
7463
7464 let mut container = div()
7465 .flex()
7466 .overflow_hidden()
7467 .flex_none()
7468 .child(dock.clone())
7469 .children(leader_border);
7470
7471 // Apply sizing only when the dock is open. When closed the dock is still
7472 // included in the element tree so its focus handle remains mounted — without
7473 // this, toggle_panel_focus cannot focus the panel when the dock is closed.
7474 let dock = dock.read(cx);
7475 if let Some(panel) = dock.visible_panel() {
7476 let size_state = dock.stored_panel_size_state(panel.as_ref());
7477 let min_size = panel.min_size(window, cx);
7478 if position.axis() == Axis::Horizontal {
7479 let use_flexible = panel.has_flexible_size(window, cx);
7480 let flex_grow = if use_flexible {
7481 size_state
7482 .and_then(|state| state.flex)
7483 .or_else(|| self.default_dock_flex(position))
7484 } else {
7485 None
7486 };
7487 if let Some(grow) = flex_grow {
7488 let grow = (grow / self.center_full_height_column_count()).max(0.001);
7489 let style = container.style();
7490 style.flex_grow = Some(grow);
7491 style.flex_shrink = Some(1.0);
7492 style.flex_basis = Some(relative(0.).into());
7493 } else {
7494 let size = size_state
7495 .and_then(|state| state.size)
7496 .unwrap_or_else(|| panel.default_size(window, cx));
7497 container = container.w(size);
7498 }
7499 if let Some(min) = min_size {
7500 container = container.min_w(min);
7501 }
7502 } else {
7503 let size = size_state
7504 .and_then(|state| state.size)
7505 .unwrap_or_else(|| panel.default_size(window, cx));
7506 container = container.h(size);
7507 }
7508 }
7509
7510 Some(container)
7511 }
7512
7513 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7514 window
7515 .root::<MultiWorkspace>()
7516 .flatten()
7517 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7518 }
7519
7520 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7521 self.zoomed.as_ref()
7522 }
7523
7524 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7525 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7526 return;
7527 };
7528 let windows = cx.windows();
7529 let next_window =
7530 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7531 || {
7532 windows
7533 .iter()
7534 .cycle()
7535 .skip_while(|window| window.window_id() != current_window_id)
7536 .nth(1)
7537 },
7538 );
7539
7540 if let Some(window) = next_window {
7541 window
7542 .update(cx, |_, window, _| window.activate_window())
7543 .ok();
7544 }
7545 }
7546
7547 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7548 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7549 return;
7550 };
7551 let windows = cx.windows();
7552 let prev_window =
7553 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7554 || {
7555 windows
7556 .iter()
7557 .rev()
7558 .cycle()
7559 .skip_while(|window| window.window_id() != current_window_id)
7560 .nth(1)
7561 },
7562 );
7563
7564 if let Some(window) = prev_window {
7565 window
7566 .update(cx, |_, window, _| window.activate_window())
7567 .ok();
7568 }
7569 }
7570
7571 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7572 if cx.stop_active_drag(window) {
7573 } else if let Some((notification_id, _)) = self.notifications.pop() {
7574 dismiss_app_notification(¬ification_id, cx);
7575 } else {
7576 cx.propagate();
7577 }
7578 }
7579
7580 fn resize_dock(
7581 &mut self,
7582 dock_pos: DockPosition,
7583 new_size: Pixels,
7584 window: &mut Window,
7585 cx: &mut Context<Self>,
7586 ) {
7587 match dock_pos {
7588 DockPosition::Left => self.resize_left_dock(new_size, window, cx),
7589 DockPosition::Right => self.resize_right_dock(new_size, window, cx),
7590 DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
7591 }
7592 }
7593
7594 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7595 let workspace_width = self.bounds.size.width;
7596 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7597
7598 self.right_dock.read_with(cx, |right_dock, cx| {
7599 let right_dock_size = right_dock
7600 .stored_active_panel_size(window, cx)
7601 .unwrap_or(Pixels::ZERO);
7602 if right_dock_size + size > workspace_width {
7603 size = workspace_width - right_dock_size
7604 }
7605 });
7606
7607 let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
7608 self.left_dock.update(cx, |left_dock, cx| {
7609 if WorkspaceSettings::get_global(cx)
7610 .resize_all_panels_in_dock
7611 .contains(&DockPosition::Left)
7612 {
7613 left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7614 } else {
7615 left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7616 }
7617 });
7618 }
7619
7620 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7621 let workspace_width = self.bounds.size.width;
7622 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7623 self.left_dock.read_with(cx, |left_dock, cx| {
7624 let left_dock_size = left_dock
7625 .stored_active_panel_size(window, cx)
7626 .unwrap_or(Pixels::ZERO);
7627 if left_dock_size + size > workspace_width {
7628 size = workspace_width - left_dock_size
7629 }
7630 });
7631 let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
7632 self.right_dock.update(cx, |right_dock, cx| {
7633 if WorkspaceSettings::get_global(cx)
7634 .resize_all_panels_in_dock
7635 .contains(&DockPosition::Right)
7636 {
7637 right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7638 } else {
7639 right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7640 }
7641 });
7642 }
7643
7644 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7645 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7646 self.bottom_dock.update(cx, |bottom_dock, cx| {
7647 if WorkspaceSettings::get_global(cx)
7648 .resize_all_panels_in_dock
7649 .contains(&DockPosition::Bottom)
7650 {
7651 bottom_dock.resize_all_panels(Some(size), None, window, cx);
7652 } else {
7653 bottom_dock.resize_active_panel(Some(size), None, window, cx);
7654 }
7655 });
7656 }
7657
7658 fn toggle_edit_predictions_all_files(
7659 &mut self,
7660 _: &ToggleEditPrediction,
7661 _window: &mut Window,
7662 cx: &mut Context<Self>,
7663 ) {
7664 let fs = self.project().read(cx).fs().clone();
7665 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7666 update_settings_file(fs, cx, move |file, _| {
7667 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7668 });
7669 }
7670
7671 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7672 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7673 let next_mode = match current_mode {
7674 Some(theme_settings::ThemeAppearanceMode::Light) => {
7675 theme_settings::ThemeAppearanceMode::Dark
7676 }
7677 Some(theme_settings::ThemeAppearanceMode::Dark) => {
7678 theme_settings::ThemeAppearanceMode::Light
7679 }
7680 Some(theme_settings::ThemeAppearanceMode::System) | None => {
7681 match cx.theme().appearance() {
7682 theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
7683 theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
7684 }
7685 }
7686 };
7687
7688 let fs = self.project().read(cx).fs().clone();
7689 settings::update_settings_file(fs, cx, move |settings, _cx| {
7690 theme_settings::set_mode(settings, next_mode);
7691 });
7692 }
7693
7694 pub fn show_worktree_trust_security_modal(
7695 &mut self,
7696 toggle: bool,
7697 window: &mut Window,
7698 cx: &mut Context<Self>,
7699 ) {
7700 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7701 if toggle {
7702 security_modal.update(cx, |security_modal, cx| {
7703 security_modal.dismiss(cx);
7704 })
7705 } else {
7706 security_modal.update(cx, |security_modal, cx| {
7707 security_modal.refresh_restricted_paths(cx);
7708 });
7709 }
7710 } else {
7711 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7712 .map(|trusted_worktrees| {
7713 trusted_worktrees
7714 .read(cx)
7715 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7716 })
7717 .unwrap_or(false);
7718 if has_restricted_worktrees {
7719 let project = self.project().read(cx);
7720 let remote_host = project
7721 .remote_connection_options(cx)
7722 .map(RemoteHostLocation::from);
7723 let worktree_store = project.worktree_store().downgrade();
7724 self.toggle_modal(window, cx, |_, cx| {
7725 SecurityModal::new(worktree_store, remote_host, cx)
7726 });
7727 }
7728 }
7729 }
7730}
7731
7732pub trait AnyActiveCall {
7733 fn entity(&self) -> AnyEntity;
7734 fn is_in_room(&self, _: &App) -> bool;
7735 fn room_id(&self, _: &App) -> Option<u64>;
7736 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7737 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7738 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7739 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7740 fn is_sharing_project(&self, _: &App) -> bool;
7741 fn has_remote_participants(&self, _: &App) -> bool;
7742 fn local_participant_is_guest(&self, _: &App) -> bool;
7743 fn client(&self, _: &App) -> Arc<Client>;
7744 fn share_on_join(&self, _: &App) -> bool;
7745 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7746 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7747 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7748 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7749 fn join_project(
7750 &self,
7751 _: u64,
7752 _: Arc<LanguageRegistry>,
7753 _: Arc<dyn Fs>,
7754 _: &mut App,
7755 ) -> Task<Result<Entity<Project>>>;
7756 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7757 fn subscribe(
7758 &self,
7759 _: &mut Window,
7760 _: &mut Context<Workspace>,
7761 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7762 ) -> Subscription;
7763 fn create_shared_screen(
7764 &self,
7765 _: PeerId,
7766 _: &Entity<Pane>,
7767 _: &mut Window,
7768 _: &mut App,
7769 ) -> Option<Entity<SharedScreen>>;
7770}
7771
7772#[derive(Clone)]
7773pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7774impl Global for GlobalAnyActiveCall {}
7775
7776impl GlobalAnyActiveCall {
7777 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7778 cx.try_global()
7779 }
7780
7781 pub(crate) fn global(cx: &App) -> &Self {
7782 cx.global()
7783 }
7784}
7785
7786/// Workspace-local view of a remote participant's location.
7787#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7788pub enum ParticipantLocation {
7789 SharedProject { project_id: u64 },
7790 UnsharedProject,
7791 External,
7792}
7793
7794impl ParticipantLocation {
7795 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7796 match location
7797 .and_then(|l| l.variant)
7798 .context("participant location was not provided")?
7799 {
7800 proto::participant_location::Variant::SharedProject(project) => {
7801 Ok(Self::SharedProject {
7802 project_id: project.id,
7803 })
7804 }
7805 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7806 proto::participant_location::Variant::External(_) => Ok(Self::External),
7807 }
7808 }
7809}
7810/// Workspace-local view of a remote collaborator's state.
7811/// This is the subset of `call::RemoteParticipant` that workspace needs.
7812#[derive(Clone)]
7813pub struct RemoteCollaborator {
7814 pub user: Arc<User>,
7815 pub peer_id: PeerId,
7816 pub location: ParticipantLocation,
7817 pub participant_index: ParticipantIndex,
7818}
7819
7820pub enum ActiveCallEvent {
7821 ParticipantLocationChanged { participant_id: PeerId },
7822 RemoteVideoTracksChanged { participant_id: PeerId },
7823}
7824
7825fn leader_border_for_pane(
7826 follower_states: &HashMap<CollaboratorId, FollowerState>,
7827 pane: &Entity<Pane>,
7828 _: &Window,
7829 cx: &App,
7830) -> Option<Div> {
7831 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7832 if state.pane() == pane {
7833 Some((*leader_id, state))
7834 } else {
7835 None
7836 }
7837 })?;
7838
7839 let mut leader_color = match leader_id {
7840 CollaboratorId::PeerId(leader_peer_id) => {
7841 let leader = GlobalAnyActiveCall::try_global(cx)?
7842 .0
7843 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7844
7845 cx.theme()
7846 .players()
7847 .color_for_participant(leader.participant_index.0)
7848 .cursor
7849 }
7850 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7851 };
7852 leader_color.fade_out(0.3);
7853 Some(
7854 div()
7855 .absolute()
7856 .size_full()
7857 .left_0()
7858 .top_0()
7859 .border_2()
7860 .border_color(leader_color),
7861 )
7862}
7863
7864fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7865 ZED_WINDOW_POSITION
7866 .zip(*ZED_WINDOW_SIZE)
7867 .map(|(position, size)| Bounds {
7868 origin: position,
7869 size,
7870 })
7871}
7872
7873fn open_items(
7874 serialized_workspace: Option<SerializedWorkspace>,
7875 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7876 window: &mut Window,
7877 cx: &mut Context<Workspace>,
7878) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7879 let restored_items = serialized_workspace.map(|serialized_workspace| {
7880 Workspace::load_workspace(
7881 serialized_workspace,
7882 project_paths_to_open
7883 .iter()
7884 .map(|(_, project_path)| project_path)
7885 .cloned()
7886 .collect(),
7887 window,
7888 cx,
7889 )
7890 });
7891
7892 cx.spawn_in(window, async move |workspace, cx| {
7893 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7894
7895 if let Some(restored_items) = restored_items {
7896 let restored_items = restored_items.await?;
7897
7898 let restored_project_paths = restored_items
7899 .iter()
7900 .filter_map(|item| {
7901 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7902 .ok()
7903 .flatten()
7904 })
7905 .collect::<HashSet<_>>();
7906
7907 for restored_item in restored_items {
7908 opened_items.push(restored_item.map(Ok));
7909 }
7910
7911 project_paths_to_open
7912 .iter_mut()
7913 .for_each(|(_, project_path)| {
7914 if let Some(project_path_to_open) = project_path
7915 && restored_project_paths.contains(project_path_to_open)
7916 {
7917 *project_path = None;
7918 }
7919 });
7920 } else {
7921 for _ in 0..project_paths_to_open.len() {
7922 opened_items.push(None);
7923 }
7924 }
7925 assert!(opened_items.len() == project_paths_to_open.len());
7926
7927 let tasks =
7928 project_paths_to_open
7929 .into_iter()
7930 .enumerate()
7931 .map(|(ix, (abs_path, project_path))| {
7932 let workspace = workspace.clone();
7933 cx.spawn(async move |cx| {
7934 let file_project_path = project_path?;
7935 let abs_path_task = workspace.update(cx, |workspace, cx| {
7936 workspace.project().update(cx, |project, cx| {
7937 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7938 })
7939 });
7940
7941 // We only want to open file paths here. If one of the items
7942 // here is a directory, it was already opened further above
7943 // with a `find_or_create_worktree`.
7944 if let Ok(task) = abs_path_task
7945 && task.await.is_none_or(|p| p.is_file())
7946 {
7947 return Some((
7948 ix,
7949 workspace
7950 .update_in(cx, |workspace, window, cx| {
7951 workspace.open_path(
7952 file_project_path,
7953 None,
7954 true,
7955 window,
7956 cx,
7957 )
7958 })
7959 .log_err()?
7960 .await,
7961 ));
7962 }
7963 None
7964 })
7965 });
7966
7967 let tasks = tasks.collect::<Vec<_>>();
7968
7969 let tasks = futures::future::join_all(tasks);
7970 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7971 opened_items[ix] = Some(path_open_result);
7972 }
7973
7974 Ok(opened_items)
7975 })
7976}
7977
7978#[derive(Clone)]
7979enum ActivateInDirectionTarget {
7980 Pane(Entity<Pane>),
7981 Dock(Entity<Dock>),
7982 Sidebar(FocusHandle),
7983}
7984
7985fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7986 window
7987 .update(cx, |multi_workspace, _, cx| {
7988 let workspace = multi_workspace.workspace().clone();
7989 workspace.update(cx, |workspace, cx| {
7990 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7991 struct DatabaseFailedNotification;
7992
7993 workspace.show_notification(
7994 NotificationId::unique::<DatabaseFailedNotification>(),
7995 cx,
7996 |cx| {
7997 cx.new(|cx| {
7998 MessageNotification::new("Failed to load the database file.", cx)
7999 .primary_message("File an Issue")
8000 .primary_icon(IconName::Plus)
8001 .primary_on_click(|window, cx| {
8002 window.dispatch_action(Box::new(FileBugReport), cx)
8003 })
8004 })
8005 },
8006 );
8007 }
8008 });
8009 })
8010 .log_err();
8011}
8012
8013fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
8014 if val == 0 {
8015 ThemeSettings::get_global(cx).ui_font_size(cx)
8016 } else {
8017 px(val as f32)
8018 }
8019}
8020
8021fn adjust_active_dock_size_by_px(
8022 px: Pixels,
8023 workspace: &mut Workspace,
8024 window: &mut Window,
8025 cx: &mut Context<Workspace>,
8026) {
8027 let Some(active_dock) = workspace
8028 .all_docks()
8029 .into_iter()
8030 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
8031 else {
8032 return;
8033 };
8034 let dock = active_dock.read(cx);
8035 let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
8036 return;
8037 };
8038 workspace.resize_dock(dock.position(), panel_size + px, window, cx);
8039}
8040
8041fn adjust_open_docks_size_by_px(
8042 px: Pixels,
8043 workspace: &mut Workspace,
8044 window: &mut Window,
8045 cx: &mut Context<Workspace>,
8046) {
8047 let docks = workspace
8048 .all_docks()
8049 .into_iter()
8050 .filter_map(|dock_entity| {
8051 let dock = dock_entity.read(cx);
8052 if dock.is_open() {
8053 let dock_pos = dock.position();
8054 let panel_size = workspace.dock_size(&dock, window, cx)?;
8055 Some((dock_pos, panel_size + px))
8056 } else {
8057 None
8058 }
8059 })
8060 .collect::<Vec<_>>();
8061
8062 for (position, new_size) in docks {
8063 workspace.resize_dock(position, new_size, window, cx);
8064 }
8065}
8066
8067impl Focusable for Workspace {
8068 fn focus_handle(&self, cx: &App) -> FocusHandle {
8069 self.active_pane.focus_handle(cx)
8070 }
8071}
8072
8073#[derive(Clone)]
8074struct DraggedDock(DockPosition);
8075
8076impl Render for DraggedDock {
8077 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8078 gpui::Empty
8079 }
8080}
8081
8082impl Render for Workspace {
8083 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
8084 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
8085 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
8086 log::info!("Rendered first frame");
8087 }
8088
8089 let centered_layout = self.centered_layout
8090 && self.center.panes().len() == 1
8091 && self.active_item(cx).is_some();
8092 let render_padding = |size| {
8093 (size > 0.0).then(|| {
8094 div()
8095 .h_full()
8096 .w(relative(size))
8097 .bg(cx.theme().colors().editor_background)
8098 .border_color(cx.theme().colors().pane_group_border)
8099 })
8100 };
8101 let paddings = if centered_layout {
8102 let settings = WorkspaceSettings::get_global(cx).centered_layout;
8103 (
8104 render_padding(Self::adjust_padding(
8105 settings.left_padding.map(|padding| padding.0),
8106 )),
8107 render_padding(Self::adjust_padding(
8108 settings.right_padding.map(|padding| padding.0),
8109 )),
8110 )
8111 } else {
8112 (None, None)
8113 };
8114 let ui_font = theme_settings::setup_ui_font(window, cx);
8115
8116 let theme = cx.theme().clone();
8117 let colors = theme.colors();
8118 let notification_entities = self
8119 .notifications
8120 .iter()
8121 .map(|(_, notification)| notification.entity_id())
8122 .collect::<Vec<_>>();
8123 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
8124
8125 div()
8126 .relative()
8127 .size_full()
8128 .flex()
8129 .flex_col()
8130 .font(ui_font)
8131 .gap_0()
8132 .justify_start()
8133 .items_start()
8134 .text_color(colors.text)
8135 .overflow_hidden()
8136 .children(self.titlebar_item.clone())
8137 .on_modifiers_changed(move |_, _, cx| {
8138 for &id in ¬ification_entities {
8139 cx.notify(id);
8140 }
8141 })
8142 .child(
8143 div()
8144 .size_full()
8145 .relative()
8146 .flex_1()
8147 .flex()
8148 .flex_col()
8149 .child(
8150 div()
8151 .id("workspace")
8152 .bg(colors.background)
8153 .relative()
8154 .flex_1()
8155 .w_full()
8156 .flex()
8157 .flex_col()
8158 .overflow_hidden()
8159 .border_t_1()
8160 .border_b_1()
8161 .border_color(colors.border)
8162 .child({
8163 let this = cx.entity();
8164 canvas(
8165 move |bounds, window, cx| {
8166 this.update(cx, |this, cx| {
8167 let bounds_changed = this.bounds != bounds;
8168 this.bounds = bounds;
8169
8170 if bounds_changed {
8171 this.left_dock.update(cx, |dock, cx| {
8172 dock.clamp_panel_size(
8173 bounds.size.width,
8174 window,
8175 cx,
8176 )
8177 });
8178
8179 this.right_dock.update(cx, |dock, cx| {
8180 dock.clamp_panel_size(
8181 bounds.size.width,
8182 window,
8183 cx,
8184 )
8185 });
8186
8187 this.bottom_dock.update(cx, |dock, cx| {
8188 dock.clamp_panel_size(
8189 bounds.size.height,
8190 window,
8191 cx,
8192 )
8193 });
8194 }
8195 })
8196 },
8197 |_, _, _, _| {},
8198 )
8199 .absolute()
8200 .size_full()
8201 })
8202 .when(self.zoomed.is_none(), |this| {
8203 this.on_drag_move(cx.listener(
8204 move |workspace,
8205 e: &DragMoveEvent<DraggedDock>,
8206 window,
8207 cx| {
8208 if workspace.previous_dock_drag_coordinates
8209 != Some(e.event.position)
8210 {
8211 workspace.previous_dock_drag_coordinates =
8212 Some(e.event.position);
8213
8214 match e.drag(cx).0 {
8215 DockPosition::Left => {
8216 workspace.resize_left_dock(
8217 e.event.position.x
8218 - workspace.bounds.left(),
8219 window,
8220 cx,
8221 );
8222 }
8223 DockPosition::Right => {
8224 workspace.resize_right_dock(
8225 workspace.bounds.right()
8226 - e.event.position.x,
8227 window,
8228 cx,
8229 );
8230 }
8231 DockPosition::Bottom => {
8232 workspace.resize_bottom_dock(
8233 workspace.bounds.bottom()
8234 - e.event.position.y,
8235 window,
8236 cx,
8237 );
8238 }
8239 };
8240 workspace.serialize_workspace(window, cx);
8241 }
8242 },
8243 ))
8244
8245 })
8246 .child({
8247 match bottom_dock_layout {
8248 BottomDockLayout::Full => div()
8249 .flex()
8250 .flex_col()
8251 .h_full()
8252 .child(
8253 div()
8254 .flex()
8255 .flex_row()
8256 .flex_1()
8257 .overflow_hidden()
8258 .children(self.render_dock(
8259 DockPosition::Left,
8260 &self.left_dock,
8261 window,
8262 cx,
8263 ))
8264
8265 .child(
8266 div()
8267 .flex()
8268 .flex_col()
8269 .flex_1()
8270 .overflow_hidden()
8271 .child(
8272 h_flex()
8273 .flex_1()
8274 .when_some(
8275 paddings.0,
8276 |this, p| {
8277 this.child(
8278 p.border_r_1(),
8279 )
8280 },
8281 )
8282 .child(self.center.render(
8283 self.zoomed.as_ref(),
8284 &PaneRenderContext {
8285 follower_states:
8286 &self.follower_states,
8287 active_call: self.active_call(),
8288 active_pane: &self.active_pane,
8289 app_state: &self.app_state,
8290 project: &self.project,
8291 workspace: &self.weak_self,
8292 },
8293 window,
8294 cx,
8295 ))
8296 .when_some(
8297 paddings.1,
8298 |this, p| {
8299 this.child(
8300 p.border_l_1(),
8301 )
8302 },
8303 ),
8304 ),
8305 )
8306
8307 .children(self.render_dock(
8308 DockPosition::Right,
8309 &self.right_dock,
8310 window,
8311 cx,
8312 )),
8313 )
8314 .child(div().w_full().children(self.render_dock(
8315 DockPosition::Bottom,
8316 &self.bottom_dock,
8317 window,
8318 cx
8319 ))),
8320
8321 BottomDockLayout::LeftAligned => div()
8322 .flex()
8323 .flex_row()
8324 .h_full()
8325 .child(
8326 div()
8327 .flex()
8328 .flex_col()
8329 .flex_1()
8330 .h_full()
8331 .child(
8332 div()
8333 .flex()
8334 .flex_row()
8335 .flex_1()
8336 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
8337
8338 .child(
8339 div()
8340 .flex()
8341 .flex_col()
8342 .flex_1()
8343 .overflow_hidden()
8344 .child(
8345 h_flex()
8346 .flex_1()
8347 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8348 .child(self.center.render(
8349 self.zoomed.as_ref(),
8350 &PaneRenderContext {
8351 follower_states:
8352 &self.follower_states,
8353 active_call: self.active_call(),
8354 active_pane: &self.active_pane,
8355 app_state: &self.app_state,
8356 project: &self.project,
8357 workspace: &self.weak_self,
8358 },
8359 window,
8360 cx,
8361 ))
8362 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8363 )
8364 )
8365
8366 )
8367 .child(
8368 div()
8369 .w_full()
8370 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8371 ),
8372 )
8373 .children(self.render_dock(
8374 DockPosition::Right,
8375 &self.right_dock,
8376 window,
8377 cx,
8378 )),
8379 BottomDockLayout::RightAligned => div()
8380 .flex()
8381 .flex_row()
8382 .h_full()
8383 .children(self.render_dock(
8384 DockPosition::Left,
8385 &self.left_dock,
8386 window,
8387 cx,
8388 ))
8389
8390 .child(
8391 div()
8392 .flex()
8393 .flex_col()
8394 .flex_1()
8395 .h_full()
8396 .child(
8397 div()
8398 .flex()
8399 .flex_row()
8400 .flex_1()
8401 .child(
8402 div()
8403 .flex()
8404 .flex_col()
8405 .flex_1()
8406 .overflow_hidden()
8407 .child(
8408 h_flex()
8409 .flex_1()
8410 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8411 .child(self.center.render(
8412 self.zoomed.as_ref(),
8413 &PaneRenderContext {
8414 follower_states:
8415 &self.follower_states,
8416 active_call: self.active_call(),
8417 active_pane: &self.active_pane,
8418 app_state: &self.app_state,
8419 project: &self.project,
8420 workspace: &self.weak_self,
8421 },
8422 window,
8423 cx,
8424 ))
8425 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8426 )
8427 )
8428
8429 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
8430 )
8431 .child(
8432 div()
8433 .w_full()
8434 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8435 ),
8436 ),
8437 BottomDockLayout::Contained => div()
8438 .flex()
8439 .flex_row()
8440 .h_full()
8441 .children(self.render_dock(
8442 DockPosition::Left,
8443 &self.left_dock,
8444 window,
8445 cx,
8446 ))
8447
8448 .child(
8449 div()
8450 .flex()
8451 .flex_col()
8452 .flex_1()
8453 .overflow_hidden()
8454 .child(
8455 h_flex()
8456 .flex_1()
8457 .when_some(paddings.0, |this, p| {
8458 this.child(p.border_r_1())
8459 })
8460 .child(self.center.render(
8461 self.zoomed.as_ref(),
8462 &PaneRenderContext {
8463 follower_states:
8464 &self.follower_states,
8465 active_call: self.active_call(),
8466 active_pane: &self.active_pane,
8467 app_state: &self.app_state,
8468 project: &self.project,
8469 workspace: &self.weak_self,
8470 },
8471 window,
8472 cx,
8473 ))
8474 .when_some(paddings.1, |this, p| {
8475 this.child(p.border_l_1())
8476 }),
8477 )
8478 .children(self.render_dock(
8479 DockPosition::Bottom,
8480 &self.bottom_dock,
8481 window,
8482 cx,
8483 )),
8484 )
8485
8486 .children(self.render_dock(
8487 DockPosition::Right,
8488 &self.right_dock,
8489 window,
8490 cx,
8491 )),
8492 }
8493 })
8494 .children(self.zoomed.as_ref().and_then(|view| {
8495 let zoomed_view = view.upgrade()?;
8496 let div = div()
8497 .occlude()
8498 .absolute()
8499 .overflow_hidden()
8500 .border_color(colors.border)
8501 .bg(colors.background)
8502 .child(zoomed_view)
8503 .inset_0()
8504 .shadow_lg();
8505
8506 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8507 return Some(div);
8508 }
8509
8510 Some(match self.zoomed_position {
8511 Some(DockPosition::Left) => div.right_2().border_r_1(),
8512 Some(DockPosition::Right) => div.left_2().border_l_1(),
8513 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8514 None => {
8515 div.top_2().bottom_2().left_2().right_2().border_1()
8516 }
8517 })
8518 }))
8519 .children(self.render_notifications(window, cx)),
8520 )
8521 .when(self.status_bar_visible(cx), |parent| {
8522 parent.child(self.status_bar.clone())
8523 })
8524 .child(self.toast_layer.clone()),
8525 )
8526 }
8527}
8528
8529impl WorkspaceStore {
8530 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8531 Self {
8532 workspaces: Default::default(),
8533 _subscriptions: vec![
8534 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8535 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8536 ],
8537 client,
8538 }
8539 }
8540
8541 pub fn update_followers(
8542 &self,
8543 project_id: Option<u64>,
8544 update: proto::update_followers::Variant,
8545 cx: &App,
8546 ) -> Option<()> {
8547 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8548 let room_id = active_call.0.room_id(cx)?;
8549 self.client
8550 .send(proto::UpdateFollowers {
8551 room_id,
8552 project_id,
8553 variant: Some(update),
8554 })
8555 .log_err()
8556 }
8557
8558 pub async fn handle_follow(
8559 this: Entity<Self>,
8560 envelope: TypedEnvelope<proto::Follow>,
8561 mut cx: AsyncApp,
8562 ) -> Result<proto::FollowResponse> {
8563 this.update(&mut cx, |this, cx| {
8564 let follower = Follower {
8565 project_id: envelope.payload.project_id,
8566 peer_id: envelope.original_sender_id()?,
8567 };
8568
8569 let mut response = proto::FollowResponse::default();
8570
8571 this.workspaces.retain(|(window_handle, weak_workspace)| {
8572 let Some(workspace) = weak_workspace.upgrade() else {
8573 return false;
8574 };
8575 window_handle
8576 .update(cx, |_, window, cx| {
8577 workspace.update(cx, |workspace, cx| {
8578 let handler_response =
8579 workspace.handle_follow(follower.project_id, window, cx);
8580 if let Some(active_view) = handler_response.active_view
8581 && workspace.project.read(cx).remote_id() == follower.project_id
8582 {
8583 response.active_view = Some(active_view)
8584 }
8585 });
8586 })
8587 .is_ok()
8588 });
8589
8590 Ok(response)
8591 })
8592 }
8593
8594 async fn handle_update_followers(
8595 this: Entity<Self>,
8596 envelope: TypedEnvelope<proto::UpdateFollowers>,
8597 mut cx: AsyncApp,
8598 ) -> Result<()> {
8599 let leader_id = envelope.original_sender_id()?;
8600 let update = envelope.payload;
8601
8602 this.update(&mut cx, |this, cx| {
8603 this.workspaces.retain(|(window_handle, weak_workspace)| {
8604 let Some(workspace) = weak_workspace.upgrade() else {
8605 return false;
8606 };
8607 window_handle
8608 .update(cx, |_, window, cx| {
8609 workspace.update(cx, |workspace, cx| {
8610 let project_id = workspace.project.read(cx).remote_id();
8611 if update.project_id != project_id && update.project_id.is_some() {
8612 return;
8613 }
8614 workspace.handle_update_followers(
8615 leader_id,
8616 update.clone(),
8617 window,
8618 cx,
8619 );
8620 });
8621 })
8622 .is_ok()
8623 });
8624 Ok(())
8625 })
8626 }
8627
8628 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8629 self.workspaces.iter().map(|(_, weak)| weak)
8630 }
8631
8632 pub fn workspaces_with_windows(
8633 &self,
8634 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8635 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8636 }
8637}
8638
8639impl ViewId {
8640 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8641 Ok(Self {
8642 creator: message
8643 .creator
8644 .map(CollaboratorId::PeerId)
8645 .context("creator is missing")?,
8646 id: message.id,
8647 })
8648 }
8649
8650 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8651 if let CollaboratorId::PeerId(peer_id) = self.creator {
8652 Some(proto::ViewId {
8653 creator: Some(peer_id),
8654 id: self.id,
8655 })
8656 } else {
8657 None
8658 }
8659 }
8660}
8661
8662impl FollowerState {
8663 fn pane(&self) -> &Entity<Pane> {
8664 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8665 }
8666}
8667
8668pub trait WorkspaceHandle {
8669 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8670}
8671
8672impl WorkspaceHandle for Entity<Workspace> {
8673 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8674 self.read(cx)
8675 .worktrees(cx)
8676 .flat_map(|worktree| {
8677 let worktree_id = worktree.read(cx).id();
8678 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8679 worktree_id,
8680 path: f.path.clone(),
8681 })
8682 })
8683 .collect::<Vec<_>>()
8684 }
8685}
8686
8687pub async fn last_opened_workspace_location(
8688 db: &WorkspaceDb,
8689 fs: &dyn fs::Fs,
8690) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8691 db.last_workspace(fs)
8692 .await
8693 .log_err()
8694 .flatten()
8695 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8696}
8697
8698pub async fn last_session_workspace_locations(
8699 db: &WorkspaceDb,
8700 last_session_id: &str,
8701 last_session_window_stack: Option<Vec<WindowId>>,
8702 fs: &dyn fs::Fs,
8703) -> Option<Vec<SessionWorkspace>> {
8704 db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8705 .await
8706 .log_err()
8707}
8708
8709pub async fn restore_multiworkspace(
8710 multi_workspace: SerializedMultiWorkspace,
8711 app_state: Arc<AppState>,
8712 cx: &mut AsyncApp,
8713) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8714 let SerializedMultiWorkspace {
8715 active_workspace,
8716 state,
8717 } = multi_workspace;
8718
8719 let workspace_result = if active_workspace.paths.is_empty() {
8720 cx.update(|cx| {
8721 open_workspace_by_id(active_workspace.workspace_id, app_state.clone(), None, cx)
8722 })
8723 .await
8724 } else {
8725 cx.update(|cx| {
8726 Workspace::new_local(
8727 active_workspace.paths.paths().to_vec(),
8728 app_state.clone(),
8729 None,
8730 None,
8731 None,
8732 OpenMode::Activate,
8733 cx,
8734 )
8735 })
8736 .await
8737 .map(|result| result.window)
8738 };
8739
8740 let window_handle = match workspace_result {
8741 Ok(handle) => handle,
8742 Err(err) => {
8743 log::error!("Failed to restore active workspace: {err:#}");
8744
8745 let mut fallback_handle = None;
8746 for key in &state.project_groups {
8747 let key: ProjectGroupKey = key.clone().into();
8748 let paths = key.path_list().paths().to_vec();
8749 match cx
8750 .update(|cx| {
8751 Workspace::new_local(
8752 paths,
8753 app_state.clone(),
8754 None,
8755 None,
8756 None,
8757 OpenMode::Activate,
8758 cx,
8759 )
8760 })
8761 .await
8762 {
8763 Ok(OpenResult { window, .. }) => {
8764 fallback_handle = Some(window);
8765 break;
8766 }
8767 Err(fallback_err) => {
8768 log::error!("Fallback project group also failed: {fallback_err:#}");
8769 }
8770 }
8771 }
8772
8773 fallback_handle.ok_or(err)?
8774 }
8775 };
8776
8777 apply_restored_multiworkspace_state(window_handle, &state, app_state.fs.clone(), cx).await;
8778
8779 window_handle
8780 .update(cx, |_, window, _cx| {
8781 window.activate_window();
8782 })
8783 .ok();
8784
8785 Ok(window_handle)
8786}
8787
8788pub async fn apply_restored_multiworkspace_state(
8789 window_handle: WindowHandle<MultiWorkspace>,
8790 state: &MultiWorkspaceState,
8791 fs: Arc<dyn fs::Fs>,
8792 cx: &mut AsyncApp,
8793) {
8794 let MultiWorkspaceState {
8795 sidebar_open,
8796 project_groups,
8797 sidebar_state,
8798 ..
8799 } = state;
8800
8801 if !project_groups.is_empty() {
8802 // Resolve linked worktree paths to their main repo paths so
8803 // stale keys from previous sessions get normalized and deduped.
8804 let mut resolved_groups: Vec<SerializedProjectGroupState> = Vec::new();
8805 for serialized in project_groups.iter().cloned() {
8806 let SerializedProjectGroupState { key, expanded } = serialized.into_restored_state();
8807 if key.path_list().paths().is_empty() {
8808 continue;
8809 }
8810 let mut resolved_paths = Vec::new();
8811 for path in key.path_list().paths() {
8812 if key.host().is_none()
8813 && let Some(common_dir) =
8814 project::discover_root_repo_common_dir(path, fs.as_ref()).await
8815 {
8816 let main_path = common_dir.parent().unwrap_or(&common_dir);
8817 resolved_paths.push(main_path.to_path_buf());
8818 } else {
8819 resolved_paths.push(path.to_path_buf());
8820 }
8821 }
8822 let resolved = ProjectGroupKey::new(key.host(), PathList::new(&resolved_paths));
8823 if !resolved_groups.iter().any(|g| g.key == resolved) {
8824 resolved_groups.push(SerializedProjectGroupState {
8825 key: resolved,
8826 expanded,
8827 });
8828 }
8829 }
8830
8831 window_handle
8832 .update(cx, |multi_workspace, _window, cx| {
8833 multi_workspace.restore_project_groups(resolved_groups, cx);
8834 })
8835 .ok();
8836 }
8837
8838 if *sidebar_open {
8839 window_handle
8840 .update(cx, |multi_workspace, _, cx| {
8841 multi_workspace.restore_open_sidebar(cx);
8842 })
8843 .ok();
8844 }
8845
8846 if let Some(sidebar_state) = sidebar_state {
8847 window_handle
8848 .update(cx, |multi_workspace, window, cx| {
8849 if let Some(sidebar) = multi_workspace.sidebar() {
8850 sidebar.restore_serialized_state(sidebar_state, window, cx);
8851 }
8852 multi_workspace.serialize(cx);
8853 })
8854 .ok();
8855 }
8856}
8857
8858actions!(
8859 collab,
8860 [
8861 /// Opens the channel notes for the current call.
8862 ///
8863 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8864 /// channel in the collab panel.
8865 ///
8866 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8867 /// can be copied via "Copy link to section" in the context menu of the channel notes
8868 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8869 OpenChannelNotes,
8870 /// Mutes your microphone.
8871 Mute,
8872 /// Deafens yourself (mute both microphone and speakers).
8873 Deafen,
8874 /// Leaves the current call.
8875 LeaveCall,
8876 /// Shares the current project with collaborators.
8877 ShareProject,
8878 /// Shares your screen with collaborators.
8879 ScreenShare,
8880 /// Copies the current room name and session id for debugging purposes.
8881 CopyRoomId,
8882 ]
8883);
8884
8885/// Opens the channel notes for a specific channel by its ID.
8886#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8887#[action(namespace = collab)]
8888#[serde(deny_unknown_fields)]
8889pub struct OpenChannelNotesById {
8890 pub channel_id: u64,
8891}
8892
8893actions!(
8894 zed,
8895 [
8896 /// Opens the Zed log file.
8897 OpenLog,
8898 /// Reveals the Zed log file in the system file manager.
8899 RevealLogInFileManager
8900 ]
8901);
8902
8903async fn join_channel_internal(
8904 channel_id: ChannelId,
8905 app_state: &Arc<AppState>,
8906 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8907 requesting_workspace: Option<WeakEntity<Workspace>>,
8908 active_call: &dyn AnyActiveCall,
8909 cx: &mut AsyncApp,
8910) -> Result<bool> {
8911 let (should_prompt, already_in_channel) = cx.update(|cx| {
8912 if !active_call.is_in_room(cx) {
8913 return (false, false);
8914 }
8915
8916 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8917 let should_prompt = active_call.is_sharing_project(cx)
8918 && active_call.has_remote_participants(cx)
8919 && !already_in_channel;
8920 (should_prompt, already_in_channel)
8921 });
8922
8923 if already_in_channel {
8924 let task = cx.update(|cx| {
8925 if let Some((project, host)) = active_call.most_active_project(cx) {
8926 Some(join_in_room_project(project, host, app_state.clone(), cx))
8927 } else {
8928 None
8929 }
8930 });
8931 if let Some(task) = task {
8932 task.await?;
8933 }
8934 return anyhow::Ok(true);
8935 }
8936
8937 if should_prompt {
8938 if let Some(multi_workspace) = requesting_window {
8939 let answer = multi_workspace
8940 .update(cx, |_, window, cx| {
8941 window.prompt(
8942 PromptLevel::Warning,
8943 "Do you want to switch channels?",
8944 Some("Leaving this call will unshare your current project."),
8945 &["Yes, Join Channel", "Cancel"],
8946 cx,
8947 )
8948 })?
8949 .await;
8950
8951 if answer == Ok(1) {
8952 return Ok(false);
8953 }
8954 } else {
8955 return Ok(false);
8956 }
8957 }
8958
8959 let client = cx.update(|cx| active_call.client(cx));
8960
8961 let mut client_status = client.status();
8962
8963 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8964 'outer: loop {
8965 let Some(status) = client_status.recv().await else {
8966 anyhow::bail!("error connecting");
8967 };
8968
8969 match status {
8970 Status::Connecting
8971 | Status::Authenticating
8972 | Status::Authenticated
8973 | Status::Reconnecting
8974 | Status::Reauthenticating
8975 | Status::Reauthenticated => continue,
8976 Status::Connected { .. } => break 'outer,
8977 Status::SignedOut | Status::AuthenticationError => {
8978 return Err(ErrorCode::SignedOut.into());
8979 }
8980 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8981 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8982 return Err(ErrorCode::Disconnected.into());
8983 }
8984 }
8985 }
8986
8987 let joined = cx
8988 .update(|cx| active_call.join_channel(channel_id, cx))
8989 .await?;
8990
8991 if !joined {
8992 return anyhow::Ok(true);
8993 }
8994
8995 cx.update(|cx| active_call.room_update_completed(cx)).await;
8996
8997 let task = cx.update(|cx| {
8998 if let Some((project, host)) = active_call.most_active_project(cx) {
8999 return Some(join_in_room_project(project, host, app_state.clone(), cx));
9000 }
9001
9002 // If you are the first to join a channel, see if you should share your project.
9003 if !active_call.has_remote_participants(cx)
9004 && !active_call.local_participant_is_guest(cx)
9005 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
9006 {
9007 let project = workspace.update(cx, |workspace, cx| {
9008 let project = workspace.project.read(cx);
9009
9010 if !active_call.share_on_join(cx) {
9011 return None;
9012 }
9013
9014 if (project.is_local() || project.is_via_remote_server())
9015 && project.visible_worktrees(cx).any(|tree| {
9016 tree.read(cx)
9017 .root_entry()
9018 .is_some_and(|entry| entry.is_dir())
9019 })
9020 {
9021 Some(workspace.project.clone())
9022 } else {
9023 None
9024 }
9025 });
9026 if let Some(project) = project {
9027 let share_task = active_call.share_project(project, cx);
9028 return Some(cx.spawn(async move |_cx| -> Result<()> {
9029 share_task.await?;
9030 Ok(())
9031 }));
9032 }
9033 }
9034
9035 None
9036 });
9037 if let Some(task) = task {
9038 task.await?;
9039 return anyhow::Ok(true);
9040 }
9041 anyhow::Ok(false)
9042}
9043
9044pub fn join_channel(
9045 channel_id: ChannelId,
9046 app_state: Arc<AppState>,
9047 requesting_window: Option<WindowHandle<MultiWorkspace>>,
9048 requesting_workspace: Option<WeakEntity<Workspace>>,
9049 cx: &mut App,
9050) -> Task<Result<()>> {
9051 let active_call = GlobalAnyActiveCall::global(cx).clone();
9052 cx.spawn(async move |cx| {
9053 let result = join_channel_internal(
9054 channel_id,
9055 &app_state,
9056 requesting_window,
9057 requesting_workspace,
9058 &*active_call.0,
9059 cx,
9060 )
9061 .await;
9062
9063 // join channel succeeded, and opened a window
9064 if matches!(result, Ok(true)) {
9065 return anyhow::Ok(());
9066 }
9067
9068 // find an existing workspace to focus and show call controls
9069 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
9070 if active_window.is_none() {
9071 // no open workspaces, make one to show the error in (blergh)
9072 let OpenResult {
9073 window: window_handle,
9074 ..
9075 } = cx
9076 .update(|cx| {
9077 Workspace::new_local(
9078 vec![],
9079 app_state.clone(),
9080 requesting_window,
9081 None,
9082 None,
9083 OpenMode::Activate,
9084 cx,
9085 )
9086 })
9087 .await?;
9088
9089 window_handle
9090 .update(cx, |_, window, _cx| {
9091 window.activate_window();
9092 })
9093 .ok();
9094
9095 if result.is_ok() {
9096 cx.update(|cx| {
9097 cx.dispatch_action(&OpenChannelNotes);
9098 });
9099 }
9100
9101 active_window = Some(window_handle);
9102 }
9103
9104 if let Err(err) = result {
9105 log::error!("failed to join channel: {}", err);
9106 if let Some(active_window) = active_window {
9107 active_window
9108 .update(cx, |_, window, cx| {
9109 let detail: SharedString = match err.error_code() {
9110 ErrorCode::SignedOut => "Please sign in to continue.".into(),
9111 ErrorCode::UpgradeRequired => concat!(
9112 "Your are running an unsupported version of Zed. ",
9113 "Please update to continue."
9114 )
9115 .into(),
9116 ErrorCode::NoSuchChannel => concat!(
9117 "No matching channel was found. ",
9118 "Please check the link and try again."
9119 )
9120 .into(),
9121 ErrorCode::Forbidden => concat!(
9122 "This channel is private, and you do not have access. ",
9123 "Please ask someone to add you and try again."
9124 )
9125 .into(),
9126 ErrorCode::Disconnected => {
9127 "Please check your internet connection and try again.".into()
9128 }
9129 _ => format!("{}\n\nPlease try again.", err).into(),
9130 };
9131 window.prompt(
9132 PromptLevel::Critical,
9133 "Failed to join channel",
9134 Some(&detail),
9135 &["Ok"],
9136 cx,
9137 )
9138 })?
9139 .await
9140 .ok();
9141 }
9142 }
9143
9144 // return ok, we showed the error to the user.
9145 anyhow::Ok(())
9146 })
9147}
9148
9149pub async fn get_any_active_multi_workspace(
9150 app_state: Arc<AppState>,
9151 mut cx: AsyncApp,
9152) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
9153 // find an existing workspace to focus and show call controls
9154 let active_window = activate_any_workspace_window(&mut cx);
9155 if active_window.is_none() {
9156 cx.update(|cx| {
9157 Workspace::new_local(
9158 vec![],
9159 app_state.clone(),
9160 None,
9161 None,
9162 None,
9163 OpenMode::Activate,
9164 cx,
9165 )
9166 })
9167 .await?;
9168 }
9169 activate_any_workspace_window(&mut cx).context("could not open zed")
9170}
9171
9172fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
9173 cx.update(|cx| {
9174 if let Some(workspace_window) = cx
9175 .active_window()
9176 .and_then(|window| window.downcast::<MultiWorkspace>())
9177 {
9178 return Some(workspace_window);
9179 }
9180
9181 for window in cx.windows() {
9182 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
9183 workspace_window
9184 .update(cx, |_, window, _| window.activate_window())
9185 .ok();
9186 return Some(workspace_window);
9187 }
9188 }
9189 None
9190 })
9191}
9192
9193pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
9194 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
9195}
9196
9197pub fn workspace_windows_for_location(
9198 serialized_location: &SerializedWorkspaceLocation,
9199 cx: &App,
9200) -> Vec<WindowHandle<MultiWorkspace>> {
9201 cx.windows()
9202 .into_iter()
9203 .filter_map(|window| window.downcast::<MultiWorkspace>())
9204 .filter(|multi_workspace| {
9205 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
9206 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
9207 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
9208 }
9209 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
9210 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
9211 a.distro_name == b.distro_name
9212 }
9213 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
9214 a.container_id == b.container_id
9215 }
9216 #[cfg(any(test, feature = "test-support"))]
9217 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
9218 a.id == b.id
9219 }
9220 _ => false,
9221 };
9222
9223 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
9224 multi_workspace.workspaces().any(|workspace| {
9225 match workspace.read(cx).workspace_location(cx) {
9226 WorkspaceLocation::Location(location, _) => {
9227 match (&location, serialized_location) {
9228 (
9229 SerializedWorkspaceLocation::Local,
9230 SerializedWorkspaceLocation::Local,
9231 ) => true,
9232 (
9233 SerializedWorkspaceLocation::Remote(a),
9234 SerializedWorkspaceLocation::Remote(b),
9235 ) => same_host(a, b),
9236 _ => false,
9237 }
9238 }
9239 _ => false,
9240 }
9241 })
9242 })
9243 })
9244 .collect()
9245}
9246
9247pub async fn find_existing_workspace(
9248 abs_paths: &[PathBuf],
9249 open_options: &OpenOptions,
9250 location: &SerializedWorkspaceLocation,
9251 cx: &mut AsyncApp,
9252) -> (
9253 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
9254 OpenVisible,
9255) {
9256 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
9257 let mut open_visible = OpenVisible::All;
9258 let mut best_match = None;
9259
9260 if open_options.workspace_matching != WorkspaceMatching::None {
9261 cx.update(|cx| {
9262 for window in workspace_windows_for_location(location, cx) {
9263 if let Ok(multi_workspace) = window.read(cx) {
9264 for workspace in multi_workspace.workspaces() {
9265 let project = workspace.read(cx).project.read(cx);
9266 let m = project.visibility_for_paths(
9267 abs_paths,
9268 open_options.workspace_matching != WorkspaceMatching::MatchSubdirectory,
9269 cx,
9270 );
9271 if m > best_match {
9272 existing = Some((window, workspace.clone()));
9273 best_match = m;
9274 } else if best_match.is_none()
9275 && open_options.workspace_matching
9276 == WorkspaceMatching::MatchSubdirectory
9277 {
9278 existing = Some((window, workspace.clone()))
9279 }
9280 }
9281 }
9282 }
9283 });
9284
9285 let all_paths_are_files = existing
9286 .as_ref()
9287 .and_then(|(_, target_workspace)| {
9288 cx.update(|cx| {
9289 let workspace = target_workspace.read(cx);
9290 let project = workspace.project.read(cx);
9291 let path_style = workspace.path_style(cx);
9292 Some(!abs_paths.iter().any(|path| {
9293 let path = util::paths::SanitizedPath::new(path);
9294 project.worktrees(cx).any(|worktree| {
9295 let worktree = worktree.read(cx);
9296 let abs_path = worktree.abs_path();
9297 path_style
9298 .strip_prefix(path.as_ref(), abs_path.as_ref())
9299 .and_then(|rel| worktree.entry_for_path(&rel))
9300 .is_some_and(|e| e.is_dir())
9301 })
9302 }))
9303 })
9304 })
9305 .unwrap_or(false);
9306
9307 if open_options.wait && existing.is_some() && all_paths_are_files {
9308 cx.update(|cx| {
9309 let windows = workspace_windows_for_location(location, cx);
9310 let window = cx
9311 .active_window()
9312 .and_then(|window| window.downcast::<MultiWorkspace>())
9313 .filter(|window| windows.contains(window))
9314 .or_else(|| windows.into_iter().next());
9315 if let Some(window) = window {
9316 if let Ok(multi_workspace) = window.read(cx) {
9317 let active_workspace = multi_workspace.workspace().clone();
9318 existing = Some((window, active_workspace));
9319 open_visible = OpenVisible::None;
9320 }
9321 }
9322 });
9323 }
9324 }
9325 (existing, open_visible)
9326}
9327
9328/// Controls whether to reuse an existing workspace whose worktrees contain the
9329/// given paths, and how broadly to match.
9330#[derive(Clone, Debug, Default, PartialEq, Eq)]
9331pub enum WorkspaceMatching {
9332 /// Always open a new workspace. No matching against existing worktrees.
9333 None,
9334 /// Match paths against existing worktree roots and files within them.
9335 #[default]
9336 MatchExact,
9337 /// Match paths against existing worktrees including subdirectories, and
9338 /// fall back to any existing window if no worktree matched.
9339 ///
9340 /// For example, `zed -a foo/bar` will activate the `bar` workspace if it
9341 /// exists, otherwise it will open a new window with `foo/bar` as the root.
9342 MatchSubdirectory,
9343}
9344
9345#[derive(Clone)]
9346pub struct OpenOptions {
9347 pub visible: Option<OpenVisible>,
9348 pub focus: Option<bool>,
9349 pub workspace_matching: WorkspaceMatching,
9350 /// Whether to add unmatched directories to the existing window's sidebar
9351 /// rather than opening a new window. Defaults to true, matching the default
9352 /// `cli_default_open_behavior` setting.
9353 pub add_dirs_to_sidebar: bool,
9354 pub wait: bool,
9355 pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
9356 pub open_mode: OpenMode,
9357 pub env: Option<HashMap<String, String>>,
9358 pub open_in_dev_container: bool,
9359}
9360
9361impl Default for OpenOptions {
9362 fn default() -> Self {
9363 Self {
9364 visible: None,
9365 focus: None,
9366 workspace_matching: WorkspaceMatching::default(),
9367 add_dirs_to_sidebar: true,
9368 wait: false,
9369 requesting_window: None,
9370 open_mode: OpenMode::default(),
9371 env: None,
9372 open_in_dev_container: false,
9373 }
9374 }
9375}
9376
9377impl OpenOptions {
9378 fn should_reuse_existing_window(&self) -> bool {
9379 self.workspace_matching != WorkspaceMatching::None && self.open_mode != OpenMode::NewWindow
9380 }
9381}
9382
9383/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
9384/// or [`Workspace::open_workspace_for_paths`].
9385pub struct OpenResult {
9386 pub window: WindowHandle<MultiWorkspace>,
9387 pub workspace: Entity<Workspace>,
9388 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
9389}
9390
9391/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
9392pub fn open_workspace_by_id(
9393 workspace_id: WorkspaceId,
9394 app_state: Arc<AppState>,
9395 requesting_window: Option<WindowHandle<MultiWorkspace>>,
9396 cx: &mut App,
9397) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
9398 let project_handle = Project::local(
9399 app_state.client.clone(),
9400 app_state.node_runtime.clone(),
9401 app_state.user_store.clone(),
9402 app_state.languages.clone(),
9403 app_state.fs.clone(),
9404 None,
9405 project::LocalProjectFlags {
9406 init_worktree_trust: true,
9407 ..project::LocalProjectFlags::default()
9408 },
9409 cx,
9410 );
9411
9412 let db = WorkspaceDb::global(cx);
9413 let kvp = db::kvp::KeyValueStore::global(cx);
9414 cx.spawn(async move |cx| {
9415 let serialized_workspace = db
9416 .workspace_for_id(workspace_id)
9417 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
9418
9419 let centered_layout = serialized_workspace.centered_layout;
9420
9421 let (window, workspace) = if let Some(window) = requesting_window {
9422 let workspace = window.update(cx, |multi_workspace, window, cx| {
9423 let workspace = cx.new(|cx| {
9424 let mut workspace = Workspace::new(
9425 Some(workspace_id),
9426 project_handle.clone(),
9427 app_state.clone(),
9428 window,
9429 cx,
9430 );
9431 workspace.centered_layout = centered_layout;
9432 workspace
9433 });
9434 multi_workspace.add(workspace.clone(), &*window, cx);
9435 workspace
9436 })?;
9437 (window, workspace)
9438 } else {
9439 let window_bounds_override = window_bounds_env_override();
9440
9441 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
9442 (Some(WindowBounds::Windowed(bounds)), None)
9443 } else if let Some(display) = serialized_workspace.display
9444 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
9445 {
9446 (Some(bounds.0), Some(display))
9447 } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
9448 (Some(bounds), Some(display))
9449 } else {
9450 (None, None)
9451 };
9452
9453 let options = cx.update(|cx| {
9454 let mut options = (app_state.build_window_options)(display, cx);
9455 options.window_bounds = window_bounds;
9456 options
9457 });
9458
9459 let window = cx.open_window(options, {
9460 let app_state = app_state.clone();
9461 let project_handle = project_handle.clone();
9462 move |window, cx| {
9463 let workspace = cx.new(|cx| {
9464 let mut workspace = Workspace::new(
9465 Some(workspace_id),
9466 project_handle,
9467 app_state,
9468 window,
9469 cx,
9470 );
9471 workspace.centered_layout = centered_layout;
9472 workspace
9473 });
9474 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9475 }
9476 })?;
9477
9478 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
9479 multi_workspace.workspace().clone()
9480 })?;
9481
9482 (window, workspace)
9483 };
9484
9485 notify_if_database_failed(window, cx);
9486
9487 // Restore items from the serialized workspace
9488 window
9489 .update(cx, |_, window, cx| {
9490 workspace.update(cx, |_workspace, cx| {
9491 open_items(Some(serialized_workspace), vec![], window, cx)
9492 })
9493 })?
9494 .await?;
9495
9496 window.update(cx, |_, window, cx| {
9497 workspace.update(cx, |workspace, cx| {
9498 workspace.serialize_workspace(window, cx);
9499 });
9500 })?;
9501
9502 Ok(window)
9503 })
9504}
9505
9506#[allow(clippy::type_complexity)]
9507pub fn open_paths(
9508 abs_paths: &[PathBuf],
9509 app_state: Arc<AppState>,
9510 mut open_options: OpenOptions,
9511 cx: &mut App,
9512) -> Task<anyhow::Result<OpenResult>> {
9513 let abs_paths = abs_paths.to_vec();
9514 #[cfg(target_os = "windows")]
9515 let wsl_path = abs_paths
9516 .iter()
9517 .find_map(|p| util::paths::WslPath::from_path(p));
9518
9519 cx.spawn(async move |cx| {
9520 let (mut existing, mut open_visible) = find_existing_workspace(
9521 &abs_paths,
9522 &open_options,
9523 &SerializedWorkspaceLocation::Local,
9524 cx,
9525 )
9526 .await;
9527
9528 // Fallback: if no workspace contains the paths and all paths are files,
9529 // prefer an existing local workspace window (active window first).
9530 if open_options.should_reuse_existing_window() && existing.is_none() {
9531 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9532 let all_metadatas = futures::future::join_all(all_paths)
9533 .await
9534 .into_iter()
9535 .filter_map(|result| result.ok().flatten());
9536
9537 if all_metadatas.into_iter().all(|file| !file.is_dir) {
9538 cx.update(|cx| {
9539 let windows = workspace_windows_for_location(
9540 &SerializedWorkspaceLocation::Local,
9541 cx,
9542 );
9543 let window = cx
9544 .active_window()
9545 .and_then(|window| window.downcast::<MultiWorkspace>())
9546 .filter(|window| windows.contains(window))
9547 .or_else(|| windows.into_iter().next());
9548 if let Some(window) = window {
9549 if let Ok(multi_workspace) = window.read(cx) {
9550 let active_workspace = multi_workspace.workspace().clone();
9551 existing = Some((window, active_workspace));
9552 open_visible = OpenVisible::None;
9553 }
9554 }
9555 });
9556 }
9557 }
9558
9559 // Fallback for directories: when no flag is specified and no existing
9560 // workspace matched, check the user's setting to decide whether to add
9561 // the directory as a new workspace in the active window's MultiWorkspace
9562 // or open a new window.
9563 // Skip when requesting_window is already set: the caller (e.g.
9564 // open_workspace_for_paths reusing an empty window) already chose the
9565 // target window, so we must not open the sidebar as a side-effect.
9566 if open_options.should_reuse_existing_window()
9567 && existing.is_none()
9568 && open_options.requesting_window.is_none()
9569 {
9570 let use_existing_window = open_options.add_dirs_to_sidebar;
9571
9572 if use_existing_window {
9573 let target_window = cx.update(|cx| {
9574 let windows = workspace_windows_for_location(
9575 &SerializedWorkspaceLocation::Local,
9576 cx,
9577 );
9578 let window = cx
9579 .active_window()
9580 .and_then(|window| window.downcast::<MultiWorkspace>())
9581 .filter(|window| windows.contains(window))
9582 .or_else(|| windows.into_iter().next());
9583 window.filter(|window| {
9584 window
9585 .read(cx)
9586 .is_ok_and(|mw| mw.multi_workspace_enabled(cx))
9587 })
9588 });
9589
9590 if let Some(window) = target_window {
9591 open_options.requesting_window = Some(window);
9592 window
9593 .update(cx, |multi_workspace, _, cx| {
9594 multi_workspace.open_sidebar(cx);
9595 })
9596 .log_err();
9597 }
9598 }
9599 }
9600
9601 let open_in_dev_container = open_options.open_in_dev_container;
9602
9603 let result = if let Some((existing, target_workspace)) = existing {
9604 let open_task = existing
9605 .update(cx, |multi_workspace, window, cx| {
9606 window.activate_window();
9607 multi_workspace.activate(target_workspace.clone(), window, cx);
9608 target_workspace.update(cx, |workspace, cx| {
9609 if open_in_dev_container {
9610 workspace.set_open_in_dev_container(true);
9611 }
9612 workspace.open_paths(
9613 abs_paths,
9614 OpenOptions {
9615 visible: Some(open_visible),
9616 ..Default::default()
9617 },
9618 None,
9619 window,
9620 cx,
9621 )
9622 })
9623 })?
9624 .await;
9625
9626 _ = existing.update(cx, |multi_workspace, _, cx| {
9627 let workspace = multi_workspace.workspace().clone();
9628 workspace.update(cx, |workspace, cx| {
9629 for item in open_task.iter().flatten() {
9630 if let Err(e) = item {
9631 workspace.show_error(&e, cx);
9632 }
9633 }
9634 });
9635 });
9636
9637 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9638 } else {
9639 let init = if open_in_dev_container {
9640 Some(Box::new(|workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context<Workspace>| {
9641 workspace.set_open_in_dev_container(true);
9642 }) as Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>)
9643 } else {
9644 None
9645 };
9646 let result = cx
9647 .update(move |cx| {
9648 Workspace::new_local(
9649 abs_paths,
9650 app_state.clone(),
9651 open_options.requesting_window,
9652 open_options.env,
9653 init,
9654 open_options.open_mode,
9655 cx,
9656 )
9657 })
9658 .await;
9659
9660 if let Ok(ref result) = result {
9661 result.window
9662 .update(cx, |_, window, _cx| {
9663 window.activate_window();
9664 })
9665 .log_err();
9666 }
9667
9668 result
9669 };
9670
9671 #[cfg(target_os = "windows")]
9672 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9673 && let Ok(ref result) = result
9674 {
9675 result.window
9676 .update(cx, move |multi_workspace, _window, cx| {
9677 struct OpenInWsl;
9678 let workspace = multi_workspace.workspace().clone();
9679 workspace.update(cx, |workspace, cx| {
9680 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9681 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9682 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9683 cx.new(move |cx| {
9684 MessageNotification::new(msg, cx)
9685 .primary_message("Open in WSL")
9686 .primary_icon(IconName::FolderOpen)
9687 .primary_on_click(move |window, cx| {
9688 window.dispatch_action(Box::new(remote::OpenWslPath {
9689 distro: remote::WslConnectionOptions {
9690 distro_name: distro.clone(),
9691 user: None,
9692 },
9693 paths: vec![path.clone().into()],
9694 }), cx)
9695 })
9696 })
9697 });
9698 });
9699 })
9700 .unwrap();
9701 };
9702 result
9703 })
9704}
9705
9706pub fn open_new(
9707 open_options: OpenOptions,
9708 app_state: Arc<AppState>,
9709 cx: &mut App,
9710 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9711) -> Task<anyhow::Result<()>> {
9712 let addition = open_options.open_mode;
9713 let task = Workspace::new_local(
9714 Vec::new(),
9715 app_state,
9716 open_options.requesting_window,
9717 open_options.env,
9718 Some(Box::new(init)),
9719 addition,
9720 cx,
9721 );
9722 cx.spawn(async move |cx| {
9723 let OpenResult { window, .. } = task.await?;
9724 window
9725 .update(cx, |_, window, _cx| {
9726 window.activate_window();
9727 })
9728 .ok();
9729 Ok(())
9730 })
9731}
9732
9733pub fn create_and_open_local_file(
9734 path: &'static Path,
9735 window: &mut Window,
9736 cx: &mut Context<Workspace>,
9737 default_content: impl 'static + Send + FnOnce() -> Rope,
9738) -> Task<Result<Box<dyn ItemHandle>>> {
9739 cx.spawn_in(window, async move |workspace, cx| {
9740 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9741 if !fs.is_file(path).await {
9742 fs.create_file(path, Default::default()).await?;
9743 fs.save(path, &default_content(), Default::default())
9744 .await?;
9745 }
9746
9747 workspace
9748 .update_in(cx, |workspace, window, cx| {
9749 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9750 let path = workspace
9751 .project
9752 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9753 cx.spawn_in(window, async move |workspace, cx| {
9754 let path = path.await?;
9755
9756 let path = fs.canonicalize(&path).await.unwrap_or(path);
9757
9758 let mut items = workspace
9759 .update_in(cx, |workspace, window, cx| {
9760 workspace.open_paths(
9761 vec![path.to_path_buf()],
9762 OpenOptions {
9763 visible: Some(OpenVisible::None),
9764 ..Default::default()
9765 },
9766 None,
9767 window,
9768 cx,
9769 )
9770 })?
9771 .await;
9772 let item = items.pop().flatten();
9773 item.with_context(|| format!("path {path:?} is not a file"))?
9774 })
9775 })
9776 })?
9777 .await?
9778 .await
9779 })
9780}
9781
9782pub fn open_remote_project_with_new_connection(
9783 window: WindowHandle<MultiWorkspace>,
9784 remote_connection: Arc<dyn RemoteConnection>,
9785 cancel_rx: oneshot::Receiver<()>,
9786 delegate: Arc<dyn RemoteClientDelegate>,
9787 app_state: Arc<AppState>,
9788 paths: Vec<PathBuf>,
9789 cx: &mut App,
9790) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9791 cx.spawn(async move |cx| {
9792 let (workspace_id, serialized_workspace) =
9793 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9794 .await?;
9795
9796 let session = match cx
9797 .update(|cx| {
9798 remote::RemoteClient::new(
9799 ConnectionIdentifier::Workspace(workspace_id.0),
9800 remote_connection,
9801 cancel_rx,
9802 delegate,
9803 cx,
9804 )
9805 })
9806 .await?
9807 {
9808 Some(result) => result,
9809 None => return Ok(Vec::new()),
9810 };
9811
9812 let project = cx.update(|cx| {
9813 project::Project::remote(
9814 session,
9815 app_state.client.clone(),
9816 app_state.node_runtime.clone(),
9817 app_state.user_store.clone(),
9818 app_state.languages.clone(),
9819 app_state.fs.clone(),
9820 true,
9821 cx,
9822 )
9823 });
9824
9825 open_remote_project_inner(
9826 project,
9827 paths,
9828 workspace_id,
9829 serialized_workspace,
9830 app_state,
9831 window,
9832 None,
9833 cx,
9834 )
9835 .await
9836 })
9837}
9838
9839pub fn open_remote_project_with_existing_connection(
9840 connection_options: RemoteConnectionOptions,
9841 project: Entity<Project>,
9842 paths: Vec<PathBuf>,
9843 app_state: Arc<AppState>,
9844 window: WindowHandle<MultiWorkspace>,
9845 provisional_project_group_key: Option<ProjectGroupKey>,
9846 cx: &mut AsyncApp,
9847) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9848 cx.spawn(async move |cx| {
9849 let (workspace_id, serialized_workspace) =
9850 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9851
9852 open_remote_project_inner(
9853 project,
9854 paths,
9855 workspace_id,
9856 serialized_workspace,
9857 app_state,
9858 window,
9859 provisional_project_group_key,
9860 cx,
9861 )
9862 .await
9863 })
9864}
9865
9866async fn open_remote_project_inner(
9867 project: Entity<Project>,
9868 paths: Vec<PathBuf>,
9869 workspace_id: WorkspaceId,
9870 serialized_workspace: Option<SerializedWorkspace>,
9871 app_state: Arc<AppState>,
9872 window: WindowHandle<MultiWorkspace>,
9873 provisional_project_group_key: Option<ProjectGroupKey>,
9874 cx: &mut AsyncApp,
9875) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9876 let db = cx.update(|cx| WorkspaceDb::global(cx));
9877 let toolchains = db.toolchains(workspace_id).await?;
9878 for (toolchain, worktree_path, path) in toolchains {
9879 project
9880 .update(cx, |this, cx| {
9881 let Some(worktree_id) =
9882 this.find_worktree(&worktree_path, cx)
9883 .and_then(|(worktree, rel_path)| {
9884 if rel_path.is_empty() {
9885 Some(worktree.read(cx).id())
9886 } else {
9887 None
9888 }
9889 })
9890 else {
9891 return Task::ready(None);
9892 };
9893
9894 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9895 })
9896 .await;
9897 }
9898 let mut project_paths_to_open = vec![];
9899 let mut project_path_errors = vec![];
9900
9901 for path in paths {
9902 let result = cx
9903 .update(|cx| {
9904 Workspace::project_path_for_path(project.clone(), path.as_path(), true, cx)
9905 })
9906 .await;
9907 match result {
9908 Ok((_, project_path)) => {
9909 project_paths_to_open.push((path, Some(project_path)));
9910 }
9911 Err(error) => {
9912 project_path_errors.push(error);
9913 }
9914 };
9915 }
9916
9917 if project_paths_to_open.is_empty() {
9918 return Err(project_path_errors.pop().context("no paths given")?);
9919 }
9920
9921 let workspace = window.update(cx, |multi_workspace, window, cx| {
9922 telemetry::event!("SSH Project Opened");
9923
9924 let new_workspace = cx.new(|cx| {
9925 let mut workspace =
9926 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9927 workspace.update_history(cx);
9928
9929 if let Some(ref serialized) = serialized_workspace {
9930 workspace.centered_layout = serialized.centered_layout;
9931 }
9932
9933 workspace
9934 });
9935
9936 if let Some(project_group_key) = provisional_project_group_key.clone() {
9937 multi_workspace.retain_workspace(new_workspace.clone(), project_group_key, cx);
9938 }
9939 multi_workspace.activate(new_workspace.clone(), window, cx);
9940 new_workspace
9941 })?;
9942
9943 let items = window
9944 .update(cx, |_, window, cx| {
9945 window.activate_window();
9946 workspace.update(cx, |_workspace, cx| {
9947 open_items(serialized_workspace, project_paths_to_open, window, cx)
9948 })
9949 })?
9950 .await?;
9951
9952 workspace.update(cx, |workspace, cx| {
9953 for error in project_path_errors {
9954 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9955 if let Some(path) = error.error_tag("path") {
9956 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9957 }
9958 } else {
9959 workspace.show_error(&error, cx)
9960 }
9961 }
9962 });
9963
9964 Ok(items.into_iter().map(|item| item?.ok()).collect())
9965}
9966
9967fn deserialize_remote_project(
9968 connection_options: RemoteConnectionOptions,
9969 paths: Vec<PathBuf>,
9970 cx: &AsyncApp,
9971) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9972 let db = cx.update(|cx| WorkspaceDb::global(cx));
9973 cx.background_spawn(async move {
9974 let remote_connection_id = db
9975 .get_or_create_remote_connection(connection_options)
9976 .await?;
9977
9978 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9979
9980 let workspace_id = if let Some(workspace_id) =
9981 serialized_workspace.as_ref().map(|workspace| workspace.id)
9982 {
9983 workspace_id
9984 } else {
9985 db.next_id().await?
9986 };
9987
9988 Ok((workspace_id, serialized_workspace))
9989 })
9990}
9991
9992pub fn join_in_room_project(
9993 project_id: u64,
9994 follow_user_id: u64,
9995 app_state: Arc<AppState>,
9996 cx: &mut App,
9997) -> Task<Result<()>> {
9998 let windows = cx.windows();
9999 cx.spawn(async move |cx| {
10000 let existing_window_and_workspace: Option<(
10001 WindowHandle<MultiWorkspace>,
10002 Entity<Workspace>,
10003 )> = windows.into_iter().find_map(|window_handle| {
10004 window_handle
10005 .downcast::<MultiWorkspace>()
10006 .and_then(|window_handle| {
10007 window_handle
10008 .update(cx, |multi_workspace, _window, cx| {
10009 multi_workspace
10010 .workspaces()
10011 .find(|workspace| {
10012 workspace.read(cx).project().read(cx).remote_id()
10013 == Some(project_id)
10014 })
10015 .map(|workspace| (window_handle, workspace.clone()))
10016 })
10017 .unwrap_or(None)
10018 })
10019 });
10020
10021 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
10022 existing_window_and_workspace
10023 {
10024 existing_window
10025 .update(cx, |multi_workspace, window, cx| {
10026 multi_workspace.activate(target_workspace, window, cx);
10027 })
10028 .ok();
10029 existing_window
10030 } else {
10031 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
10032 let project = cx
10033 .update(|cx| {
10034 active_call.0.join_project(
10035 project_id,
10036 app_state.languages.clone(),
10037 app_state.fs.clone(),
10038 cx,
10039 )
10040 })
10041 .await?;
10042
10043 let window_bounds_override = window_bounds_env_override();
10044 cx.update(|cx| {
10045 let mut options = (app_state.build_window_options)(None, cx);
10046 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
10047 cx.open_window(options, |window, cx| {
10048 let workspace = cx.new(|cx| {
10049 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
10050 });
10051 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
10052 })
10053 })?
10054 };
10055
10056 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
10057 cx.activate(true);
10058 window.activate_window();
10059
10060 // We set the active workspace above, so this is the correct workspace.
10061 let workspace = multi_workspace.workspace().clone();
10062 workspace.update(cx, |workspace, cx| {
10063 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
10064 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
10065 .or_else(|| {
10066 // If we couldn't follow the given user, follow the host instead.
10067 let collaborator = workspace
10068 .project()
10069 .read(cx)
10070 .collaborators()
10071 .values()
10072 .find(|collaborator| collaborator.is_host)?;
10073 Some(collaborator.peer_id)
10074 });
10075
10076 if let Some(follow_peer_id) = follow_peer_id {
10077 workspace.follow(follow_peer_id, window, cx);
10078 }
10079 });
10080 })?;
10081
10082 anyhow::Ok(())
10083 })
10084}
10085
10086pub fn reload(cx: &mut App) {
10087 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
10088 let mut workspace_windows = cx
10089 .windows()
10090 .into_iter()
10091 .filter_map(|window| window.downcast::<MultiWorkspace>())
10092 .collect::<Vec<_>>();
10093
10094 // If multiple windows have unsaved changes, and need a save prompt,
10095 // prompt in the active window before switching to a different window.
10096 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
10097
10098 let mut prompt = None;
10099 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
10100 prompt = window
10101 .update(cx, |_, window, cx| {
10102 window.prompt(
10103 PromptLevel::Info,
10104 "Are you sure you want to restart?",
10105 None,
10106 &["Restart", "Cancel"],
10107 cx,
10108 )
10109 })
10110 .ok();
10111 }
10112
10113 cx.spawn(async move |cx| {
10114 if let Some(prompt) = prompt {
10115 let answer = prompt.await?;
10116 if answer != 0 {
10117 return anyhow::Ok(());
10118 }
10119 }
10120
10121 // If the user cancels any save prompt, then keep the app open.
10122 for window in workspace_windows {
10123 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
10124 let workspace = multi_workspace.workspace().clone();
10125 workspace.update(cx, |workspace, cx| {
10126 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
10127 })
10128 }) && !should_close.await?
10129 {
10130 return anyhow::Ok(());
10131 }
10132 }
10133 cx.update(|cx| cx.restart());
10134 anyhow::Ok(())
10135 })
10136 .detach_and_log_err(cx);
10137}
10138
10139fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
10140 let mut parts = value.split(',');
10141 let x: usize = parts.next()?.parse().ok()?;
10142 let y: usize = parts.next()?.parse().ok()?;
10143 Some(point(px(x as f32), px(y as f32)))
10144}
10145
10146fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
10147 let mut parts = value.split(',');
10148 let width: usize = parts.next()?.parse().ok()?;
10149 let height: usize = parts.next()?.parse().ok()?;
10150 Some(size(px(width as f32), px(height as f32)))
10151}
10152
10153/// Add client-side decorations (rounded corners, shadows, resize handling) when
10154/// appropriate.
10155///
10156/// The `border_radius_tiling` parameter allows overriding which corners get
10157/// rounded, independently of the actual window tiling state. This is used
10158/// specifically for the workspace switcher sidebar: when the sidebar is open,
10159/// we want square corners on the left (so the sidebar appears flush with the
10160/// window edge) but we still need the shadow padding for proper visual
10161/// appearance. Unlike actual window tiling, this only affects border radius -
10162/// not padding or shadows.
10163pub fn client_side_decorations(
10164 element: impl IntoElement,
10165 window: &mut Window,
10166 cx: &mut App,
10167 border_radius_tiling: Tiling,
10168) -> Stateful<Div> {
10169 const BORDER_SIZE: Pixels = px(1.0);
10170 let decorations = window.window_decorations();
10171 let tiling = match decorations {
10172 Decorations::Server => Tiling::default(),
10173 Decorations::Client { tiling } => tiling,
10174 };
10175
10176 match decorations {
10177 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
10178 Decorations::Server => window.set_client_inset(px(0.0)),
10179 }
10180
10181 struct GlobalResizeEdge(ResizeEdge);
10182 impl Global for GlobalResizeEdge {}
10183
10184 div()
10185 .id("window-backdrop")
10186 .bg(transparent_black())
10187 .map(|div| match decorations {
10188 Decorations::Server => div,
10189 Decorations::Client { .. } => div
10190 .when(
10191 !(tiling.top
10192 || tiling.right
10193 || border_radius_tiling.top
10194 || border_radius_tiling.right),
10195 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10196 )
10197 .when(
10198 !(tiling.top
10199 || tiling.left
10200 || border_radius_tiling.top
10201 || border_radius_tiling.left),
10202 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10203 )
10204 .when(
10205 !(tiling.bottom
10206 || tiling.right
10207 || border_radius_tiling.bottom
10208 || border_radius_tiling.right),
10209 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10210 )
10211 .when(
10212 !(tiling.bottom
10213 || tiling.left
10214 || border_radius_tiling.bottom
10215 || border_radius_tiling.left),
10216 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10217 )
10218 .when(!tiling.top, |div| {
10219 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
10220 })
10221 .when(!tiling.bottom, |div| {
10222 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
10223 })
10224 .when(!tiling.left, |div| {
10225 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
10226 })
10227 .when(!tiling.right, |div| {
10228 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10229 })
10230 .on_mouse_move(move |e, window, cx| {
10231 let size = window.window_bounds().get_bounds().size;
10232 let pos = e.position;
10233
10234 let new_edge =
10235 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10236
10237 let edge = cx.try_global::<GlobalResizeEdge>();
10238 if new_edge != edge.map(|edge| edge.0) {
10239 window
10240 .window_handle()
10241 .update(cx, |workspace, _, cx| {
10242 cx.notify(workspace.entity_id());
10243 })
10244 .ok();
10245 }
10246 })
10247 .on_mouse_down(MouseButton::Left, move |e, window, _| {
10248 let size = window.window_bounds().get_bounds().size;
10249 let pos = e.position;
10250
10251 let edge = match resize_edge(
10252 pos,
10253 theme::CLIENT_SIDE_DECORATION_SHADOW,
10254 size,
10255 tiling,
10256 ) {
10257 Some(value) => value,
10258 None => return,
10259 };
10260
10261 window.start_window_resize(edge);
10262 }),
10263 })
10264 .size_full()
10265 .child(
10266 div()
10267 .cursor(CursorStyle::Arrow)
10268 .map(|div| match decorations {
10269 Decorations::Server => div,
10270 Decorations::Client { .. } => div
10271 .border_color(cx.theme().colors().border)
10272 .when(
10273 !(tiling.top
10274 || tiling.right
10275 || border_radius_tiling.top
10276 || border_radius_tiling.right),
10277 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10278 )
10279 .when(
10280 !(tiling.top
10281 || tiling.left
10282 || border_radius_tiling.top
10283 || border_radius_tiling.left),
10284 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10285 )
10286 .when(
10287 !(tiling.bottom
10288 || tiling.right
10289 || border_radius_tiling.bottom
10290 || border_radius_tiling.right),
10291 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10292 )
10293 .when(
10294 !(tiling.bottom
10295 || tiling.left
10296 || border_radius_tiling.bottom
10297 || border_radius_tiling.left),
10298 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10299 )
10300 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10301 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10302 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10303 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10304 .when(!tiling.is_tiled(), |div| {
10305 div.shadow(vec![gpui::BoxShadow {
10306 color: Hsla {
10307 h: 0.,
10308 s: 0.,
10309 l: 0.,
10310 a: 0.4,
10311 },
10312 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10313 spread_radius: px(0.),
10314 offset: point(px(0.0), px(0.0)),
10315 }])
10316 }),
10317 })
10318 .on_mouse_move(|_e, _, cx| {
10319 cx.stop_propagation();
10320 })
10321 .size_full()
10322 .child(element),
10323 )
10324 .map(|div| match decorations {
10325 Decorations::Server => div,
10326 Decorations::Client { tiling, .. } => div.child(
10327 canvas(
10328 |_bounds, window, _| {
10329 window.insert_hitbox(
10330 Bounds::new(
10331 point(px(0.0), px(0.0)),
10332 window.window_bounds().get_bounds().size,
10333 ),
10334 HitboxBehavior::Normal,
10335 )
10336 },
10337 move |_bounds, hitbox, window, cx| {
10338 let mouse = window.mouse_position();
10339 let size = window.window_bounds().get_bounds().size;
10340 let Some(edge) =
10341 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10342 else {
10343 return;
10344 };
10345 cx.set_global(GlobalResizeEdge(edge));
10346 window.set_cursor_style(
10347 match edge {
10348 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10349 ResizeEdge::Left | ResizeEdge::Right => {
10350 CursorStyle::ResizeLeftRight
10351 }
10352 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10353 CursorStyle::ResizeUpLeftDownRight
10354 }
10355 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10356 CursorStyle::ResizeUpRightDownLeft
10357 }
10358 },
10359 &hitbox,
10360 );
10361 },
10362 )
10363 .size_full()
10364 .absolute(),
10365 ),
10366 })
10367}
10368
10369fn resize_edge(
10370 pos: Point<Pixels>,
10371 shadow_size: Pixels,
10372 window_size: Size<Pixels>,
10373 tiling: Tiling,
10374) -> Option<ResizeEdge> {
10375 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10376 if bounds.contains(&pos) {
10377 return None;
10378 }
10379
10380 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10381 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10382 if !tiling.top && top_left_bounds.contains(&pos) {
10383 return Some(ResizeEdge::TopLeft);
10384 }
10385
10386 let top_right_bounds = Bounds::new(
10387 Point::new(window_size.width - corner_size.width, px(0.)),
10388 corner_size,
10389 );
10390 if !tiling.top && top_right_bounds.contains(&pos) {
10391 return Some(ResizeEdge::TopRight);
10392 }
10393
10394 let bottom_left_bounds = Bounds::new(
10395 Point::new(px(0.), window_size.height - corner_size.height),
10396 corner_size,
10397 );
10398 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10399 return Some(ResizeEdge::BottomLeft);
10400 }
10401
10402 let bottom_right_bounds = Bounds::new(
10403 Point::new(
10404 window_size.width - corner_size.width,
10405 window_size.height - corner_size.height,
10406 ),
10407 corner_size,
10408 );
10409 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10410 return Some(ResizeEdge::BottomRight);
10411 }
10412
10413 if !tiling.top && pos.y < shadow_size {
10414 Some(ResizeEdge::Top)
10415 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10416 Some(ResizeEdge::Bottom)
10417 } else if !tiling.left && pos.x < shadow_size {
10418 Some(ResizeEdge::Left)
10419 } else if !tiling.right && pos.x > window_size.width - shadow_size {
10420 Some(ResizeEdge::Right)
10421 } else {
10422 None
10423 }
10424}
10425
10426fn join_pane_into_active(
10427 active_pane: &Entity<Pane>,
10428 pane: &Entity<Pane>,
10429 window: &mut Window,
10430 cx: &mut App,
10431) {
10432 if pane == active_pane {
10433 } else if pane.read(cx).items_len() == 0 {
10434 pane.update(cx, |_, cx| {
10435 cx.emit(pane::Event::Remove {
10436 focus_on_pane: None,
10437 });
10438 })
10439 } else {
10440 move_all_items(pane, active_pane, window, cx);
10441 }
10442}
10443
10444fn move_all_items(
10445 from_pane: &Entity<Pane>,
10446 to_pane: &Entity<Pane>,
10447 window: &mut Window,
10448 cx: &mut App,
10449) {
10450 let destination_is_different = from_pane != to_pane;
10451 let mut moved_items = 0;
10452 for (item_ix, item_handle) in from_pane
10453 .read(cx)
10454 .items()
10455 .enumerate()
10456 .map(|(ix, item)| (ix, item.clone()))
10457 .collect::<Vec<_>>()
10458 {
10459 let ix = item_ix - moved_items;
10460 if destination_is_different {
10461 // Close item from previous pane
10462 from_pane.update(cx, |source, cx| {
10463 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10464 });
10465 moved_items += 1;
10466 }
10467
10468 // This automatically removes duplicate items in the pane
10469 to_pane.update(cx, |destination, cx| {
10470 destination.add_item(item_handle, true, true, None, window, cx);
10471 window.focus(&destination.focus_handle(cx), cx)
10472 });
10473 }
10474}
10475
10476pub fn move_item(
10477 source: &Entity<Pane>,
10478 destination: &Entity<Pane>,
10479 item_id_to_move: EntityId,
10480 destination_index: usize,
10481 activate: bool,
10482 window: &mut Window,
10483 cx: &mut App,
10484) {
10485 let Some((item_ix, item_handle)) = source
10486 .read(cx)
10487 .items()
10488 .enumerate()
10489 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10490 .map(|(ix, item)| (ix, item.clone()))
10491 else {
10492 // Tab was closed during drag
10493 return;
10494 };
10495
10496 if source != destination {
10497 // Close item from previous pane
10498 source.update(cx, |source, cx| {
10499 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10500 });
10501 }
10502
10503 // This automatically removes duplicate items in the pane
10504 destination.update(cx, |destination, cx| {
10505 destination.add_item_inner(
10506 item_handle,
10507 activate,
10508 activate,
10509 activate,
10510 Some(destination_index),
10511 window,
10512 cx,
10513 );
10514 if activate {
10515 window.focus(&destination.focus_handle(cx), cx)
10516 }
10517 });
10518}
10519
10520pub fn move_active_item(
10521 source: &Entity<Pane>,
10522 destination: &Entity<Pane>,
10523 focus_destination: bool,
10524 close_if_empty: bool,
10525 window: &mut Window,
10526 cx: &mut App,
10527) {
10528 if source == destination {
10529 return;
10530 }
10531 let Some(active_item) = source.read(cx).active_item() else {
10532 return;
10533 };
10534 source.update(cx, |source_pane, cx| {
10535 let item_id = active_item.item_id();
10536 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10537 destination.update(cx, |target_pane, cx| {
10538 target_pane.add_item(
10539 active_item,
10540 focus_destination,
10541 focus_destination,
10542 Some(target_pane.items_len()),
10543 window,
10544 cx,
10545 );
10546 });
10547 });
10548}
10549
10550pub fn clone_active_item(
10551 workspace_id: Option<WorkspaceId>,
10552 source: &Entity<Pane>,
10553 destination: &Entity<Pane>,
10554 focus_destination: bool,
10555 window: &mut Window,
10556 cx: &mut App,
10557) {
10558 if source == destination {
10559 return;
10560 }
10561 let Some(active_item) = source.read(cx).active_item() else {
10562 return;
10563 };
10564 if !active_item.can_split(cx) {
10565 return;
10566 }
10567 let destination = destination.downgrade();
10568 let task = active_item.clone_on_split(workspace_id, window, cx);
10569 window
10570 .spawn(cx, async move |cx| {
10571 let Some(clone) = task.await else {
10572 return;
10573 };
10574 destination
10575 .update_in(cx, |target_pane, window, cx| {
10576 target_pane.add_item(
10577 clone,
10578 focus_destination,
10579 focus_destination,
10580 Some(target_pane.items_len()),
10581 window,
10582 cx,
10583 );
10584 })
10585 .log_err();
10586 })
10587 .detach();
10588}
10589
10590#[derive(Debug)]
10591pub struct WorkspacePosition {
10592 pub window_bounds: Option<WindowBounds>,
10593 pub display: Option<Uuid>,
10594 pub centered_layout: bool,
10595}
10596
10597pub fn remote_workspace_position_from_db(
10598 connection_options: RemoteConnectionOptions,
10599 paths_to_open: &[PathBuf],
10600 cx: &App,
10601) -> Task<Result<WorkspacePosition>> {
10602 let paths = paths_to_open.to_vec();
10603 let db = WorkspaceDb::global(cx);
10604 let kvp = db::kvp::KeyValueStore::global(cx);
10605
10606 cx.background_spawn(async move {
10607 let remote_connection_id = db
10608 .get_or_create_remote_connection(connection_options)
10609 .await
10610 .context("fetching serialized ssh project")?;
10611 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10612
10613 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10614 (Some(WindowBounds::Windowed(bounds)), None)
10615 } else {
10616 let restorable_bounds = serialized_workspace
10617 .as_ref()
10618 .and_then(|workspace| {
10619 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10620 })
10621 .or_else(|| persistence::read_default_window_bounds(&kvp));
10622
10623 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10624 (Some(serialized_bounds), Some(serialized_display))
10625 } else {
10626 (None, None)
10627 }
10628 };
10629
10630 let centered_layout = serialized_workspace
10631 .as_ref()
10632 .map(|w| w.centered_layout)
10633 .unwrap_or(false);
10634
10635 Ok(WorkspacePosition {
10636 window_bounds,
10637 display,
10638 centered_layout,
10639 })
10640 })
10641}
10642
10643pub fn with_active_or_new_workspace(
10644 cx: &mut App,
10645 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10646) {
10647 match cx
10648 .active_window()
10649 .and_then(|w| w.downcast::<MultiWorkspace>())
10650 {
10651 Some(multi_workspace) => {
10652 cx.defer(move |cx| {
10653 multi_workspace
10654 .update(cx, |multi_workspace, window, cx| {
10655 let workspace = multi_workspace.workspace().clone();
10656 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10657 })
10658 .log_err();
10659 });
10660 }
10661 None => {
10662 let app_state = AppState::global(cx);
10663 open_new(
10664 OpenOptions::default(),
10665 app_state,
10666 cx,
10667 move |workspace, window, cx| f(workspace, window, cx),
10668 )
10669 .detach_and_log_err(cx);
10670 }
10671 }
10672}
10673
10674/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10675/// key. This migration path only runs once per panel per workspace.
10676fn load_legacy_panel_size(
10677 panel_key: &str,
10678 dock_position: DockPosition,
10679 workspace: &Workspace,
10680 cx: &mut App,
10681) -> Option<Pixels> {
10682 #[derive(Deserialize)]
10683 struct LegacyPanelState {
10684 #[serde(default)]
10685 width: Option<Pixels>,
10686 #[serde(default)]
10687 height: Option<Pixels>,
10688 }
10689
10690 let workspace_id = workspace
10691 .database_id()
10692 .map(|id| i64::from(id).to_string())
10693 .or_else(|| workspace.session_id())?;
10694
10695 let legacy_key = match panel_key {
10696 "ProjectPanel" => {
10697 format!("{}-{:?}", "ProjectPanel", workspace_id)
10698 }
10699 "OutlinePanel" => {
10700 format!("{}-{:?}", "OutlinePanel", workspace_id)
10701 }
10702 "GitPanel" => {
10703 format!("{}-{:?}", "GitPanel", workspace_id)
10704 }
10705 "TerminalPanel" => {
10706 format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10707 }
10708 _ => return None,
10709 };
10710
10711 let kvp = db::kvp::KeyValueStore::global(cx);
10712 let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10713 let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10714 let size = match dock_position {
10715 DockPosition::Bottom => state.height,
10716 DockPosition::Left | DockPosition::Right => state.width,
10717 }?;
10718
10719 cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10720 .detach_and_log_err(cx);
10721
10722 Some(size)
10723}
10724
10725#[cfg(test)]
10726mod tests {
10727 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10728
10729 use super::*;
10730 use crate::{
10731 dock::{PanelEvent, test::TestPanel},
10732 item::{
10733 ItemBufferKind, ItemEvent,
10734 test::{TestItem, TestProjectItem},
10735 },
10736 };
10737 use fs::FakeFs;
10738 use gpui::{
10739 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10740 UpdateGlobal, VisualTestContext, px,
10741 };
10742 use project::{Project, ProjectEntryId};
10743 use serde_json::json;
10744 use settings::SettingsStore;
10745 use util::path;
10746 use util::rel_path::rel_path;
10747
10748 #[gpui::test]
10749 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10750 init_test(cx);
10751
10752 let fs = FakeFs::new(cx.executor());
10753 let project = Project::test(fs, [], cx).await;
10754 let (workspace, cx) =
10755 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10756
10757 // Adding an item with no ambiguity renders the tab without detail.
10758 let item1 = cx.new(|cx| {
10759 let mut item = TestItem::new(cx);
10760 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10761 item
10762 });
10763 workspace.update_in(cx, |workspace, window, cx| {
10764 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10765 });
10766 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10767
10768 // Adding an item that creates ambiguity increases the level of detail on
10769 // both tabs.
10770 let item2 = cx.new_window_entity(|_window, cx| {
10771 let mut item = TestItem::new(cx);
10772 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10773 item
10774 });
10775 workspace.update_in(cx, |workspace, window, cx| {
10776 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10777 });
10778 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10779 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10780
10781 // Adding an item that creates ambiguity increases the level of detail only
10782 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10783 // we stop at the highest detail available.
10784 let item3 = cx.new(|cx| {
10785 let mut item = TestItem::new(cx);
10786 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10787 item
10788 });
10789 workspace.update_in(cx, |workspace, window, cx| {
10790 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10791 });
10792 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10793 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10794 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10795 }
10796
10797 #[gpui::test]
10798 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10799 init_test(cx);
10800
10801 let fs = FakeFs::new(cx.executor());
10802 fs.insert_tree(
10803 "/root1",
10804 json!({
10805 "one.txt": "",
10806 "two.txt": "",
10807 }),
10808 )
10809 .await;
10810 fs.insert_tree(
10811 "/root2",
10812 json!({
10813 "three.txt": "",
10814 }),
10815 )
10816 .await;
10817
10818 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10819 let (workspace, cx) =
10820 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10821 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10822 let worktree_id = project.update(cx, |project, cx| {
10823 project.worktrees(cx).next().unwrap().read(cx).id()
10824 });
10825
10826 let item1 = cx.new(|cx| {
10827 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10828 });
10829 let item2 = cx.new(|cx| {
10830 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10831 });
10832
10833 // Add an item to an empty pane
10834 workspace.update_in(cx, |workspace, window, cx| {
10835 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10836 });
10837 project.update(cx, |project, cx| {
10838 assert_eq!(
10839 project.active_entry(),
10840 project
10841 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10842 .map(|e| e.id)
10843 );
10844 });
10845 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10846
10847 // Add a second item to a non-empty pane
10848 workspace.update_in(cx, |workspace, window, cx| {
10849 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10850 });
10851 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10852 project.update(cx, |project, cx| {
10853 assert_eq!(
10854 project.active_entry(),
10855 project
10856 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10857 .map(|e| e.id)
10858 );
10859 });
10860
10861 // Close the active item
10862 pane.update_in(cx, |pane, window, cx| {
10863 pane.close_active_item(&Default::default(), window, cx)
10864 })
10865 .await
10866 .unwrap();
10867 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10868 project.update(cx, |project, cx| {
10869 assert_eq!(
10870 project.active_entry(),
10871 project
10872 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10873 .map(|e| e.id)
10874 );
10875 });
10876
10877 // Add a project folder
10878 project
10879 .update(cx, |project, cx| {
10880 project.find_or_create_worktree("root2", true, cx)
10881 })
10882 .await
10883 .unwrap();
10884 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10885
10886 // Remove a project folder
10887 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10888 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10889 }
10890
10891 #[gpui::test]
10892 async fn test_close_window(cx: &mut TestAppContext) {
10893 init_test(cx);
10894
10895 let fs = FakeFs::new(cx.executor());
10896 fs.insert_tree("/root", json!({ "one": "" })).await;
10897
10898 let project = Project::test(fs, ["root".as_ref()], cx).await;
10899 let (workspace, cx) =
10900 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10901
10902 // When there are no dirty items, there's nothing to do.
10903 let item1 = cx.new(TestItem::new);
10904 workspace.update_in(cx, |w, window, cx| {
10905 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10906 });
10907 let task = workspace.update_in(cx, |w, window, cx| {
10908 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10909 });
10910 assert!(task.await.unwrap());
10911
10912 // When there are dirty untitled items, prompt to save each one. If the user
10913 // cancels any prompt, then abort.
10914 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10915 let item3 = cx.new(|cx| {
10916 TestItem::new(cx)
10917 .with_dirty(true)
10918 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10919 });
10920 workspace.update_in(cx, |w, window, cx| {
10921 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10922 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10923 });
10924 let task = workspace.update_in(cx, |w, window, cx| {
10925 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10926 });
10927 cx.executor().run_until_parked();
10928 cx.simulate_prompt_answer("Cancel"); // cancel save all
10929 cx.executor().run_until_parked();
10930 assert!(!cx.has_pending_prompt());
10931 assert!(!task.await.unwrap());
10932 }
10933
10934 #[gpui::test]
10935 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10936 init_test(cx);
10937
10938 let fs = FakeFs::new(cx.executor());
10939 fs.insert_tree("/root", json!({ "one": "" })).await;
10940
10941 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10942 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10943 let multi_workspace_handle =
10944 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10945 cx.run_until_parked();
10946
10947 multi_workspace_handle
10948 .update(cx, |mw, _window, cx| {
10949 mw.open_sidebar(cx);
10950 })
10951 .unwrap();
10952
10953 let workspace_a = multi_workspace_handle
10954 .read_with(cx, |mw, _| mw.workspace().clone())
10955 .unwrap();
10956
10957 let workspace_b = multi_workspace_handle
10958 .update(cx, |mw, window, cx| {
10959 mw.test_add_workspace(project_b, window, cx)
10960 })
10961 .unwrap();
10962
10963 // Activate workspace A
10964 multi_workspace_handle
10965 .update(cx, |mw, window, cx| {
10966 mw.activate(workspace_a.clone(), window, cx);
10967 })
10968 .unwrap();
10969
10970 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10971
10972 // Workspace A has a clean item
10973 let item_a = cx.new(TestItem::new);
10974 workspace_a.update_in(cx, |w, window, cx| {
10975 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10976 });
10977
10978 // Workspace B has a dirty item
10979 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10980 workspace_b.update_in(cx, |w, window, cx| {
10981 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10982 });
10983
10984 // Verify workspace A is active
10985 multi_workspace_handle
10986 .read_with(cx, |mw, _| {
10987 assert_eq!(mw.workspace(), &workspace_a);
10988 })
10989 .unwrap();
10990
10991 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10992 multi_workspace_handle
10993 .update(cx, |mw, window, cx| {
10994 mw.close_window(&CloseWindow, window, cx);
10995 })
10996 .unwrap();
10997 cx.run_until_parked();
10998
10999 // Workspace B should now be active since it has dirty items that need attention
11000 multi_workspace_handle
11001 .read_with(cx, |mw, _| {
11002 assert_eq!(
11003 mw.workspace(),
11004 &workspace_b,
11005 "workspace B should be activated when it prompts"
11006 );
11007 })
11008 .unwrap();
11009
11010 // User cancels the save prompt from workspace B
11011 cx.simulate_prompt_answer("Cancel");
11012 cx.run_until_parked();
11013
11014 // Window should still exist because workspace B's close was cancelled
11015 assert!(
11016 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
11017 "window should still exist after cancelling one workspace's close"
11018 );
11019 }
11020
11021 #[gpui::test]
11022 async fn test_remove_workspace_prompts_for_unsaved_changes(cx: &mut TestAppContext) {
11023 init_test(cx);
11024
11025 let fs = FakeFs::new(cx.executor());
11026 fs.insert_tree("/root", json!({ "one": "" })).await;
11027
11028 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
11029 let project_b = Project::test(fs.clone(), ["root".as_ref()], cx).await;
11030 let multi_workspace_handle =
11031 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
11032 cx.run_until_parked();
11033
11034 multi_workspace_handle
11035 .update(cx, |mw, _window, cx| mw.open_sidebar(cx))
11036 .unwrap();
11037
11038 let workspace_a = multi_workspace_handle
11039 .read_with(cx, |mw, _| mw.workspace().clone())
11040 .unwrap();
11041
11042 let workspace_b = multi_workspace_handle
11043 .update(cx, |mw, window, cx| {
11044 mw.test_add_workspace(project_b, window, cx)
11045 })
11046 .unwrap();
11047
11048 // Activate workspace A.
11049 multi_workspace_handle
11050 .update(cx, |mw, window, cx| {
11051 mw.activate(workspace_a.clone(), window, cx);
11052 })
11053 .unwrap();
11054
11055 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
11056
11057 // Workspace B has a dirty item.
11058 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
11059 workspace_b.update_in(cx, |w, window, cx| {
11060 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
11061 });
11062
11063 // Try to remove workspace B. It should prompt because of the dirty item.
11064 let remove_task = multi_workspace_handle
11065 .update(cx, |mw, window, cx| {
11066 mw.remove([workspace_b.clone()], |_, _, _| unreachable!(), window, cx)
11067 })
11068 .unwrap();
11069 cx.run_until_parked();
11070
11071 // The prompt should have activated workspace B.
11072 multi_workspace_handle
11073 .read_with(cx, |mw, _| {
11074 assert_eq!(
11075 mw.workspace(),
11076 &workspace_b,
11077 "workspace B should be active while prompting"
11078 );
11079 })
11080 .unwrap();
11081
11082 // Cancel the prompt — user stays on workspace B.
11083 cx.simulate_prompt_answer("Cancel");
11084 cx.run_until_parked();
11085 let removed = remove_task.await.unwrap();
11086 assert!(!removed, "removal should have been cancelled");
11087
11088 multi_workspace_handle
11089 .read_with(cx, |mw, _cx| {
11090 assert_eq!(
11091 mw.workspace(),
11092 &workspace_b,
11093 "user should stay on workspace B after cancelling"
11094 );
11095 assert_eq!(mw.workspaces().count(), 2, "both workspaces should remain");
11096 })
11097 .unwrap();
11098
11099 // Try again. This time accept the prompt.
11100 let remove_task = multi_workspace_handle
11101 .update(cx, |mw, window, cx| {
11102 // First switch back to A.
11103 mw.activate(workspace_a.clone(), window, cx);
11104 mw.remove([workspace_b.clone()], |_, _, _| unreachable!(), window, cx)
11105 })
11106 .unwrap();
11107 cx.run_until_parked();
11108
11109 // Accept the save prompt.
11110 cx.simulate_prompt_answer("Don't Save");
11111 cx.run_until_parked();
11112 let removed = remove_task.await.unwrap();
11113 assert!(removed, "removal should have succeeded");
11114
11115 // Should be back on workspace A, and B should be gone.
11116 multi_workspace_handle
11117 .read_with(cx, |mw, _cx| {
11118 assert_eq!(
11119 mw.workspace(),
11120 &workspace_a,
11121 "should be back on workspace A after removing B"
11122 );
11123 assert_eq!(mw.workspaces().count(), 1, "only workspace A should remain");
11124 })
11125 .unwrap();
11126 }
11127
11128 #[gpui::test]
11129 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
11130 init_test(cx);
11131
11132 // Register TestItem as a serializable item
11133 cx.update(|cx| {
11134 register_serializable_item::<TestItem>(cx);
11135 });
11136
11137 let fs = FakeFs::new(cx.executor());
11138 fs.insert_tree("/root", json!({ "one": "" })).await;
11139
11140 let project = Project::test(fs, ["root".as_ref()], cx).await;
11141 let (workspace, cx) =
11142 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11143
11144 // When there are dirty untitled items, but they can serialize, then there is no prompt.
11145 let item1 = cx.new(|cx| {
11146 TestItem::new(cx)
11147 .with_dirty(true)
11148 .with_serialize(|| Some(Task::ready(Ok(()))))
11149 });
11150 let item2 = cx.new(|cx| {
11151 TestItem::new(cx)
11152 .with_dirty(true)
11153 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11154 .with_serialize(|| Some(Task::ready(Ok(()))))
11155 });
11156 workspace.update_in(cx, |w, window, cx| {
11157 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
11158 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
11159 });
11160 let task = workspace.update_in(cx, |w, window, cx| {
11161 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
11162 });
11163 assert!(task.await.unwrap());
11164 }
11165
11166 #[gpui::test]
11167 async fn test_close_pane_items(cx: &mut TestAppContext) {
11168 init_test(cx);
11169
11170 let fs = FakeFs::new(cx.executor());
11171
11172 let project = Project::test(fs, None, cx).await;
11173 let (workspace, cx) =
11174 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11175
11176 let item1 = cx.new(|cx| {
11177 TestItem::new(cx)
11178 .with_dirty(true)
11179 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11180 });
11181 let item2 = cx.new(|cx| {
11182 TestItem::new(cx)
11183 .with_dirty(true)
11184 .with_conflict(true)
11185 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11186 });
11187 let item3 = cx.new(|cx| {
11188 TestItem::new(cx)
11189 .with_dirty(true)
11190 .with_conflict(true)
11191 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
11192 });
11193 let item4 = cx.new(|cx| {
11194 TestItem::new(cx).with_dirty(true).with_project_items(&[{
11195 let project_item = TestProjectItem::new_untitled(cx);
11196 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11197 project_item
11198 }])
11199 });
11200 let pane = workspace.update_in(cx, |workspace, window, cx| {
11201 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
11202 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
11203 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
11204 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
11205 workspace.active_pane().clone()
11206 });
11207
11208 let close_items = pane.update_in(cx, |pane, window, cx| {
11209 pane.activate_item(1, true, true, window, cx);
11210 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
11211 let item1_id = item1.item_id();
11212 let item3_id = item3.item_id();
11213 let item4_id = item4.item_id();
11214 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
11215 [item1_id, item3_id, item4_id].contains(&id)
11216 })
11217 });
11218 cx.executor().run_until_parked();
11219
11220 assert!(cx.has_pending_prompt());
11221 cx.simulate_prompt_answer("Save all");
11222
11223 cx.executor().run_until_parked();
11224
11225 // Item 1 is saved. There's a prompt to save item 3.
11226 pane.update(cx, |pane, cx| {
11227 assert_eq!(item1.read(cx).save_count, 1);
11228 assert_eq!(item1.read(cx).save_as_count, 0);
11229 assert_eq!(item1.read(cx).reload_count, 0);
11230 assert_eq!(pane.items_len(), 3);
11231 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
11232 });
11233 assert!(cx.has_pending_prompt());
11234
11235 // Cancel saving item 3.
11236 cx.simulate_prompt_answer("Discard");
11237 cx.executor().run_until_parked();
11238
11239 // Item 3 is reloaded. There's a prompt to save item 4.
11240 pane.update(cx, |pane, cx| {
11241 assert_eq!(item3.read(cx).save_count, 0);
11242 assert_eq!(item3.read(cx).save_as_count, 0);
11243 assert_eq!(item3.read(cx).reload_count, 1);
11244 assert_eq!(pane.items_len(), 2);
11245 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
11246 });
11247
11248 // There's a prompt for a path for item 4.
11249 cx.simulate_new_path_selection(|_| Some(Default::default()));
11250 close_items.await.unwrap();
11251
11252 // The requested items are closed.
11253 pane.update(cx, |pane, cx| {
11254 assert_eq!(item4.read(cx).save_count, 0);
11255 assert_eq!(item4.read(cx).save_as_count, 1);
11256 assert_eq!(item4.read(cx).reload_count, 0);
11257 assert_eq!(pane.items_len(), 1);
11258 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
11259 });
11260 }
11261
11262 #[gpui::test]
11263 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
11264 init_test(cx);
11265
11266 let fs = FakeFs::new(cx.executor());
11267 let project = Project::test(fs, [], cx).await;
11268 let (workspace, cx) =
11269 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11270
11271 // Create several workspace items with single project entries, and two
11272 // workspace items with multiple project entries.
11273 let single_entry_items = (0..=4)
11274 .map(|project_entry_id| {
11275 cx.new(|cx| {
11276 TestItem::new(cx)
11277 .with_dirty(true)
11278 .with_project_items(&[dirty_project_item(
11279 project_entry_id,
11280 &format!("{project_entry_id}.txt"),
11281 cx,
11282 )])
11283 })
11284 })
11285 .collect::<Vec<_>>();
11286 let item_2_3 = cx.new(|cx| {
11287 TestItem::new(cx)
11288 .with_dirty(true)
11289 .with_buffer_kind(ItemBufferKind::Multibuffer)
11290 .with_project_items(&[
11291 single_entry_items[2].read(cx).project_items[0].clone(),
11292 single_entry_items[3].read(cx).project_items[0].clone(),
11293 ])
11294 });
11295 let item_3_4 = cx.new(|cx| {
11296 TestItem::new(cx)
11297 .with_dirty(true)
11298 .with_buffer_kind(ItemBufferKind::Multibuffer)
11299 .with_project_items(&[
11300 single_entry_items[3].read(cx).project_items[0].clone(),
11301 single_entry_items[4].read(cx).project_items[0].clone(),
11302 ])
11303 });
11304
11305 // Create two panes that contain the following project entries:
11306 // left pane:
11307 // multi-entry items: (2, 3)
11308 // single-entry items: 0, 2, 3, 4
11309 // right pane:
11310 // single-entry items: 4, 1
11311 // multi-entry items: (3, 4)
11312 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
11313 let left_pane = workspace.active_pane().clone();
11314 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
11315 workspace.add_item_to_active_pane(
11316 single_entry_items[0].boxed_clone(),
11317 None,
11318 true,
11319 window,
11320 cx,
11321 );
11322 workspace.add_item_to_active_pane(
11323 single_entry_items[2].boxed_clone(),
11324 None,
11325 true,
11326 window,
11327 cx,
11328 );
11329 workspace.add_item_to_active_pane(
11330 single_entry_items[3].boxed_clone(),
11331 None,
11332 true,
11333 window,
11334 cx,
11335 );
11336 workspace.add_item_to_active_pane(
11337 single_entry_items[4].boxed_clone(),
11338 None,
11339 true,
11340 window,
11341 cx,
11342 );
11343
11344 let right_pane =
11345 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11346
11347 let boxed_clone = single_entry_items[1].boxed_clone();
11348 let right_pane = window.spawn(cx, async move |cx| {
11349 right_pane.await.inspect(|right_pane| {
11350 right_pane
11351 .update_in(cx, |pane, window, cx| {
11352 pane.add_item(boxed_clone, true, true, None, window, cx);
11353 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11354 })
11355 .unwrap();
11356 })
11357 });
11358
11359 (left_pane, right_pane)
11360 });
11361 let right_pane = right_pane.await.unwrap();
11362 cx.focus(&right_pane);
11363
11364 let close = right_pane.update_in(cx, |pane, window, cx| {
11365 pane.close_all_items(&CloseAllItems::default(), window, cx)
11366 .unwrap()
11367 });
11368 cx.executor().run_until_parked();
11369
11370 let msg = cx.pending_prompt().unwrap().0;
11371 assert!(msg.contains("1.txt"));
11372 assert!(!msg.contains("2.txt"));
11373 assert!(!msg.contains("3.txt"));
11374 assert!(!msg.contains("4.txt"));
11375
11376 // With best-effort close, cancelling item 1 keeps it open but items 4
11377 // and (3,4) still close since their entries exist in left pane.
11378 cx.simulate_prompt_answer("Cancel");
11379 close.await;
11380
11381 right_pane.read_with(cx, |pane, _| {
11382 assert_eq!(pane.items_len(), 1);
11383 });
11384
11385 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11386 left_pane
11387 .update_in(cx, |left_pane, window, cx| {
11388 left_pane.close_item_by_id(
11389 single_entry_items[3].entity_id(),
11390 SaveIntent::Skip,
11391 window,
11392 cx,
11393 )
11394 })
11395 .await
11396 .unwrap();
11397
11398 let close = left_pane.update_in(cx, |pane, window, cx| {
11399 pane.close_all_items(&CloseAllItems::default(), window, cx)
11400 .unwrap()
11401 });
11402 cx.executor().run_until_parked();
11403
11404 let details = cx.pending_prompt().unwrap().1;
11405 assert!(details.contains("0.txt"));
11406 assert!(details.contains("3.txt"));
11407 assert!(details.contains("4.txt"));
11408 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11409 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11410 // assert!(!details.contains("2.txt"));
11411
11412 cx.simulate_prompt_answer("Save all");
11413 cx.executor().run_until_parked();
11414 close.await;
11415
11416 left_pane.read_with(cx, |pane, _| {
11417 assert_eq!(pane.items_len(), 0);
11418 });
11419 }
11420
11421 #[gpui::test]
11422 async fn test_autosave(cx: &mut gpui::TestAppContext) {
11423 init_test(cx);
11424
11425 let fs = FakeFs::new(cx.executor());
11426 let project = Project::test(fs, [], cx).await;
11427 let (workspace, cx) =
11428 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11429 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11430
11431 let item = cx.new(|cx| {
11432 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11433 });
11434 let item_id = item.entity_id();
11435 workspace.update_in(cx, |workspace, window, cx| {
11436 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11437 });
11438
11439 // Autosave on window change.
11440 item.update(cx, |item, cx| {
11441 SettingsStore::update_global(cx, |settings, cx| {
11442 settings.update_user_settings(cx, |settings| {
11443 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11444 })
11445 });
11446 item.is_dirty = true;
11447 });
11448
11449 // Deactivating the window saves the file.
11450 cx.deactivate_window();
11451 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11452
11453 // Re-activating the window doesn't save the file.
11454 cx.update(|window, _| window.activate_window());
11455 cx.executor().run_until_parked();
11456 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11457
11458 // Autosave on focus change.
11459 item.update_in(cx, |item, window, cx| {
11460 cx.focus_self(window);
11461 SettingsStore::update_global(cx, |settings, cx| {
11462 settings.update_user_settings(cx, |settings| {
11463 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11464 })
11465 });
11466 item.is_dirty = true;
11467 });
11468 // Blurring the item saves the file.
11469 item.update_in(cx, |_, window, _| window.blur());
11470 cx.executor().run_until_parked();
11471 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11472
11473 // Deactivating the window still saves the file.
11474 item.update_in(cx, |item, window, cx| {
11475 cx.focus_self(window);
11476 item.is_dirty = true;
11477 });
11478 cx.deactivate_window();
11479 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11480
11481 // Autosave after delay.
11482 item.update(cx, |item, cx| {
11483 SettingsStore::update_global(cx, |settings, cx| {
11484 settings.update_user_settings(cx, |settings| {
11485 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11486 milliseconds: 500.into(),
11487 });
11488 })
11489 });
11490 item.is_dirty = true;
11491 cx.emit(ItemEvent::Edit);
11492 });
11493
11494 // Delay hasn't fully expired, so the file is still dirty and unsaved.
11495 cx.executor().advance_clock(Duration::from_millis(250));
11496 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11497
11498 // After delay expires, the file is saved.
11499 cx.executor().advance_clock(Duration::from_millis(250));
11500 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11501
11502 // Autosave after delay, should save earlier than delay if tab is closed
11503 item.update(cx, |item, cx| {
11504 item.is_dirty = true;
11505 cx.emit(ItemEvent::Edit);
11506 });
11507 cx.executor().advance_clock(Duration::from_millis(250));
11508 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11509
11510 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11511 pane.update_in(cx, |pane, window, cx| {
11512 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11513 })
11514 .await
11515 .unwrap();
11516 assert!(!cx.has_pending_prompt());
11517 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11518
11519 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11520 workspace.update_in(cx, |workspace, window, cx| {
11521 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11522 });
11523 item.update_in(cx, |item, _window, cx| {
11524 item.is_dirty = true;
11525 for project_item in &mut item.project_items {
11526 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11527 }
11528 });
11529 cx.run_until_parked();
11530 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11531
11532 // Autosave on focus change, ensuring closing the tab counts as such.
11533 item.update(cx, |item, cx| {
11534 SettingsStore::update_global(cx, |settings, cx| {
11535 settings.update_user_settings(cx, |settings| {
11536 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11537 })
11538 });
11539 item.is_dirty = true;
11540 for project_item in &mut item.project_items {
11541 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11542 }
11543 });
11544
11545 pane.update_in(cx, |pane, window, cx| {
11546 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11547 })
11548 .await
11549 .unwrap();
11550 assert!(!cx.has_pending_prompt());
11551 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11552
11553 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11554 workspace.update_in(cx, |workspace, window, cx| {
11555 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11556 });
11557 item.update_in(cx, |item, window, cx| {
11558 item.project_items[0].update(cx, |item, _| {
11559 item.entry_id = None;
11560 });
11561 item.is_dirty = true;
11562 window.blur();
11563 });
11564 cx.run_until_parked();
11565 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11566
11567 // Ensure autosave is prevented for deleted files also when closing the buffer.
11568 let _close_items = pane.update_in(cx, |pane, window, cx| {
11569 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11570 });
11571 cx.run_until_parked();
11572 assert!(cx.has_pending_prompt());
11573 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11574 }
11575
11576 #[gpui::test]
11577 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11578 init_test(cx);
11579
11580 let fs = FakeFs::new(cx.executor());
11581 let project = Project::test(fs, [], cx).await;
11582 let (workspace, cx) =
11583 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11584
11585 // Create a multibuffer-like item with two child focus handles,
11586 // simulating individual buffer editors within a multibuffer.
11587 let item = cx.new(|cx| {
11588 TestItem::new(cx)
11589 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11590 .with_child_focus_handles(2, cx)
11591 });
11592 workspace.update_in(cx, |workspace, window, cx| {
11593 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11594 });
11595
11596 // Set autosave to OnFocusChange and focus the first child handle,
11597 // simulating the user's cursor being inside one of the multibuffer's excerpts.
11598 item.update_in(cx, |item, window, cx| {
11599 SettingsStore::update_global(cx, |settings, cx| {
11600 settings.update_user_settings(cx, |settings| {
11601 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11602 })
11603 });
11604 item.is_dirty = true;
11605 window.focus(&item.child_focus_handles[0], cx);
11606 });
11607 cx.executor().run_until_parked();
11608 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11609
11610 // Moving focus from one child to another within the same item should
11611 // NOT trigger autosave — focus is still within the item's focus hierarchy.
11612 item.update_in(cx, |item, window, cx| {
11613 window.focus(&item.child_focus_handles[1], cx);
11614 });
11615 cx.executor().run_until_parked();
11616 item.read_with(cx, |item, _| {
11617 assert_eq!(
11618 item.save_count, 0,
11619 "Switching focus between children within the same item should not autosave"
11620 );
11621 });
11622
11623 // Blurring the item saves the file. This is the core regression scenario:
11624 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11625 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11626 // the leaf is always a child focus handle, so `on_blur` never detected
11627 // focus leaving the item.
11628 item.update_in(cx, |_, window, _| window.blur());
11629 cx.executor().run_until_parked();
11630 item.read_with(cx, |item, _| {
11631 assert_eq!(
11632 item.save_count, 1,
11633 "Blurring should trigger autosave when focus was on a child of the item"
11634 );
11635 });
11636
11637 // Deactivating the window should also trigger autosave when a child of
11638 // the multibuffer item currently owns focus.
11639 item.update_in(cx, |item, window, cx| {
11640 item.is_dirty = true;
11641 window.focus(&item.child_focus_handles[0], cx);
11642 });
11643 cx.executor().run_until_parked();
11644 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11645
11646 cx.deactivate_window();
11647 item.read_with(cx, |item, _| {
11648 assert_eq!(
11649 item.save_count, 2,
11650 "Deactivating window should trigger autosave when focus was on a child"
11651 );
11652 });
11653 }
11654
11655 #[gpui::test]
11656 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11657 init_test(cx);
11658
11659 let fs = FakeFs::new(cx.executor());
11660
11661 let project = Project::test(fs, [], cx).await;
11662 let (workspace, cx) =
11663 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11664
11665 let item = cx.new(|cx| {
11666 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11667 });
11668 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11669 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11670 let toolbar_notify_count = Rc::new(RefCell::new(0));
11671
11672 workspace.update_in(cx, |workspace, window, cx| {
11673 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11674 let toolbar_notification_count = toolbar_notify_count.clone();
11675 cx.observe_in(&toolbar, window, move |_, _, _, _| {
11676 *toolbar_notification_count.borrow_mut() += 1
11677 })
11678 .detach();
11679 });
11680
11681 pane.read_with(cx, |pane, _| {
11682 assert!(!pane.can_navigate_backward());
11683 assert!(!pane.can_navigate_forward());
11684 });
11685
11686 item.update_in(cx, |item, _, cx| {
11687 item.set_state("one".to_string(), cx);
11688 });
11689
11690 // Toolbar must be notified to re-render the navigation buttons
11691 assert_eq!(*toolbar_notify_count.borrow(), 1);
11692
11693 pane.read_with(cx, |pane, _| {
11694 assert!(pane.can_navigate_backward());
11695 assert!(!pane.can_navigate_forward());
11696 });
11697
11698 workspace
11699 .update_in(cx, |workspace, window, cx| {
11700 workspace.go_back(pane.downgrade(), window, cx)
11701 })
11702 .await
11703 .unwrap();
11704
11705 assert_eq!(*toolbar_notify_count.borrow(), 2);
11706 pane.read_with(cx, |pane, _| {
11707 assert!(!pane.can_navigate_backward());
11708 assert!(pane.can_navigate_forward());
11709 });
11710 }
11711
11712 /// Tests that the navigation history deduplicates entries for the same item.
11713 ///
11714 /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11715 /// the navigation history deduplicates by keeping only the most recent visit to each item,
11716 /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11717 /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11718 /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11719 ///
11720 /// This behavior prevents the navigation history from growing unnecessarily large and provides
11721 /// a better user experience by eliminating redundant navigation steps when jumping between files.
11722 #[gpui::test]
11723 async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11724 init_test(cx);
11725
11726 let fs = FakeFs::new(cx.executor());
11727 let project = Project::test(fs, [], cx).await;
11728 let (workspace, cx) =
11729 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11730
11731 let item_a = cx.new(|cx| {
11732 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11733 });
11734 let item_b = cx.new(|cx| {
11735 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11736 });
11737 let item_c = cx.new(|cx| {
11738 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11739 });
11740
11741 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11742
11743 workspace.update_in(cx, |workspace, window, cx| {
11744 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11745 workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11746 workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11747 });
11748
11749 workspace.update_in(cx, |workspace, window, cx| {
11750 workspace.activate_item(&item_a, false, false, window, cx);
11751 });
11752 cx.run_until_parked();
11753
11754 workspace.update_in(cx, |workspace, window, cx| {
11755 workspace.activate_item(&item_b, false, false, window, cx);
11756 });
11757 cx.run_until_parked();
11758
11759 workspace.update_in(cx, |workspace, window, cx| {
11760 workspace.activate_item(&item_a, false, false, window, cx);
11761 });
11762 cx.run_until_parked();
11763
11764 workspace.update_in(cx, |workspace, window, cx| {
11765 workspace.activate_item(&item_b, false, false, window, cx);
11766 });
11767 cx.run_until_parked();
11768
11769 workspace.update_in(cx, |workspace, window, cx| {
11770 workspace.activate_item(&item_a, false, false, window, cx);
11771 });
11772 cx.run_until_parked();
11773
11774 workspace.update_in(cx, |workspace, window, cx| {
11775 workspace.activate_item(&item_b, false, false, window, cx);
11776 });
11777 cx.run_until_parked();
11778
11779 workspace.update_in(cx, |workspace, window, cx| {
11780 workspace.activate_item(&item_c, false, false, window, cx);
11781 });
11782 cx.run_until_parked();
11783
11784 let backward_count = pane.read_with(cx, |pane, cx| {
11785 let mut count = 0;
11786 pane.nav_history().for_each_entry(cx, &mut |_, _| {
11787 count += 1;
11788 });
11789 count
11790 });
11791 assert!(
11792 backward_count <= 4,
11793 "Should have at most 4 entries, got {}",
11794 backward_count
11795 );
11796
11797 workspace
11798 .update_in(cx, |workspace, window, cx| {
11799 workspace.go_back(pane.downgrade(), window, cx)
11800 })
11801 .await
11802 .unwrap();
11803
11804 let active_item = workspace.read_with(cx, |workspace, cx| {
11805 workspace.active_item(cx).unwrap().item_id()
11806 });
11807 assert_eq!(
11808 active_item,
11809 item_b.entity_id(),
11810 "After first go_back, should be at item B"
11811 );
11812
11813 workspace
11814 .update_in(cx, |workspace, window, cx| {
11815 workspace.go_back(pane.downgrade(), window, cx)
11816 })
11817 .await
11818 .unwrap();
11819
11820 let active_item = workspace.read_with(cx, |workspace, cx| {
11821 workspace.active_item(cx).unwrap().item_id()
11822 });
11823 assert_eq!(
11824 active_item,
11825 item_a.entity_id(),
11826 "After second go_back, should be at item A"
11827 );
11828
11829 pane.read_with(cx, |pane, _| {
11830 assert!(pane.can_navigate_forward(), "Should be able to go forward");
11831 });
11832 }
11833
11834 #[gpui::test]
11835 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11836 init_test(cx);
11837 let fs = FakeFs::new(cx.executor());
11838 let project = Project::test(fs, [], cx).await;
11839 let (multi_workspace, cx) =
11840 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11841 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11842
11843 workspace.update_in(cx, |workspace, window, cx| {
11844 let first_item = cx.new(|cx| {
11845 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11846 });
11847 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11848 workspace.split_pane(
11849 workspace.active_pane().clone(),
11850 SplitDirection::Right,
11851 window,
11852 cx,
11853 );
11854 workspace.split_pane(
11855 workspace.active_pane().clone(),
11856 SplitDirection::Right,
11857 window,
11858 cx,
11859 );
11860 });
11861
11862 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11863 let panes = workspace.center.panes();
11864 assert!(panes.len() >= 2);
11865 (
11866 panes.first().expect("at least one pane").entity_id(),
11867 panes.last().expect("at least one pane").entity_id(),
11868 )
11869 });
11870
11871 workspace.update_in(cx, |workspace, window, cx| {
11872 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11873 });
11874 workspace.update(cx, |workspace, _| {
11875 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11876 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11877 });
11878
11879 cx.dispatch_action(ActivateLastPane);
11880
11881 workspace.update(cx, |workspace, _| {
11882 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11883 });
11884 }
11885
11886 #[gpui::test]
11887 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11888 init_test(cx);
11889 let fs = FakeFs::new(cx.executor());
11890
11891 let project = Project::test(fs, [], cx).await;
11892 let (workspace, cx) =
11893 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11894
11895 let panel = workspace.update_in(cx, |workspace, window, cx| {
11896 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11897 workspace.add_panel(panel.clone(), window, cx);
11898
11899 workspace
11900 .right_dock()
11901 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11902
11903 panel
11904 });
11905
11906 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11907 pane.update_in(cx, |pane, window, cx| {
11908 let item = cx.new(TestItem::new);
11909 pane.add_item(Box::new(item), true, true, None, window, cx);
11910 });
11911
11912 // Transfer focus from center to panel
11913 workspace.update_in(cx, |workspace, window, cx| {
11914 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11915 });
11916
11917 workspace.update_in(cx, |workspace, window, cx| {
11918 assert!(workspace.right_dock().read(cx).is_open());
11919 assert!(!panel.is_zoomed(window, cx));
11920 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11921 });
11922
11923 // Transfer focus from panel to center
11924 workspace.update_in(cx, |workspace, window, cx| {
11925 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11926 });
11927
11928 workspace.update_in(cx, |workspace, window, cx| {
11929 assert!(workspace.right_dock().read(cx).is_open());
11930 assert!(!panel.is_zoomed(window, cx));
11931 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11932 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11933 });
11934
11935 // Close the dock
11936 workspace.update_in(cx, |workspace, window, cx| {
11937 workspace.toggle_dock(DockPosition::Right, window, cx);
11938 });
11939
11940 workspace.update_in(cx, |workspace, window, cx| {
11941 assert!(!workspace.right_dock().read(cx).is_open());
11942 assert!(!panel.is_zoomed(window, cx));
11943 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11944 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11945 });
11946
11947 // Open the dock
11948 workspace.update_in(cx, |workspace, window, cx| {
11949 workspace.toggle_dock(DockPosition::Right, window, cx);
11950 });
11951
11952 workspace.update_in(cx, |workspace, window, cx| {
11953 assert!(workspace.right_dock().read(cx).is_open());
11954 assert!(!panel.is_zoomed(window, cx));
11955 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11956 });
11957
11958 // Focus and zoom panel
11959 panel.update_in(cx, |panel, window, cx| {
11960 cx.focus_self(window);
11961 panel.set_zoomed(true, window, cx)
11962 });
11963
11964 workspace.update_in(cx, |workspace, window, cx| {
11965 assert!(workspace.right_dock().read(cx).is_open());
11966 assert!(panel.is_zoomed(window, cx));
11967 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11968 });
11969
11970 // Transfer focus to the center closes the dock
11971 workspace.update_in(cx, |workspace, window, cx| {
11972 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11973 });
11974
11975 workspace.update_in(cx, |workspace, window, cx| {
11976 assert!(!workspace.right_dock().read(cx).is_open());
11977 assert!(panel.is_zoomed(window, cx));
11978 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11979 });
11980
11981 // Transferring focus back to the panel keeps it zoomed
11982 workspace.update_in(cx, |workspace, window, cx| {
11983 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11984 });
11985
11986 workspace.update_in(cx, |workspace, window, cx| {
11987 assert!(workspace.right_dock().read(cx).is_open());
11988 assert!(panel.is_zoomed(window, cx));
11989 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11990 });
11991
11992 // Close the dock while it is zoomed
11993 workspace.update_in(cx, |workspace, window, cx| {
11994 workspace.toggle_dock(DockPosition::Right, window, cx)
11995 });
11996
11997 workspace.update_in(cx, |workspace, window, cx| {
11998 assert!(!workspace.right_dock().read(cx).is_open());
11999 assert!(panel.is_zoomed(window, cx));
12000 assert!(workspace.zoomed.is_none());
12001 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12002 });
12003
12004 // Opening the dock, when it's zoomed, retains focus
12005 workspace.update_in(cx, |workspace, window, cx| {
12006 workspace.toggle_dock(DockPosition::Right, window, cx)
12007 });
12008
12009 workspace.update_in(cx, |workspace, window, cx| {
12010 assert!(workspace.right_dock().read(cx).is_open());
12011 assert!(panel.is_zoomed(window, cx));
12012 assert!(workspace.zoomed.is_some());
12013 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12014 });
12015
12016 // Unzoom and close the panel, zoom the active pane.
12017 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
12018 workspace.update_in(cx, |workspace, window, cx| {
12019 workspace.toggle_dock(DockPosition::Right, window, cx)
12020 });
12021 pane.update_in(cx, |pane, window, cx| {
12022 pane.toggle_zoom(&Default::default(), window, cx)
12023 });
12024
12025 // Opening a dock unzooms the pane.
12026 workspace.update_in(cx, |workspace, window, cx| {
12027 workspace.toggle_dock(DockPosition::Right, window, cx)
12028 });
12029 workspace.update_in(cx, |workspace, window, cx| {
12030 let pane = pane.read(cx);
12031 assert!(!pane.is_zoomed());
12032 assert!(!pane.focus_handle(cx).is_focused(window));
12033 assert!(workspace.right_dock().read(cx).is_open());
12034 assert!(workspace.zoomed.is_none());
12035 });
12036 }
12037
12038 #[gpui::test]
12039 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
12040 init_test(cx);
12041 let fs = FakeFs::new(cx.executor());
12042
12043 let project = Project::test(fs, [], cx).await;
12044 let (workspace, cx) =
12045 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12046
12047 let panel = workspace.update_in(cx, |workspace, window, cx| {
12048 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12049 workspace.add_panel(panel.clone(), window, cx);
12050 panel
12051 });
12052
12053 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12054 pane.update_in(cx, |pane, window, cx| {
12055 let item = cx.new(TestItem::new);
12056 pane.add_item(Box::new(item), true, true, None, window, cx);
12057 });
12058
12059 // Enable close_panel_on_toggle
12060 cx.update_global(|store: &mut SettingsStore, cx| {
12061 store.update_user_settings(cx, |settings| {
12062 settings.workspace.close_panel_on_toggle = Some(true);
12063 });
12064 });
12065
12066 // Panel starts closed. Toggling should open and focus it.
12067 workspace.update_in(cx, |workspace, window, cx| {
12068 assert!(!workspace.right_dock().read(cx).is_open());
12069 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12070 });
12071
12072 workspace.update_in(cx, |workspace, window, cx| {
12073 assert!(
12074 workspace.right_dock().read(cx).is_open(),
12075 "Dock should be open after toggling from center"
12076 );
12077 assert!(
12078 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12079 "Panel should be focused after toggling from center"
12080 );
12081 });
12082
12083 // Panel is open and focused. Toggling should close the panel and
12084 // return focus to the center.
12085 workspace.update_in(cx, |workspace, window, cx| {
12086 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12087 });
12088
12089 workspace.update_in(cx, |workspace, window, cx| {
12090 assert!(
12091 !workspace.right_dock().read(cx).is_open(),
12092 "Dock should be closed after toggling from focused panel"
12093 );
12094 assert!(
12095 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12096 "Panel should not be focused after toggling from focused panel"
12097 );
12098 });
12099
12100 // Open the dock and focus something else so the panel is open but not
12101 // focused. Toggling should focus the panel (not close it).
12102 workspace.update_in(cx, |workspace, window, cx| {
12103 workspace
12104 .right_dock()
12105 .update(cx, |dock, cx| dock.set_open(true, window, cx));
12106 window.focus(&pane.read(cx).focus_handle(cx), cx);
12107 });
12108
12109 workspace.update_in(cx, |workspace, window, cx| {
12110 assert!(workspace.right_dock().read(cx).is_open());
12111 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12112 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12113 });
12114
12115 workspace.update_in(cx, |workspace, window, cx| {
12116 assert!(
12117 workspace.right_dock().read(cx).is_open(),
12118 "Dock should remain open when toggling focuses an open-but-unfocused panel"
12119 );
12120 assert!(
12121 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12122 "Panel should be focused after toggling an open-but-unfocused panel"
12123 );
12124 });
12125
12126 // Now disable the setting and verify the original behavior: toggling
12127 // from a focused panel moves focus to center but leaves the dock open.
12128 cx.update_global(|store: &mut SettingsStore, cx| {
12129 store.update_user_settings(cx, |settings| {
12130 settings.workspace.close_panel_on_toggle = Some(false);
12131 });
12132 });
12133
12134 workspace.update_in(cx, |workspace, window, cx| {
12135 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12136 });
12137
12138 workspace.update_in(cx, |workspace, window, cx| {
12139 assert!(
12140 workspace.right_dock().read(cx).is_open(),
12141 "Dock should remain open when setting is disabled"
12142 );
12143 assert!(
12144 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12145 "Panel should not be focused after toggling with setting disabled"
12146 );
12147 });
12148 }
12149
12150 #[gpui::test]
12151 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
12152 init_test(cx);
12153 let fs = FakeFs::new(cx.executor());
12154
12155 let project = Project::test(fs, [], cx).await;
12156 let (workspace, cx) =
12157 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12158
12159 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
12160 workspace.active_pane().clone()
12161 });
12162
12163 // Add an item to the pane so it can be zoomed
12164 workspace.update_in(cx, |workspace, window, cx| {
12165 let item = cx.new(TestItem::new);
12166 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
12167 });
12168
12169 // Initially not zoomed
12170 workspace.update_in(cx, |workspace, _window, cx| {
12171 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
12172 assert!(
12173 workspace.zoomed.is_none(),
12174 "Workspace should track no zoomed pane"
12175 );
12176 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
12177 });
12178
12179 // Zoom In
12180 pane.update_in(cx, |pane, window, cx| {
12181 pane.zoom_in(&crate::ZoomIn, window, cx);
12182 });
12183
12184 workspace.update_in(cx, |workspace, window, cx| {
12185 assert!(
12186 pane.read(cx).is_zoomed(),
12187 "Pane should be zoomed after ZoomIn"
12188 );
12189 assert!(
12190 workspace.zoomed.is_some(),
12191 "Workspace should track the zoomed pane"
12192 );
12193 assert!(
12194 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
12195 "ZoomIn should focus the pane"
12196 );
12197 });
12198
12199 // Zoom In again is a no-op
12200 pane.update_in(cx, |pane, window, cx| {
12201 pane.zoom_in(&crate::ZoomIn, window, cx);
12202 });
12203
12204 workspace.update_in(cx, |workspace, window, cx| {
12205 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
12206 assert!(
12207 workspace.zoomed.is_some(),
12208 "Workspace still tracks zoomed pane"
12209 );
12210 assert!(
12211 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
12212 "Pane remains focused after repeated ZoomIn"
12213 );
12214 });
12215
12216 // Zoom Out
12217 pane.update_in(cx, |pane, window, cx| {
12218 pane.zoom_out(&crate::ZoomOut, window, cx);
12219 });
12220
12221 workspace.update_in(cx, |workspace, _window, cx| {
12222 assert!(
12223 !pane.read(cx).is_zoomed(),
12224 "Pane should unzoom after ZoomOut"
12225 );
12226 assert!(
12227 workspace.zoomed.is_none(),
12228 "Workspace clears zoom tracking after ZoomOut"
12229 );
12230 });
12231
12232 // Zoom Out again is a no-op
12233 pane.update_in(cx, |pane, window, cx| {
12234 pane.zoom_out(&crate::ZoomOut, window, cx);
12235 });
12236
12237 workspace.update_in(cx, |workspace, _window, cx| {
12238 assert!(
12239 !pane.read(cx).is_zoomed(),
12240 "Second ZoomOut keeps pane unzoomed"
12241 );
12242 assert!(
12243 workspace.zoomed.is_none(),
12244 "Workspace remains without zoomed pane"
12245 );
12246 });
12247 }
12248
12249 #[gpui::test]
12250 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
12251 init_test(cx);
12252 let fs = FakeFs::new(cx.executor());
12253
12254 let project = Project::test(fs, [], cx).await;
12255 let (workspace, cx) =
12256 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12257 workspace.update_in(cx, |workspace, window, cx| {
12258 // Open two docks
12259 let left_dock = workspace.dock_at_position(DockPosition::Left);
12260 let right_dock = workspace.dock_at_position(DockPosition::Right);
12261
12262 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12263 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12264
12265 assert!(left_dock.read(cx).is_open());
12266 assert!(right_dock.read(cx).is_open());
12267 });
12268
12269 workspace.update_in(cx, |workspace, window, cx| {
12270 // Toggle all docks - should close both
12271 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12272
12273 let left_dock = workspace.dock_at_position(DockPosition::Left);
12274 let right_dock = workspace.dock_at_position(DockPosition::Right);
12275 assert!(!left_dock.read(cx).is_open());
12276 assert!(!right_dock.read(cx).is_open());
12277 });
12278
12279 workspace.update_in(cx, |workspace, window, cx| {
12280 // Toggle again - should reopen both
12281 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12282
12283 let left_dock = workspace.dock_at_position(DockPosition::Left);
12284 let right_dock = workspace.dock_at_position(DockPosition::Right);
12285 assert!(left_dock.read(cx).is_open());
12286 assert!(right_dock.read(cx).is_open());
12287 });
12288 }
12289
12290 #[gpui::test]
12291 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
12292 init_test(cx);
12293 let fs = FakeFs::new(cx.executor());
12294
12295 let project = Project::test(fs, [], cx).await;
12296 let (workspace, cx) =
12297 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12298 workspace.update_in(cx, |workspace, window, cx| {
12299 // Open two docks
12300 let left_dock = workspace.dock_at_position(DockPosition::Left);
12301 let right_dock = workspace.dock_at_position(DockPosition::Right);
12302
12303 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12304 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12305
12306 assert!(left_dock.read(cx).is_open());
12307 assert!(right_dock.read(cx).is_open());
12308 });
12309
12310 workspace.update_in(cx, |workspace, window, cx| {
12311 // Close them manually
12312 workspace.toggle_dock(DockPosition::Left, window, cx);
12313 workspace.toggle_dock(DockPosition::Right, window, cx);
12314
12315 let left_dock = workspace.dock_at_position(DockPosition::Left);
12316 let right_dock = workspace.dock_at_position(DockPosition::Right);
12317 assert!(!left_dock.read(cx).is_open());
12318 assert!(!right_dock.read(cx).is_open());
12319 });
12320
12321 workspace.update_in(cx, |workspace, window, cx| {
12322 // Toggle all docks - only last closed (right dock) should reopen
12323 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12324
12325 let left_dock = workspace.dock_at_position(DockPosition::Left);
12326 let right_dock = workspace.dock_at_position(DockPosition::Right);
12327 assert!(!left_dock.read(cx).is_open());
12328 assert!(right_dock.read(cx).is_open());
12329 });
12330 }
12331
12332 #[gpui::test]
12333 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
12334 init_test(cx);
12335 let fs = FakeFs::new(cx.executor());
12336 let project = Project::test(fs, [], cx).await;
12337 let (multi_workspace, cx) =
12338 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12339 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12340
12341 // Open two docks (left and right) with one panel each
12342 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12343 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12344 workspace.add_panel(left_panel.clone(), window, cx);
12345
12346 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12347 workspace.add_panel(right_panel.clone(), window, cx);
12348
12349 workspace.toggle_dock(DockPosition::Left, window, cx);
12350 workspace.toggle_dock(DockPosition::Right, window, cx);
12351
12352 // Verify initial state
12353 assert!(
12354 workspace.left_dock().read(cx).is_open(),
12355 "Left dock should be open"
12356 );
12357 assert_eq!(
12358 workspace
12359 .left_dock()
12360 .read(cx)
12361 .visible_panel()
12362 .unwrap()
12363 .panel_id(),
12364 left_panel.panel_id(),
12365 "Left panel should be visible in left dock"
12366 );
12367 assert!(
12368 workspace.right_dock().read(cx).is_open(),
12369 "Right dock should be open"
12370 );
12371 assert_eq!(
12372 workspace
12373 .right_dock()
12374 .read(cx)
12375 .visible_panel()
12376 .unwrap()
12377 .panel_id(),
12378 right_panel.panel_id(),
12379 "Right panel should be visible in right dock"
12380 );
12381 assert!(
12382 !workspace.bottom_dock().read(cx).is_open(),
12383 "Bottom dock should be closed"
12384 );
12385
12386 (left_panel, right_panel)
12387 });
12388
12389 // Focus the left panel and move it to the next position (bottom dock)
12390 workspace.update_in(cx, |workspace, window, cx| {
12391 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12392 assert!(
12393 left_panel.read(cx).focus_handle(cx).is_focused(window),
12394 "Left panel should be focused"
12395 );
12396 });
12397
12398 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12399
12400 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12401 workspace.update(cx, |workspace, cx| {
12402 assert!(
12403 !workspace.left_dock().read(cx).is_open(),
12404 "Left dock should be closed"
12405 );
12406 assert!(
12407 workspace.bottom_dock().read(cx).is_open(),
12408 "Bottom dock should now be open"
12409 );
12410 assert_eq!(
12411 left_panel.read(cx).position,
12412 DockPosition::Bottom,
12413 "Left panel should now be in the bottom dock"
12414 );
12415 assert_eq!(
12416 workspace
12417 .bottom_dock()
12418 .read(cx)
12419 .visible_panel()
12420 .unwrap()
12421 .panel_id(),
12422 left_panel.panel_id(),
12423 "Left panel should be the visible panel in the bottom dock"
12424 );
12425 });
12426
12427 // Toggle all docks off
12428 workspace.update_in(cx, |workspace, window, cx| {
12429 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12430 assert!(
12431 !workspace.left_dock().read(cx).is_open(),
12432 "Left dock should be closed"
12433 );
12434 assert!(
12435 !workspace.right_dock().read(cx).is_open(),
12436 "Right dock should be closed"
12437 );
12438 assert!(
12439 !workspace.bottom_dock().read(cx).is_open(),
12440 "Bottom dock should be closed"
12441 );
12442 });
12443
12444 // Toggle all docks back on and verify positions are restored
12445 workspace.update_in(cx, |workspace, window, cx| {
12446 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12447 assert!(
12448 !workspace.left_dock().read(cx).is_open(),
12449 "Left dock should remain closed"
12450 );
12451 assert!(
12452 workspace.right_dock().read(cx).is_open(),
12453 "Right dock should remain open"
12454 );
12455 assert!(
12456 workspace.bottom_dock().read(cx).is_open(),
12457 "Bottom dock should remain open"
12458 );
12459 assert_eq!(
12460 left_panel.read(cx).position,
12461 DockPosition::Bottom,
12462 "Left panel should remain in the bottom dock"
12463 );
12464 assert_eq!(
12465 right_panel.read(cx).position,
12466 DockPosition::Right,
12467 "Right panel should remain in the right dock"
12468 );
12469 assert_eq!(
12470 workspace
12471 .bottom_dock()
12472 .read(cx)
12473 .visible_panel()
12474 .unwrap()
12475 .panel_id(),
12476 left_panel.panel_id(),
12477 "Left panel should be the visible panel in the right dock"
12478 );
12479 });
12480 }
12481
12482 #[gpui::test]
12483 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12484 init_test(cx);
12485
12486 let fs = FakeFs::new(cx.executor());
12487
12488 let project = Project::test(fs, None, cx).await;
12489 let (workspace, cx) =
12490 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12491
12492 // Let's arrange the panes like this:
12493 //
12494 // +-----------------------+
12495 // | top |
12496 // +------+--------+-------+
12497 // | left | center | right |
12498 // +------+--------+-------+
12499 // | bottom |
12500 // +-----------------------+
12501
12502 let top_item = cx.new(|cx| {
12503 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12504 });
12505 let bottom_item = cx.new(|cx| {
12506 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12507 });
12508 let left_item = cx.new(|cx| {
12509 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12510 });
12511 let right_item = cx.new(|cx| {
12512 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12513 });
12514 let center_item = cx.new(|cx| {
12515 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12516 });
12517
12518 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12519 let top_pane_id = workspace.active_pane().entity_id();
12520 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12521 workspace.split_pane(
12522 workspace.active_pane().clone(),
12523 SplitDirection::Down,
12524 window,
12525 cx,
12526 );
12527 top_pane_id
12528 });
12529 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12530 let bottom_pane_id = workspace.active_pane().entity_id();
12531 workspace.add_item_to_active_pane(
12532 Box::new(bottom_item.clone()),
12533 None,
12534 false,
12535 window,
12536 cx,
12537 );
12538 workspace.split_pane(
12539 workspace.active_pane().clone(),
12540 SplitDirection::Up,
12541 window,
12542 cx,
12543 );
12544 bottom_pane_id
12545 });
12546 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12547 let left_pane_id = workspace.active_pane().entity_id();
12548 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12549 workspace.split_pane(
12550 workspace.active_pane().clone(),
12551 SplitDirection::Right,
12552 window,
12553 cx,
12554 );
12555 left_pane_id
12556 });
12557 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12558 let right_pane_id = workspace.active_pane().entity_id();
12559 workspace.add_item_to_active_pane(
12560 Box::new(right_item.clone()),
12561 None,
12562 false,
12563 window,
12564 cx,
12565 );
12566 workspace.split_pane(
12567 workspace.active_pane().clone(),
12568 SplitDirection::Left,
12569 window,
12570 cx,
12571 );
12572 right_pane_id
12573 });
12574 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12575 let center_pane_id = workspace.active_pane().entity_id();
12576 workspace.add_item_to_active_pane(
12577 Box::new(center_item.clone()),
12578 None,
12579 false,
12580 window,
12581 cx,
12582 );
12583 center_pane_id
12584 });
12585 cx.executor().run_until_parked();
12586
12587 workspace.update_in(cx, |workspace, window, cx| {
12588 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12589
12590 // Join into next from center pane into right
12591 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12592 });
12593
12594 workspace.update_in(cx, |workspace, window, cx| {
12595 let active_pane = workspace.active_pane();
12596 assert_eq!(right_pane_id, active_pane.entity_id());
12597 assert_eq!(2, active_pane.read(cx).items_len());
12598 let item_ids_in_pane =
12599 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12600 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12601 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12602
12603 // Join into next from right pane into bottom
12604 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12605 });
12606
12607 workspace.update_in(cx, |workspace, window, cx| {
12608 let active_pane = workspace.active_pane();
12609 assert_eq!(bottom_pane_id, active_pane.entity_id());
12610 assert_eq!(3, active_pane.read(cx).items_len());
12611 let item_ids_in_pane =
12612 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12613 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12614 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12615 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12616
12617 // Join into next from bottom pane into left
12618 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12619 });
12620
12621 workspace.update_in(cx, |workspace, window, cx| {
12622 let active_pane = workspace.active_pane();
12623 assert_eq!(left_pane_id, active_pane.entity_id());
12624 assert_eq!(4, active_pane.read(cx).items_len());
12625 let item_ids_in_pane =
12626 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12627 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12628 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12629 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12630 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12631
12632 // Join into next from left pane into top
12633 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12634 });
12635
12636 workspace.update_in(cx, |workspace, window, cx| {
12637 let active_pane = workspace.active_pane();
12638 assert_eq!(top_pane_id, active_pane.entity_id());
12639 assert_eq!(5, active_pane.read(cx).items_len());
12640 let item_ids_in_pane =
12641 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12642 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12643 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12644 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12645 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12646 assert!(item_ids_in_pane.contains(&top_item.item_id()));
12647
12648 // Single pane left: no-op
12649 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12650 });
12651
12652 workspace.update(cx, |workspace, _cx| {
12653 let active_pane = workspace.active_pane();
12654 assert_eq!(top_pane_id, active_pane.entity_id());
12655 });
12656 }
12657
12658 fn add_an_item_to_active_pane(
12659 cx: &mut VisualTestContext,
12660 workspace: &Entity<Workspace>,
12661 item_id: u64,
12662 ) -> Entity<TestItem> {
12663 let item = cx.new(|cx| {
12664 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12665 item_id,
12666 "item{item_id}.txt",
12667 cx,
12668 )])
12669 });
12670 workspace.update_in(cx, |workspace, window, cx| {
12671 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12672 });
12673 item
12674 }
12675
12676 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12677 workspace.update_in(cx, |workspace, window, cx| {
12678 workspace.split_pane(
12679 workspace.active_pane().clone(),
12680 SplitDirection::Right,
12681 window,
12682 cx,
12683 )
12684 })
12685 }
12686
12687 #[gpui::test]
12688 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12689 init_test(cx);
12690 let fs = FakeFs::new(cx.executor());
12691 let project = Project::test(fs, None, cx).await;
12692 let (workspace, cx) =
12693 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12694
12695 add_an_item_to_active_pane(cx, &workspace, 1);
12696 split_pane(cx, &workspace);
12697 add_an_item_to_active_pane(cx, &workspace, 2);
12698 split_pane(cx, &workspace); // empty pane
12699 split_pane(cx, &workspace);
12700 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12701
12702 cx.executor().run_until_parked();
12703
12704 workspace.update(cx, |workspace, cx| {
12705 let num_panes = workspace.panes().len();
12706 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12707 let active_item = workspace
12708 .active_pane()
12709 .read(cx)
12710 .active_item()
12711 .expect("item is in focus");
12712
12713 assert_eq!(num_panes, 4);
12714 assert_eq!(num_items_in_current_pane, 1);
12715 assert_eq!(active_item.item_id(), last_item.item_id());
12716 });
12717
12718 workspace.update_in(cx, |workspace, window, cx| {
12719 workspace.join_all_panes(window, cx);
12720 });
12721
12722 workspace.update(cx, |workspace, cx| {
12723 let num_panes = workspace.panes().len();
12724 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12725 let active_item = workspace
12726 .active_pane()
12727 .read(cx)
12728 .active_item()
12729 .expect("item is in focus");
12730
12731 assert_eq!(num_panes, 1);
12732 assert_eq!(num_items_in_current_pane, 3);
12733 assert_eq!(active_item.item_id(), last_item.item_id());
12734 });
12735 }
12736
12737 #[gpui::test]
12738 async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12739 init_test(cx);
12740 let fs = FakeFs::new(cx.executor());
12741
12742 let project = Project::test(fs, [], cx).await;
12743 let (multi_workspace, cx) =
12744 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12745 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12746
12747 workspace.update(cx, |workspace, _cx| {
12748 workspace.set_random_database_id();
12749 });
12750
12751 workspace.update_in(cx, |workspace, window, cx| {
12752 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12753 workspace.add_panel(panel.clone(), window, cx);
12754 workspace.toggle_dock(DockPosition::Right, window, cx);
12755
12756 let right_dock = workspace.right_dock().clone();
12757 right_dock.update(cx, |dock, cx| {
12758 dock.set_panel_size_state(
12759 &panel,
12760 dock::PanelSizeState {
12761 size: None,
12762 flex: Some(1.0),
12763 },
12764 cx,
12765 );
12766 });
12767 });
12768
12769 workspace.update_in(cx, |workspace, window, cx| {
12770 let item = cx.new(|cx| {
12771 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12772 });
12773 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12774 workspace.bounds.size.width = px(1920.);
12775
12776 let dock = workspace.right_dock().read(cx);
12777 let initial_width = workspace
12778 .dock_size(&dock, window, cx)
12779 .expect("flexible dock should have an initial width");
12780
12781 assert_eq!(initial_width, px(960.));
12782 });
12783
12784 workspace.update_in(cx, |workspace, window, cx| {
12785 workspace.split_pane(
12786 workspace.active_pane().clone(),
12787 SplitDirection::Right,
12788 window,
12789 cx,
12790 );
12791
12792 let center_column_count = workspace.center.full_height_column_count();
12793 assert_eq!(center_column_count, 2);
12794
12795 let dock = workspace.right_dock().read(cx);
12796 assert_eq!(workspace.dock_size(&dock, window, cx).unwrap(), px(640.));
12797
12798 workspace.bounds.size.width = px(2400.);
12799
12800 let dock = workspace.right_dock().read(cx);
12801 assert_eq!(workspace.dock_size(&dock, window, cx).unwrap(), px(800.));
12802 });
12803 }
12804
12805 #[gpui::test]
12806 async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12807 init_test(cx);
12808 let fs = FakeFs::new(cx.executor());
12809
12810 // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12811 {
12812 let project = Project::test(fs.clone(), [], cx).await;
12813 let (multi_workspace, cx) =
12814 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12815 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12816
12817 workspace.update(cx, |workspace, _cx| {
12818 workspace.set_random_database_id();
12819 workspace.bounds.size.width = px(800.);
12820 });
12821
12822 let panel = workspace.update_in(cx, |workspace, window, cx| {
12823 let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12824 workspace.add_panel(panel.clone(), window, cx);
12825 workspace.toggle_dock(DockPosition::Left, window, cx);
12826 panel
12827 });
12828
12829 workspace.update_in(cx, |workspace, window, cx| {
12830 workspace.resize_left_dock(px(350.), window, cx);
12831 });
12832
12833 cx.run_until_parked();
12834
12835 let persisted = workspace.read_with(cx, |workspace, cx| {
12836 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12837 });
12838 assert_eq!(
12839 persisted.and_then(|s| s.size),
12840 Some(px(350.)),
12841 "fixed-width panel size should be persisted to KVP"
12842 );
12843
12844 // Remove the panel and re-add a fresh instance with the same key.
12845 // The new instance should have its size state restored from KVP.
12846 workspace.update_in(cx, |workspace, window, cx| {
12847 workspace.remove_panel(&panel, window, cx);
12848 });
12849
12850 workspace.update_in(cx, |workspace, window, cx| {
12851 let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12852 workspace.add_panel(new_panel, window, cx);
12853
12854 let left_dock = workspace.left_dock().read(cx);
12855 let size_state = left_dock
12856 .panel::<TestPanel>()
12857 .and_then(|p| left_dock.stored_panel_size_state(&p));
12858 assert_eq!(
12859 size_state.and_then(|s| s.size),
12860 Some(px(350.)),
12861 "re-added fixed-width panel should restore persisted size from KVP"
12862 );
12863 });
12864 }
12865
12866 // Flexible panel: both pixel size and ratio are persisted and restored.
12867 {
12868 let project = Project::test(fs.clone(), [], cx).await;
12869 let (multi_workspace, cx) =
12870 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12871 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12872
12873 workspace.update(cx, |workspace, _cx| {
12874 workspace.set_random_database_id();
12875 workspace.bounds.size.width = px(800.);
12876 });
12877
12878 let panel = workspace.update_in(cx, |workspace, window, cx| {
12879 let item = cx.new(|cx| {
12880 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12881 });
12882 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12883
12884 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12885 workspace.add_panel(panel.clone(), window, cx);
12886 workspace.toggle_dock(DockPosition::Right, window, cx);
12887 panel
12888 });
12889
12890 workspace.update_in(cx, |workspace, window, cx| {
12891 workspace.resize_right_dock(px(300.), window, cx);
12892 });
12893
12894 cx.run_until_parked();
12895
12896 let persisted = workspace
12897 .read_with(cx, |workspace, cx| {
12898 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12899 })
12900 .expect("flexible panel state should be persisted to KVP");
12901 assert_eq!(
12902 persisted.size, None,
12903 "flexible panel should not persist a redundant pixel size"
12904 );
12905 let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12906
12907 // Remove the panel and re-add: both size and ratio should be restored.
12908 workspace.update_in(cx, |workspace, window, cx| {
12909 workspace.remove_panel(&panel, window, cx);
12910 });
12911
12912 workspace.update_in(cx, |workspace, window, cx| {
12913 let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12914 workspace.add_panel(new_panel, window, cx);
12915
12916 let right_dock = workspace.right_dock().read(cx);
12917 let size_state = right_dock
12918 .panel::<TestPanel>()
12919 .and_then(|p| right_dock.stored_panel_size_state(&p))
12920 .expect("re-added flexible panel should have restored size state from KVP");
12921 assert_eq!(
12922 size_state.size, None,
12923 "re-added flexible panel should not have a persisted pixel size"
12924 );
12925 assert_eq!(
12926 size_state.flex,
12927 Some(original_ratio),
12928 "re-added flexible panel should restore persisted flex"
12929 );
12930 });
12931 }
12932 }
12933
12934 #[gpui::test]
12935 async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12936 init_test(cx);
12937 let fs = FakeFs::new(cx.executor());
12938
12939 let project = Project::test(fs, [], cx).await;
12940 let (multi_workspace, cx) =
12941 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12942 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12943
12944 workspace.update(cx, |workspace, _cx| {
12945 workspace.bounds.size.width = px(900.);
12946 });
12947
12948 // Step 1: Add a tab to the center pane then open a flexible panel in the left
12949 // dock. With one full-width center pane the default ratio is 0.5, so the panel
12950 // and the center pane each take half the workspace width.
12951 workspace.update_in(cx, |workspace, window, cx| {
12952 let item = cx.new(|cx| {
12953 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12954 });
12955 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12956
12957 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12958 workspace.add_panel(panel, window, cx);
12959 workspace.toggle_dock(DockPosition::Left, window, cx);
12960
12961 let left_dock = workspace.left_dock().read(cx);
12962 let left_width = workspace
12963 .dock_size(&left_dock, window, cx)
12964 .expect("left dock should have an active panel");
12965
12966 assert_eq!(
12967 left_width,
12968 workspace.bounds.size.width / 2.,
12969 "flexible left panel should split evenly with the center pane"
12970 );
12971 });
12972
12973 // Step 2: Split the center pane left/right. The flexible panel is treated as one
12974 // average center column, so with two center columns it should take one third of
12975 // the workspace width.
12976 workspace.update_in(cx, |workspace, window, cx| {
12977 workspace.split_pane(
12978 workspace.active_pane().clone(),
12979 SplitDirection::Right,
12980 window,
12981 cx,
12982 );
12983
12984 let left_dock = workspace.left_dock().read(cx);
12985 let left_width = workspace
12986 .dock_size(&left_dock, window, cx)
12987 .expect("left dock should still have an active panel after horizontal split");
12988
12989 assert_eq!(
12990 left_width,
12991 workspace.bounds.size.width / 3.,
12992 "flexible left panel width should match the average center column width"
12993 );
12994 });
12995
12996 // Step 3: Split the active center pane vertically (top/bottom). Vertical splits do
12997 // not change the number of center columns, so the flexible panel width stays the same.
12998 workspace.update_in(cx, |workspace, window, cx| {
12999 workspace.split_pane(
13000 workspace.active_pane().clone(),
13001 SplitDirection::Down,
13002 window,
13003 cx,
13004 );
13005
13006 let left_dock = workspace.left_dock().read(cx);
13007 let left_width = workspace
13008 .dock_size(&left_dock, window, cx)
13009 .expect("left dock should still have an active panel after vertical split");
13010
13011 assert_eq!(
13012 left_width,
13013 workspace.bounds.size.width / 3.,
13014 "flexible left panel width should still match the average center column width"
13015 );
13016 });
13017
13018 // Step 4: Open a fixed-width panel in the right dock. The right dock's default
13019 // size reduces the available width, so the flexible left panel keeps matching one
13020 // average center column within the remaining space.
13021 workspace.update_in(cx, |workspace, window, cx| {
13022 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
13023 workspace.add_panel(panel, window, cx);
13024 workspace.toggle_dock(DockPosition::Right, window, cx);
13025
13026 let right_dock = workspace.right_dock().read(cx);
13027 let right_width = workspace
13028 .dock_size(&right_dock, window, cx)
13029 .expect("right dock should have an active panel");
13030
13031 let left_dock = workspace.left_dock().read(cx);
13032 let left_width = workspace
13033 .dock_size(&left_dock, window, cx)
13034 .expect("left dock should still have an active panel");
13035
13036 let available_width = workspace.bounds.size.width - right_width;
13037 assert_eq!(
13038 left_width,
13039 available_width / 3.,
13040 "flexible left panel should keep matching one average center column"
13041 );
13042 });
13043
13044 // Step 5: Toggle the right dock's panel to flexible. Now both docks use
13045 // column-equivalent flex sizing and the workspace width is divided among
13046 // left-flex, two center columns, and right-flex.
13047 workspace.update_in(cx, |workspace, window, cx| {
13048 let right_dock = workspace.right_dock().clone();
13049 let right_panel = right_dock
13050 .read(cx)
13051 .visible_panel()
13052 .expect("right dock should have a visible panel")
13053 .clone();
13054 workspace.toggle_dock_panel_flexible_size(
13055 &right_dock,
13056 right_panel.as_ref(),
13057 window,
13058 cx,
13059 );
13060
13061 let right_dock = right_dock.read(cx);
13062 let right_panel = right_dock
13063 .visible_panel()
13064 .expect("right dock should still have a visible panel");
13065 assert!(
13066 right_panel.has_flexible_size(window, cx),
13067 "right panel should now be flexible"
13068 );
13069
13070 let right_size_state = right_dock
13071 .stored_panel_size_state(right_panel.as_ref())
13072 .expect("right panel should have a stored size state after toggling");
13073 let right_flex = right_size_state
13074 .flex
13075 .expect("right panel should have a flex value after toggling");
13076
13077 let left_dock = workspace.left_dock().read(cx);
13078 let left_width = workspace
13079 .dock_size(&left_dock, window, cx)
13080 .expect("left dock should still have an active panel");
13081 let right_width = workspace
13082 .dock_size(&right_dock, window, cx)
13083 .expect("right dock should still have an active panel");
13084
13085 let left_flex = workspace
13086 .default_dock_flex(DockPosition::Left)
13087 .expect("left dock should have a default flex");
13088 let center_column_count = workspace.center.full_height_column_count() as f32;
13089
13090 let total_flex = left_flex + center_column_count + right_flex;
13091 let expected_left = left_flex / total_flex * workspace.bounds.size.width;
13092 let expected_right = right_flex / total_flex * workspace.bounds.size.width;
13093 assert_eq!(
13094 left_width, expected_left,
13095 "flexible left panel should share workspace width via flex ratios"
13096 );
13097 assert_eq!(
13098 right_width, expected_right,
13099 "flexible right panel should share workspace width via flex ratios"
13100 );
13101 });
13102 }
13103
13104 struct TestModal(FocusHandle);
13105
13106 impl TestModal {
13107 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
13108 Self(cx.focus_handle())
13109 }
13110 }
13111
13112 impl EventEmitter<DismissEvent> for TestModal {}
13113
13114 impl Focusable for TestModal {
13115 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13116 self.0.clone()
13117 }
13118 }
13119
13120 impl ModalView for TestModal {}
13121
13122 impl Render for TestModal {
13123 fn render(
13124 &mut self,
13125 _window: &mut Window,
13126 _cx: &mut Context<TestModal>,
13127 ) -> impl IntoElement {
13128 div().track_focus(&self.0)
13129 }
13130 }
13131
13132 #[gpui::test]
13133 async fn test_panels(cx: &mut gpui::TestAppContext) {
13134 init_test(cx);
13135 let fs = FakeFs::new(cx.executor());
13136
13137 let project = Project::test(fs, [], cx).await;
13138 let (multi_workspace, cx) =
13139 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13140 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13141
13142 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
13143 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
13144 workspace.add_panel(panel_1.clone(), window, cx);
13145 workspace.toggle_dock(DockPosition::Left, window, cx);
13146 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
13147 workspace.add_panel(panel_2.clone(), window, cx);
13148 workspace.toggle_dock(DockPosition::Right, window, cx);
13149
13150 let left_dock = workspace.left_dock();
13151 assert_eq!(
13152 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13153 panel_1.panel_id()
13154 );
13155 assert_eq!(
13156 workspace.dock_size(&left_dock.read(cx), window, cx),
13157 Some(px(300.))
13158 );
13159
13160 workspace.resize_left_dock(px(1337.), window, cx);
13161 assert_eq!(
13162 workspace
13163 .right_dock()
13164 .read(cx)
13165 .visible_panel()
13166 .unwrap()
13167 .panel_id(),
13168 panel_2.panel_id(),
13169 );
13170
13171 (panel_1, panel_2)
13172 });
13173
13174 // Move panel_1 to the right
13175 panel_1.update_in(cx, |panel_1, window, cx| {
13176 panel_1.set_position(DockPosition::Right, window, cx)
13177 });
13178
13179 workspace.update_in(cx, |workspace, window, cx| {
13180 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
13181 // Since it was the only panel on the left, the left dock should now be closed.
13182 assert!(!workspace.left_dock().read(cx).is_open());
13183 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
13184 let right_dock = workspace.right_dock();
13185 assert_eq!(
13186 right_dock.read(cx).visible_panel().unwrap().panel_id(),
13187 panel_1.panel_id()
13188 );
13189 assert_eq!(
13190 right_dock
13191 .read(cx)
13192 .active_panel_size()
13193 .unwrap()
13194 .size
13195 .unwrap(),
13196 px(1337.)
13197 );
13198
13199 // Now we move panel_2 to the left
13200 panel_2.set_position(DockPosition::Left, window, cx);
13201 });
13202
13203 workspace.update(cx, |workspace, cx| {
13204 // Since panel_2 was not visible on the right, we don't open the left dock.
13205 assert!(!workspace.left_dock().read(cx).is_open());
13206 // And the right dock is unaffected in its displaying of panel_1
13207 assert!(workspace.right_dock().read(cx).is_open());
13208 assert_eq!(
13209 workspace
13210 .right_dock()
13211 .read(cx)
13212 .visible_panel()
13213 .unwrap()
13214 .panel_id(),
13215 panel_1.panel_id(),
13216 );
13217 });
13218
13219 // Move panel_1 back to the left
13220 panel_1.update_in(cx, |panel_1, window, cx| {
13221 panel_1.set_position(DockPosition::Left, window, cx)
13222 });
13223
13224 workspace.update_in(cx, |workspace, window, cx| {
13225 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
13226 let left_dock = workspace.left_dock();
13227 assert!(left_dock.read(cx).is_open());
13228 assert_eq!(
13229 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13230 panel_1.panel_id()
13231 );
13232 assert_eq!(
13233 workspace.dock_size(&left_dock.read(cx), window, cx),
13234 Some(px(1337.))
13235 );
13236 // And the right dock should be closed as it no longer has any panels.
13237 assert!(!workspace.right_dock().read(cx).is_open());
13238
13239 // Now we move panel_1 to the bottom
13240 panel_1.set_position(DockPosition::Bottom, window, cx);
13241 });
13242
13243 workspace.update_in(cx, |workspace, window, cx| {
13244 // Since panel_1 was visible on the left, we close the left dock.
13245 assert!(!workspace.left_dock().read(cx).is_open());
13246 // The bottom dock is sized based on the panel's default size,
13247 // since the panel orientation changed from vertical to horizontal.
13248 let bottom_dock = workspace.bottom_dock();
13249 assert_eq!(
13250 workspace.dock_size(&bottom_dock.read(cx), window, cx),
13251 Some(px(300.))
13252 );
13253 // Close bottom dock and move panel_1 back to the left.
13254 bottom_dock.update(cx, |bottom_dock, cx| {
13255 bottom_dock.set_open(false, window, cx)
13256 });
13257 panel_1.set_position(DockPosition::Left, window, cx);
13258 });
13259
13260 // Emit activated event on panel 1
13261 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
13262
13263 // Now the left dock is open and panel_1 is active and focused.
13264 workspace.update_in(cx, |workspace, window, cx| {
13265 let left_dock = workspace.left_dock();
13266 assert!(left_dock.read(cx).is_open());
13267 assert_eq!(
13268 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13269 panel_1.panel_id(),
13270 );
13271 assert!(panel_1.focus_handle(cx).is_focused(window));
13272 });
13273
13274 // Emit closed event on panel 2, which is not active
13275 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13276
13277 // Wo don't close the left dock, because panel_2 wasn't the active panel
13278 workspace.update(cx, |workspace, cx| {
13279 let left_dock = workspace.left_dock();
13280 assert!(left_dock.read(cx).is_open());
13281 assert_eq!(
13282 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13283 panel_1.panel_id(),
13284 );
13285 });
13286
13287 // Emitting a ZoomIn event shows the panel as zoomed.
13288 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
13289 workspace.read_with(cx, |workspace, _| {
13290 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13291 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
13292 });
13293
13294 // Move panel to another dock while it is zoomed
13295 panel_1.update_in(cx, |panel, window, cx| {
13296 panel.set_position(DockPosition::Right, window, cx)
13297 });
13298 workspace.read_with(cx, |workspace, _| {
13299 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13300
13301 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13302 });
13303
13304 // This is a helper for getting a:
13305 // - valid focus on an element,
13306 // - that isn't a part of the panes and panels system of the Workspace,
13307 // - and doesn't trigger the 'on_focus_lost' API.
13308 let focus_other_view = {
13309 let workspace = workspace.clone();
13310 move |cx: &mut VisualTestContext| {
13311 workspace.update_in(cx, |workspace, window, cx| {
13312 if workspace.active_modal::<TestModal>(cx).is_some() {
13313 workspace.toggle_modal(window, cx, TestModal::new);
13314 workspace.toggle_modal(window, cx, TestModal::new);
13315 } else {
13316 workspace.toggle_modal(window, cx, TestModal::new);
13317 }
13318 })
13319 }
13320 };
13321
13322 // If focus is transferred to another view that's not a panel or another pane, we still show
13323 // the panel as zoomed.
13324 focus_other_view(cx);
13325 workspace.read_with(cx, |workspace, _| {
13326 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13327 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13328 });
13329
13330 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13331 workspace.update_in(cx, |_workspace, window, cx| {
13332 cx.focus_self(window);
13333 });
13334 workspace.read_with(cx, |workspace, _| {
13335 assert_eq!(workspace.zoomed, None);
13336 assert_eq!(workspace.zoomed_position, None);
13337 });
13338
13339 // If focus is transferred again to another view that's not a panel or a pane, we won't
13340 // show the panel as zoomed because it wasn't zoomed before.
13341 focus_other_view(cx);
13342 workspace.read_with(cx, |workspace, _| {
13343 assert_eq!(workspace.zoomed, None);
13344 assert_eq!(workspace.zoomed_position, None);
13345 });
13346
13347 // When the panel is activated, it is zoomed again.
13348 cx.dispatch_action(ToggleRightDock);
13349 workspace.read_with(cx, |workspace, _| {
13350 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13351 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13352 });
13353
13354 // Emitting a ZoomOut event unzooms the panel.
13355 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13356 workspace.read_with(cx, |workspace, _| {
13357 assert_eq!(workspace.zoomed, None);
13358 assert_eq!(workspace.zoomed_position, None);
13359 });
13360
13361 // Emit closed event on panel 1, which is active
13362 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13363
13364 // Now the left dock is closed, because panel_1 was the active panel
13365 workspace.update(cx, |workspace, cx| {
13366 let right_dock = workspace.right_dock();
13367 assert!(!right_dock.read(cx).is_open());
13368 });
13369 }
13370
13371 #[gpui::test]
13372 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13373 init_test(cx);
13374
13375 let fs = FakeFs::new(cx.background_executor.clone());
13376 let project = Project::test(fs, [], cx).await;
13377 let (workspace, cx) =
13378 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13379 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13380
13381 let dirty_regular_buffer = cx.new(|cx| {
13382 TestItem::new(cx)
13383 .with_dirty(true)
13384 .with_label("1.txt")
13385 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13386 });
13387 let dirty_regular_buffer_2 = cx.new(|cx| {
13388 TestItem::new(cx)
13389 .with_dirty(true)
13390 .with_label("2.txt")
13391 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13392 });
13393 let dirty_multi_buffer_with_both = cx.new(|cx| {
13394 TestItem::new(cx)
13395 .with_dirty(true)
13396 .with_buffer_kind(ItemBufferKind::Multibuffer)
13397 .with_label("Fake Project Search")
13398 .with_project_items(&[
13399 dirty_regular_buffer.read(cx).project_items[0].clone(),
13400 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13401 ])
13402 });
13403 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13404 workspace.update_in(cx, |workspace, window, cx| {
13405 workspace.add_item(
13406 pane.clone(),
13407 Box::new(dirty_regular_buffer.clone()),
13408 None,
13409 false,
13410 false,
13411 window,
13412 cx,
13413 );
13414 workspace.add_item(
13415 pane.clone(),
13416 Box::new(dirty_regular_buffer_2.clone()),
13417 None,
13418 false,
13419 false,
13420 window,
13421 cx,
13422 );
13423 workspace.add_item(
13424 pane.clone(),
13425 Box::new(dirty_multi_buffer_with_both.clone()),
13426 None,
13427 false,
13428 false,
13429 window,
13430 cx,
13431 );
13432 });
13433
13434 pane.update_in(cx, |pane, window, cx| {
13435 pane.activate_item(2, true, true, window, cx);
13436 assert_eq!(
13437 pane.active_item().unwrap().item_id(),
13438 multi_buffer_with_both_files_id,
13439 "Should select the multi buffer in the pane"
13440 );
13441 });
13442 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13443 pane.close_other_items(
13444 &CloseOtherItems {
13445 save_intent: Some(SaveIntent::Save),
13446 close_pinned: true,
13447 },
13448 None,
13449 window,
13450 cx,
13451 )
13452 });
13453 cx.background_executor.run_until_parked();
13454 assert!(!cx.has_pending_prompt());
13455 close_all_but_multi_buffer_task
13456 .await
13457 .expect("Closing all buffers but the multi buffer failed");
13458 pane.update(cx, |pane, cx| {
13459 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13460 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13461 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13462 assert_eq!(pane.items_len(), 1);
13463 assert_eq!(
13464 pane.active_item().unwrap().item_id(),
13465 multi_buffer_with_both_files_id,
13466 "Should have only the multi buffer left in the pane"
13467 );
13468 assert!(
13469 dirty_multi_buffer_with_both.read(cx).is_dirty,
13470 "The multi buffer containing the unsaved buffer should still be dirty"
13471 );
13472 });
13473
13474 dirty_regular_buffer.update(cx, |buffer, cx| {
13475 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13476 });
13477
13478 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13479 pane.close_active_item(
13480 &CloseActiveItem {
13481 save_intent: Some(SaveIntent::Close),
13482 close_pinned: false,
13483 },
13484 window,
13485 cx,
13486 )
13487 });
13488 cx.background_executor.run_until_parked();
13489 assert!(
13490 cx.has_pending_prompt(),
13491 "Dirty multi buffer should prompt a save dialog"
13492 );
13493 cx.simulate_prompt_answer("Save");
13494 cx.background_executor.run_until_parked();
13495 close_multi_buffer_task
13496 .await
13497 .expect("Closing the multi buffer failed");
13498 pane.update(cx, |pane, cx| {
13499 assert_eq!(
13500 dirty_multi_buffer_with_both.read(cx).save_count,
13501 1,
13502 "Multi buffer item should get be saved"
13503 );
13504 // Test impl does not save inner items, so we do not assert them
13505 assert_eq!(
13506 pane.items_len(),
13507 0,
13508 "No more items should be left in the pane"
13509 );
13510 assert!(pane.active_item().is_none());
13511 });
13512 }
13513
13514 #[gpui::test]
13515 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13516 cx: &mut TestAppContext,
13517 ) {
13518 init_test(cx);
13519
13520 let fs = FakeFs::new(cx.background_executor.clone());
13521 let project = Project::test(fs, [], cx).await;
13522 let (workspace, cx) =
13523 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13524 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13525
13526 let dirty_regular_buffer = cx.new(|cx| {
13527 TestItem::new(cx)
13528 .with_dirty(true)
13529 .with_label("1.txt")
13530 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13531 });
13532 let dirty_regular_buffer_2 = cx.new(|cx| {
13533 TestItem::new(cx)
13534 .with_dirty(true)
13535 .with_label("2.txt")
13536 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13537 });
13538 let clear_regular_buffer = cx.new(|cx| {
13539 TestItem::new(cx)
13540 .with_label("3.txt")
13541 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13542 });
13543
13544 let dirty_multi_buffer_with_both = cx.new(|cx| {
13545 TestItem::new(cx)
13546 .with_dirty(true)
13547 .with_buffer_kind(ItemBufferKind::Multibuffer)
13548 .with_label("Fake Project Search")
13549 .with_project_items(&[
13550 dirty_regular_buffer.read(cx).project_items[0].clone(),
13551 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13552 clear_regular_buffer.read(cx).project_items[0].clone(),
13553 ])
13554 });
13555 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13556 workspace.update_in(cx, |workspace, window, cx| {
13557 workspace.add_item(
13558 pane.clone(),
13559 Box::new(dirty_regular_buffer.clone()),
13560 None,
13561 false,
13562 false,
13563 window,
13564 cx,
13565 );
13566 workspace.add_item(
13567 pane.clone(),
13568 Box::new(dirty_multi_buffer_with_both.clone()),
13569 None,
13570 false,
13571 false,
13572 window,
13573 cx,
13574 );
13575 });
13576
13577 pane.update_in(cx, |pane, window, cx| {
13578 pane.activate_item(1, true, true, window, cx);
13579 assert_eq!(
13580 pane.active_item().unwrap().item_id(),
13581 multi_buffer_with_both_files_id,
13582 "Should select the multi buffer in the pane"
13583 );
13584 });
13585 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13586 pane.close_active_item(
13587 &CloseActiveItem {
13588 save_intent: None,
13589 close_pinned: false,
13590 },
13591 window,
13592 cx,
13593 )
13594 });
13595 cx.background_executor.run_until_parked();
13596 assert!(
13597 cx.has_pending_prompt(),
13598 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13599 );
13600 }
13601
13602 /// Tests that when `close_on_file_delete` is enabled, files are automatically
13603 /// closed when they are deleted from disk.
13604 #[gpui::test]
13605 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13606 init_test(cx);
13607
13608 // Enable the close_on_disk_deletion setting
13609 cx.update_global(|store: &mut SettingsStore, cx| {
13610 store.update_user_settings(cx, |settings| {
13611 settings.workspace.close_on_file_delete = Some(true);
13612 });
13613 });
13614
13615 let fs = FakeFs::new(cx.background_executor.clone());
13616 let project = Project::test(fs, [], cx).await;
13617 let (workspace, cx) =
13618 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13619 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13620
13621 // Create a test item that simulates a file
13622 let item = cx.new(|cx| {
13623 TestItem::new(cx)
13624 .with_label("test.txt")
13625 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13626 });
13627
13628 // Add item to workspace
13629 workspace.update_in(cx, |workspace, window, cx| {
13630 workspace.add_item(
13631 pane.clone(),
13632 Box::new(item.clone()),
13633 None,
13634 false,
13635 false,
13636 window,
13637 cx,
13638 );
13639 });
13640
13641 // Verify the item is in the pane
13642 pane.read_with(cx, |pane, _| {
13643 assert_eq!(pane.items().count(), 1);
13644 });
13645
13646 // Simulate file deletion by setting the item's deleted state
13647 item.update(cx, |item, _| {
13648 item.set_has_deleted_file(true);
13649 });
13650
13651 // Emit UpdateTab event to trigger the close behavior
13652 cx.run_until_parked();
13653 item.update(cx, |_, cx| {
13654 cx.emit(ItemEvent::UpdateTab);
13655 });
13656
13657 // Allow the close operation to complete
13658 cx.run_until_parked();
13659
13660 // Verify the item was automatically closed
13661 pane.read_with(cx, |pane, _| {
13662 assert_eq!(
13663 pane.items().count(),
13664 0,
13665 "Item should be automatically closed when file is deleted"
13666 );
13667 });
13668 }
13669
13670 /// Tests that when `close_on_file_delete` is disabled (default), files remain
13671 /// open with a strikethrough when they are deleted from disk.
13672 #[gpui::test]
13673 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13674 init_test(cx);
13675
13676 // Ensure close_on_disk_deletion is disabled (default)
13677 cx.update_global(|store: &mut SettingsStore, cx| {
13678 store.update_user_settings(cx, |settings| {
13679 settings.workspace.close_on_file_delete = Some(false);
13680 });
13681 });
13682
13683 let fs = FakeFs::new(cx.background_executor.clone());
13684 let project = Project::test(fs, [], cx).await;
13685 let (workspace, cx) =
13686 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13687 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13688
13689 // Create a test item that simulates a file
13690 let item = cx.new(|cx| {
13691 TestItem::new(cx)
13692 .with_label("test.txt")
13693 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13694 });
13695
13696 // Add item to workspace
13697 workspace.update_in(cx, |workspace, window, cx| {
13698 workspace.add_item(
13699 pane.clone(),
13700 Box::new(item.clone()),
13701 None,
13702 false,
13703 false,
13704 window,
13705 cx,
13706 );
13707 });
13708
13709 // Verify the item is in the pane
13710 pane.read_with(cx, |pane, _| {
13711 assert_eq!(pane.items().count(), 1);
13712 });
13713
13714 // Simulate file deletion
13715 item.update(cx, |item, _| {
13716 item.set_has_deleted_file(true);
13717 });
13718
13719 // Emit UpdateTab event
13720 cx.run_until_parked();
13721 item.update(cx, |_, cx| {
13722 cx.emit(ItemEvent::UpdateTab);
13723 });
13724
13725 // Allow any potential close operation to complete
13726 cx.run_until_parked();
13727
13728 // Verify the item remains open (with strikethrough)
13729 pane.read_with(cx, |pane, _| {
13730 assert_eq!(
13731 pane.items().count(),
13732 1,
13733 "Item should remain open when close_on_disk_deletion is disabled"
13734 );
13735 });
13736
13737 // Verify the item shows as deleted
13738 item.read_with(cx, |item, _| {
13739 assert!(
13740 item.has_deleted_file,
13741 "Item should be marked as having deleted file"
13742 );
13743 });
13744 }
13745
13746 /// Tests that dirty files are not automatically closed when deleted from disk,
13747 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13748 /// unsaved changes without being prompted.
13749 #[gpui::test]
13750 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13751 init_test(cx);
13752
13753 // Enable the close_on_file_delete setting
13754 cx.update_global(|store: &mut SettingsStore, cx| {
13755 store.update_user_settings(cx, |settings| {
13756 settings.workspace.close_on_file_delete = Some(true);
13757 });
13758 });
13759
13760 let fs = FakeFs::new(cx.background_executor.clone());
13761 let project = Project::test(fs, [], cx).await;
13762 let (workspace, cx) =
13763 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13764 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13765
13766 // Create a dirty test item
13767 let item = cx.new(|cx| {
13768 TestItem::new(cx)
13769 .with_dirty(true)
13770 .with_label("test.txt")
13771 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13772 });
13773
13774 // Add item to workspace
13775 workspace.update_in(cx, |workspace, window, cx| {
13776 workspace.add_item(
13777 pane.clone(),
13778 Box::new(item.clone()),
13779 None,
13780 false,
13781 false,
13782 window,
13783 cx,
13784 );
13785 });
13786
13787 // Simulate file deletion
13788 item.update(cx, |item, _| {
13789 item.set_has_deleted_file(true);
13790 });
13791
13792 // Emit UpdateTab event to trigger the close behavior
13793 cx.run_until_parked();
13794 item.update(cx, |_, cx| {
13795 cx.emit(ItemEvent::UpdateTab);
13796 });
13797
13798 // Allow any potential close operation to complete
13799 cx.run_until_parked();
13800
13801 // Verify the item remains open (dirty files are not auto-closed)
13802 pane.read_with(cx, |pane, _| {
13803 assert_eq!(
13804 pane.items().count(),
13805 1,
13806 "Dirty items should not be automatically closed even when file is deleted"
13807 );
13808 });
13809
13810 // Verify the item is marked as deleted and still dirty
13811 item.read_with(cx, |item, _| {
13812 assert!(
13813 item.has_deleted_file,
13814 "Item should be marked as having deleted file"
13815 );
13816 assert!(item.is_dirty, "Item should still be dirty");
13817 });
13818 }
13819
13820 /// Tests that navigation history is cleaned up when files are auto-closed
13821 /// due to deletion from disk.
13822 #[gpui::test]
13823 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13824 init_test(cx);
13825
13826 // Enable the close_on_file_delete setting
13827 cx.update_global(|store: &mut SettingsStore, cx| {
13828 store.update_user_settings(cx, |settings| {
13829 settings.workspace.close_on_file_delete = Some(true);
13830 });
13831 });
13832
13833 let fs = FakeFs::new(cx.background_executor.clone());
13834 let project = Project::test(fs, [], cx).await;
13835 let (workspace, cx) =
13836 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13837 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13838
13839 // Create test items
13840 let item1 = cx.new(|cx| {
13841 TestItem::new(cx)
13842 .with_label("test1.txt")
13843 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13844 });
13845 let item1_id = item1.item_id();
13846
13847 let item2 = cx.new(|cx| {
13848 TestItem::new(cx)
13849 .with_label("test2.txt")
13850 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13851 });
13852
13853 // Add items to workspace
13854 workspace.update_in(cx, |workspace, window, cx| {
13855 workspace.add_item(
13856 pane.clone(),
13857 Box::new(item1.clone()),
13858 None,
13859 false,
13860 false,
13861 window,
13862 cx,
13863 );
13864 workspace.add_item(
13865 pane.clone(),
13866 Box::new(item2.clone()),
13867 None,
13868 false,
13869 false,
13870 window,
13871 cx,
13872 );
13873 });
13874
13875 // Activate item1 to ensure it gets navigation entries
13876 pane.update_in(cx, |pane, window, cx| {
13877 pane.activate_item(0, true, true, window, cx);
13878 });
13879
13880 // Switch to item2 and back to create navigation history
13881 pane.update_in(cx, |pane, window, cx| {
13882 pane.activate_item(1, true, true, window, cx);
13883 });
13884 cx.run_until_parked();
13885
13886 pane.update_in(cx, |pane, window, cx| {
13887 pane.activate_item(0, true, true, window, cx);
13888 });
13889 cx.run_until_parked();
13890
13891 // Simulate file deletion for item1
13892 item1.update(cx, |item, _| {
13893 item.set_has_deleted_file(true);
13894 });
13895
13896 // Emit UpdateTab event to trigger the close behavior
13897 item1.update(cx, |_, cx| {
13898 cx.emit(ItemEvent::UpdateTab);
13899 });
13900 cx.run_until_parked();
13901
13902 // Verify item1 was closed
13903 pane.read_with(cx, |pane, _| {
13904 assert_eq!(
13905 pane.items().count(),
13906 1,
13907 "Should have 1 item remaining after auto-close"
13908 );
13909 });
13910
13911 // Check navigation history after close
13912 let has_item = pane.read_with(cx, |pane, cx| {
13913 let mut has_item = false;
13914 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13915 if entry.item.id() == item1_id {
13916 has_item = true;
13917 }
13918 });
13919 has_item
13920 });
13921
13922 assert!(
13923 !has_item,
13924 "Navigation history should not contain closed item entries"
13925 );
13926 }
13927
13928 #[gpui::test]
13929 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13930 cx: &mut TestAppContext,
13931 ) {
13932 init_test(cx);
13933
13934 let fs = FakeFs::new(cx.background_executor.clone());
13935 let project = Project::test(fs, [], cx).await;
13936 let (workspace, cx) =
13937 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13938 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13939
13940 let dirty_regular_buffer = cx.new(|cx| {
13941 TestItem::new(cx)
13942 .with_dirty(true)
13943 .with_label("1.txt")
13944 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13945 });
13946 let dirty_regular_buffer_2 = cx.new(|cx| {
13947 TestItem::new(cx)
13948 .with_dirty(true)
13949 .with_label("2.txt")
13950 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13951 });
13952 let clear_regular_buffer = cx.new(|cx| {
13953 TestItem::new(cx)
13954 .with_label("3.txt")
13955 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13956 });
13957
13958 let dirty_multi_buffer = cx.new(|cx| {
13959 TestItem::new(cx)
13960 .with_dirty(true)
13961 .with_buffer_kind(ItemBufferKind::Multibuffer)
13962 .with_label("Fake Project Search")
13963 .with_project_items(&[
13964 dirty_regular_buffer.read(cx).project_items[0].clone(),
13965 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13966 clear_regular_buffer.read(cx).project_items[0].clone(),
13967 ])
13968 });
13969 workspace.update_in(cx, |workspace, window, cx| {
13970 workspace.add_item(
13971 pane.clone(),
13972 Box::new(dirty_regular_buffer.clone()),
13973 None,
13974 false,
13975 false,
13976 window,
13977 cx,
13978 );
13979 workspace.add_item(
13980 pane.clone(),
13981 Box::new(dirty_regular_buffer_2.clone()),
13982 None,
13983 false,
13984 false,
13985 window,
13986 cx,
13987 );
13988 workspace.add_item(
13989 pane.clone(),
13990 Box::new(dirty_multi_buffer.clone()),
13991 None,
13992 false,
13993 false,
13994 window,
13995 cx,
13996 );
13997 });
13998
13999 pane.update_in(cx, |pane, window, cx| {
14000 pane.activate_item(2, true, true, window, cx);
14001 assert_eq!(
14002 pane.active_item().unwrap().item_id(),
14003 dirty_multi_buffer.item_id(),
14004 "Should select the multi buffer in the pane"
14005 );
14006 });
14007 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
14008 pane.close_active_item(
14009 &CloseActiveItem {
14010 save_intent: None,
14011 close_pinned: false,
14012 },
14013 window,
14014 cx,
14015 )
14016 });
14017 cx.background_executor.run_until_parked();
14018 assert!(
14019 !cx.has_pending_prompt(),
14020 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
14021 );
14022 close_multi_buffer_task
14023 .await
14024 .expect("Closing multi buffer failed");
14025 pane.update(cx, |pane, cx| {
14026 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
14027 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
14028 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
14029 assert_eq!(
14030 pane.items()
14031 .map(|item| item.item_id())
14032 .sorted()
14033 .collect::<Vec<_>>(),
14034 vec![
14035 dirty_regular_buffer.item_id(),
14036 dirty_regular_buffer_2.item_id(),
14037 ],
14038 "Should have no multi buffer left in the pane"
14039 );
14040 assert!(dirty_regular_buffer.read(cx).is_dirty);
14041 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
14042 });
14043 }
14044
14045 #[gpui::test]
14046 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
14047 init_test(cx);
14048 let fs = FakeFs::new(cx.executor());
14049 let project = Project::test(fs, [], cx).await;
14050 let (multi_workspace, cx) =
14051 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14052 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14053
14054 // Add a new panel to the right dock, opening the dock and setting the
14055 // focus to the new panel.
14056 let panel = workspace.update_in(cx, |workspace, window, cx| {
14057 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14058 workspace.add_panel(panel.clone(), window, cx);
14059
14060 workspace
14061 .right_dock()
14062 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14063
14064 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14065
14066 panel
14067 });
14068
14069 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
14070 // panel to the next valid position which, in this case, is the left
14071 // dock.
14072 cx.dispatch_action(MoveFocusedPanelToNextPosition);
14073 workspace.update(cx, |workspace, cx| {
14074 assert!(workspace.left_dock().read(cx).is_open());
14075 assert_eq!(panel.read(cx).position, DockPosition::Left);
14076 });
14077
14078 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
14079 // panel to the next valid position which, in this case, is the bottom
14080 // dock.
14081 cx.dispatch_action(MoveFocusedPanelToNextPosition);
14082 workspace.update(cx, |workspace, cx| {
14083 assert!(workspace.bottom_dock().read(cx).is_open());
14084 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
14085 });
14086
14087 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
14088 // around moving the panel to its initial position, the right dock.
14089 cx.dispatch_action(MoveFocusedPanelToNextPosition);
14090 workspace.update(cx, |workspace, cx| {
14091 assert!(workspace.right_dock().read(cx).is_open());
14092 assert_eq!(panel.read(cx).position, DockPosition::Right);
14093 });
14094
14095 // Remove focus from the panel, ensuring that, if the panel is not
14096 // focused, the `MoveFocusedPanelToNextPosition` action does not update
14097 // the panel's position, so the panel is still in the right dock.
14098 workspace.update_in(cx, |workspace, window, cx| {
14099 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14100 });
14101
14102 cx.dispatch_action(MoveFocusedPanelToNextPosition);
14103 workspace.update(cx, |workspace, cx| {
14104 assert!(workspace.right_dock().read(cx).is_open());
14105 assert_eq!(panel.read(cx).position, DockPosition::Right);
14106 });
14107 }
14108
14109 #[gpui::test]
14110 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
14111 init_test(cx);
14112
14113 let fs = FakeFs::new(cx.executor());
14114 let project = Project::test(fs, [], cx).await;
14115 let (workspace, cx) =
14116 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14117
14118 let item_1 = cx.new(|cx| {
14119 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
14120 });
14121 workspace.update_in(cx, |workspace, window, cx| {
14122 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
14123 workspace.move_item_to_pane_in_direction(
14124 &MoveItemToPaneInDirection {
14125 direction: SplitDirection::Right,
14126 focus: true,
14127 clone: false,
14128 },
14129 window,
14130 cx,
14131 );
14132 workspace.move_item_to_pane_at_index(
14133 &MoveItemToPane {
14134 destination: 3,
14135 focus: true,
14136 clone: false,
14137 },
14138 window,
14139 cx,
14140 );
14141
14142 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
14143 assert_eq!(
14144 pane_items_paths(&workspace.active_pane, cx),
14145 vec!["first.txt".to_string()],
14146 "Single item was not moved anywhere"
14147 );
14148 });
14149
14150 let item_2 = cx.new(|cx| {
14151 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
14152 });
14153 workspace.update_in(cx, |workspace, window, cx| {
14154 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
14155 assert_eq!(
14156 pane_items_paths(&workspace.panes[0], cx),
14157 vec!["first.txt".to_string(), "second.txt".to_string()],
14158 );
14159 workspace.move_item_to_pane_in_direction(
14160 &MoveItemToPaneInDirection {
14161 direction: SplitDirection::Right,
14162 focus: true,
14163 clone: false,
14164 },
14165 window,
14166 cx,
14167 );
14168
14169 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
14170 assert_eq!(
14171 pane_items_paths(&workspace.panes[0], cx),
14172 vec!["first.txt".to_string()],
14173 "After moving, one item should be left in the original pane"
14174 );
14175 assert_eq!(
14176 pane_items_paths(&workspace.panes[1], cx),
14177 vec!["second.txt".to_string()],
14178 "New item should have been moved to the new pane"
14179 );
14180 });
14181
14182 let item_3 = cx.new(|cx| {
14183 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
14184 });
14185 workspace.update_in(cx, |workspace, window, cx| {
14186 let original_pane = workspace.panes[0].clone();
14187 workspace.set_active_pane(&original_pane, window, cx);
14188 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
14189 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
14190 assert_eq!(
14191 pane_items_paths(&workspace.active_pane, cx),
14192 vec!["first.txt".to_string(), "third.txt".to_string()],
14193 "New pane should be ready to move one item out"
14194 );
14195
14196 workspace.move_item_to_pane_at_index(
14197 &MoveItemToPane {
14198 destination: 3,
14199 focus: true,
14200 clone: false,
14201 },
14202 window,
14203 cx,
14204 );
14205 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
14206 assert_eq!(
14207 pane_items_paths(&workspace.active_pane, cx),
14208 vec!["first.txt".to_string()],
14209 "After moving, one item should be left in the original pane"
14210 );
14211 assert_eq!(
14212 pane_items_paths(&workspace.panes[1], cx),
14213 vec!["second.txt".to_string()],
14214 "Previously created pane should be unchanged"
14215 );
14216 assert_eq!(
14217 pane_items_paths(&workspace.panes[2], cx),
14218 vec!["third.txt".to_string()],
14219 "New item should have been moved to the new pane"
14220 );
14221 });
14222 }
14223
14224 #[gpui::test]
14225 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
14226 init_test(cx);
14227
14228 let fs = FakeFs::new(cx.executor());
14229 let project = Project::test(fs, [], cx).await;
14230 let (workspace, cx) =
14231 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14232
14233 let item_1 = cx.new(|cx| {
14234 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
14235 });
14236 workspace.update_in(cx, |workspace, window, cx| {
14237 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
14238 workspace.move_item_to_pane_in_direction(
14239 &MoveItemToPaneInDirection {
14240 direction: SplitDirection::Right,
14241 focus: true,
14242 clone: true,
14243 },
14244 window,
14245 cx,
14246 );
14247 });
14248 cx.run_until_parked();
14249 workspace.update_in(cx, |workspace, window, cx| {
14250 workspace.move_item_to_pane_at_index(
14251 &MoveItemToPane {
14252 destination: 3,
14253 focus: true,
14254 clone: true,
14255 },
14256 window,
14257 cx,
14258 );
14259 });
14260 cx.run_until_parked();
14261
14262 workspace.update(cx, |workspace, cx| {
14263 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
14264 for pane in workspace.panes() {
14265 assert_eq!(
14266 pane_items_paths(pane, cx),
14267 vec!["first.txt".to_string()],
14268 "Single item exists in all panes"
14269 );
14270 }
14271 });
14272
14273 // verify that the active pane has been updated after waiting for the
14274 // pane focus event to fire and resolve
14275 workspace.read_with(cx, |workspace, _app| {
14276 assert_eq!(
14277 workspace.active_pane(),
14278 &workspace.panes[2],
14279 "The third pane should be the active one: {:?}",
14280 workspace.panes
14281 );
14282 })
14283 }
14284
14285 #[gpui::test]
14286 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
14287 init_test(cx);
14288
14289 let fs = FakeFs::new(cx.executor());
14290 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
14291
14292 let project = Project::test(fs, ["root".as_ref()], cx).await;
14293 let (workspace, cx) =
14294 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14295
14296 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14297 // Add item to pane A with project path
14298 let item_a = cx.new(|cx| {
14299 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14300 });
14301 workspace.update_in(cx, |workspace, window, cx| {
14302 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
14303 });
14304
14305 // Split to create pane B
14306 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
14307 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
14308 });
14309
14310 // Add item with SAME project path to pane B, and pin it
14311 let item_b = cx.new(|cx| {
14312 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14313 });
14314 pane_b.update_in(cx, |pane, window, cx| {
14315 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14316 pane.set_pinned_count(1);
14317 });
14318
14319 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14320 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14321
14322 // close_pinned: false should only close the unpinned copy
14323 workspace.update_in(cx, |workspace, window, cx| {
14324 workspace.close_item_in_all_panes(
14325 &CloseItemInAllPanes {
14326 save_intent: Some(SaveIntent::Close),
14327 close_pinned: false,
14328 },
14329 window,
14330 cx,
14331 )
14332 });
14333 cx.executor().run_until_parked();
14334
14335 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14336 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14337 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14338 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14339
14340 // Split again, seeing as closing the previous item also closed its
14341 // pane, so only pane remains, which does not allow us to properly test
14342 // that both items close when `close_pinned: true`.
14343 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14344 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14345 });
14346
14347 // Add an item with the same project path to pane C so that
14348 // close_item_in_all_panes can determine what to close across all panes
14349 // (it reads the active item from the active pane, and split_pane
14350 // creates an empty pane).
14351 let item_c = cx.new(|cx| {
14352 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14353 });
14354 pane_c.update_in(cx, |pane, window, cx| {
14355 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14356 });
14357
14358 // close_pinned: true should close the pinned copy too
14359 workspace.update_in(cx, |workspace, window, cx| {
14360 let panes_count = workspace.panes().len();
14361 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14362
14363 workspace.close_item_in_all_panes(
14364 &CloseItemInAllPanes {
14365 save_intent: Some(SaveIntent::Close),
14366 close_pinned: true,
14367 },
14368 window,
14369 cx,
14370 )
14371 });
14372 cx.executor().run_until_parked();
14373
14374 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14375 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14376 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14377 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14378 }
14379
14380 mod register_project_item_tests {
14381
14382 use super::*;
14383
14384 // View
14385 struct TestPngItemView {
14386 focus_handle: FocusHandle,
14387 }
14388 // Model
14389 struct TestPngItem {}
14390
14391 impl project::ProjectItem for TestPngItem {
14392 fn try_open(
14393 _project: &Entity<Project>,
14394 path: &ProjectPath,
14395 cx: &mut App,
14396 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14397 if path.path.extension().unwrap() == "png" {
14398 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14399 } else {
14400 None
14401 }
14402 }
14403
14404 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14405 None
14406 }
14407
14408 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14409 None
14410 }
14411
14412 fn is_dirty(&self) -> bool {
14413 false
14414 }
14415 }
14416
14417 impl Item for TestPngItemView {
14418 type Event = ();
14419 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14420 "".into()
14421 }
14422 }
14423 impl EventEmitter<()> for TestPngItemView {}
14424 impl Focusable for TestPngItemView {
14425 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14426 self.focus_handle.clone()
14427 }
14428 }
14429
14430 impl Render for TestPngItemView {
14431 fn render(
14432 &mut self,
14433 _window: &mut Window,
14434 _cx: &mut Context<Self>,
14435 ) -> impl IntoElement {
14436 Empty
14437 }
14438 }
14439
14440 impl ProjectItem for TestPngItemView {
14441 type Item = TestPngItem;
14442
14443 fn for_project_item(
14444 _project: Entity<Project>,
14445 _pane: Option<&Pane>,
14446 _item: Entity<Self::Item>,
14447 _: &mut Window,
14448 cx: &mut Context<Self>,
14449 ) -> Self
14450 where
14451 Self: Sized,
14452 {
14453 Self {
14454 focus_handle: cx.focus_handle(),
14455 }
14456 }
14457 }
14458
14459 // View
14460 struct TestIpynbItemView {
14461 focus_handle: FocusHandle,
14462 }
14463 // Model
14464 struct TestIpynbItem {}
14465
14466 impl project::ProjectItem for TestIpynbItem {
14467 fn try_open(
14468 _project: &Entity<Project>,
14469 path: &ProjectPath,
14470 cx: &mut App,
14471 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14472 if path.path.extension().unwrap() == "ipynb" {
14473 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14474 } else {
14475 None
14476 }
14477 }
14478
14479 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14480 None
14481 }
14482
14483 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14484 None
14485 }
14486
14487 fn is_dirty(&self) -> bool {
14488 false
14489 }
14490 }
14491
14492 impl Item for TestIpynbItemView {
14493 type Event = ();
14494 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14495 "".into()
14496 }
14497 }
14498 impl EventEmitter<()> for TestIpynbItemView {}
14499 impl Focusable for TestIpynbItemView {
14500 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14501 self.focus_handle.clone()
14502 }
14503 }
14504
14505 impl Render for TestIpynbItemView {
14506 fn render(
14507 &mut self,
14508 _window: &mut Window,
14509 _cx: &mut Context<Self>,
14510 ) -> impl IntoElement {
14511 Empty
14512 }
14513 }
14514
14515 impl ProjectItem for TestIpynbItemView {
14516 type Item = TestIpynbItem;
14517
14518 fn for_project_item(
14519 _project: Entity<Project>,
14520 _pane: Option<&Pane>,
14521 _item: Entity<Self::Item>,
14522 _: &mut Window,
14523 cx: &mut Context<Self>,
14524 ) -> Self
14525 where
14526 Self: Sized,
14527 {
14528 Self {
14529 focus_handle: cx.focus_handle(),
14530 }
14531 }
14532 }
14533
14534 struct TestAlternatePngItemView {
14535 focus_handle: FocusHandle,
14536 }
14537
14538 impl Item for TestAlternatePngItemView {
14539 type Event = ();
14540 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14541 "".into()
14542 }
14543 }
14544
14545 impl EventEmitter<()> for TestAlternatePngItemView {}
14546 impl Focusable for TestAlternatePngItemView {
14547 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14548 self.focus_handle.clone()
14549 }
14550 }
14551
14552 impl Render for TestAlternatePngItemView {
14553 fn render(
14554 &mut self,
14555 _window: &mut Window,
14556 _cx: &mut Context<Self>,
14557 ) -> impl IntoElement {
14558 Empty
14559 }
14560 }
14561
14562 impl ProjectItem for TestAlternatePngItemView {
14563 type Item = TestPngItem;
14564
14565 fn for_project_item(
14566 _project: Entity<Project>,
14567 _pane: Option<&Pane>,
14568 _item: Entity<Self::Item>,
14569 _: &mut Window,
14570 cx: &mut Context<Self>,
14571 ) -> Self
14572 where
14573 Self: Sized,
14574 {
14575 Self {
14576 focus_handle: cx.focus_handle(),
14577 }
14578 }
14579 }
14580
14581 #[gpui::test]
14582 async fn test_register_project_item(cx: &mut TestAppContext) {
14583 init_test(cx);
14584
14585 cx.update(|cx| {
14586 register_project_item::<TestPngItemView>(cx);
14587 register_project_item::<TestIpynbItemView>(cx);
14588 });
14589
14590 let fs = FakeFs::new(cx.executor());
14591 fs.insert_tree(
14592 "/root1",
14593 json!({
14594 "one.png": "BINARYDATAHERE",
14595 "two.ipynb": "{ totally a notebook }",
14596 "three.txt": "editing text, sure why not?"
14597 }),
14598 )
14599 .await;
14600
14601 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14602 let (workspace, cx) =
14603 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14604
14605 let worktree_id = project.update(cx, |project, cx| {
14606 project.worktrees(cx).next().unwrap().read(cx).id()
14607 });
14608
14609 let handle = workspace
14610 .update_in(cx, |workspace, window, cx| {
14611 let project_path = (worktree_id, rel_path("one.png"));
14612 workspace.open_path(project_path, None, true, window, cx)
14613 })
14614 .await
14615 .unwrap();
14616
14617 // Now we can check if the handle we got back errored or not
14618 assert_eq!(
14619 handle.to_any_view().entity_type(),
14620 TypeId::of::<TestPngItemView>()
14621 );
14622
14623 let handle = workspace
14624 .update_in(cx, |workspace, window, cx| {
14625 let project_path = (worktree_id, rel_path("two.ipynb"));
14626 workspace.open_path(project_path, None, true, window, cx)
14627 })
14628 .await
14629 .unwrap();
14630
14631 assert_eq!(
14632 handle.to_any_view().entity_type(),
14633 TypeId::of::<TestIpynbItemView>()
14634 );
14635
14636 let handle = workspace
14637 .update_in(cx, |workspace, window, cx| {
14638 let project_path = (worktree_id, rel_path("three.txt"));
14639 workspace.open_path(project_path, None, true, window, cx)
14640 })
14641 .await;
14642 assert!(handle.is_err());
14643 }
14644
14645 #[gpui::test]
14646 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14647 init_test(cx);
14648
14649 cx.update(|cx| {
14650 register_project_item::<TestPngItemView>(cx);
14651 register_project_item::<TestAlternatePngItemView>(cx);
14652 });
14653
14654 let fs = FakeFs::new(cx.executor());
14655 fs.insert_tree(
14656 "/root1",
14657 json!({
14658 "one.png": "BINARYDATAHERE",
14659 "two.ipynb": "{ totally a notebook }",
14660 "three.txt": "editing text, sure why not?"
14661 }),
14662 )
14663 .await;
14664 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14665 let (workspace, cx) =
14666 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14667 let worktree_id = project.update(cx, |project, cx| {
14668 project.worktrees(cx).next().unwrap().read(cx).id()
14669 });
14670
14671 let handle = workspace
14672 .update_in(cx, |workspace, window, cx| {
14673 let project_path = (worktree_id, rel_path("one.png"));
14674 workspace.open_path(project_path, None, true, window, cx)
14675 })
14676 .await
14677 .unwrap();
14678
14679 // This _must_ be the second item registered
14680 assert_eq!(
14681 handle.to_any_view().entity_type(),
14682 TypeId::of::<TestAlternatePngItemView>()
14683 );
14684
14685 let handle = workspace
14686 .update_in(cx, |workspace, window, cx| {
14687 let project_path = (worktree_id, rel_path("three.txt"));
14688 workspace.open_path(project_path, None, true, window, cx)
14689 })
14690 .await;
14691 assert!(handle.is_err());
14692 }
14693 }
14694
14695 #[gpui::test]
14696 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14697 init_test(cx);
14698
14699 let fs = FakeFs::new(cx.executor());
14700 let project = Project::test(fs, [], cx).await;
14701 let (workspace, _cx) =
14702 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14703
14704 // Test with status bar shown (default)
14705 workspace.read_with(cx, |workspace, cx| {
14706 let visible = workspace.status_bar_visible(cx);
14707 assert!(visible, "Status bar should be visible by default");
14708 });
14709
14710 // Test with status bar hidden
14711 cx.update_global(|store: &mut SettingsStore, cx| {
14712 store.update_user_settings(cx, |settings| {
14713 settings.status_bar.get_or_insert_default().show = Some(false);
14714 });
14715 });
14716
14717 workspace.read_with(cx, |workspace, cx| {
14718 let visible = workspace.status_bar_visible(cx);
14719 assert!(!visible, "Status bar should be hidden when show is false");
14720 });
14721
14722 // Test with status bar shown explicitly
14723 cx.update_global(|store: &mut SettingsStore, cx| {
14724 store.update_user_settings(cx, |settings| {
14725 settings.status_bar.get_or_insert_default().show = Some(true);
14726 });
14727 });
14728
14729 workspace.read_with(cx, |workspace, cx| {
14730 let visible = workspace.status_bar_visible(cx);
14731 assert!(visible, "Status bar should be visible when show is true");
14732 });
14733 }
14734
14735 #[gpui::test]
14736 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14737 init_test(cx);
14738
14739 let fs = FakeFs::new(cx.executor());
14740 let project = Project::test(fs, [], cx).await;
14741 let (multi_workspace, cx) =
14742 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14743 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14744 let panel = workspace.update_in(cx, |workspace, window, cx| {
14745 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14746 workspace.add_panel(panel.clone(), window, cx);
14747
14748 workspace
14749 .right_dock()
14750 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14751
14752 panel
14753 });
14754
14755 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14756 let item_a = cx.new(TestItem::new);
14757 let item_b = cx.new(TestItem::new);
14758 let item_a_id = item_a.entity_id();
14759 let item_b_id = item_b.entity_id();
14760
14761 pane.update_in(cx, |pane, window, cx| {
14762 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14763 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14764 });
14765
14766 pane.read_with(cx, |pane, _| {
14767 assert_eq!(pane.items_len(), 2);
14768 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14769 });
14770
14771 workspace.update_in(cx, |workspace, window, cx| {
14772 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14773 });
14774
14775 workspace.update_in(cx, |_, window, cx| {
14776 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14777 });
14778
14779 // Assert that the `pane::CloseActiveItem` action is handled at the
14780 // workspace level when one of the dock panels is focused and, in that
14781 // case, the center pane's active item is closed but the focus is not
14782 // moved.
14783 cx.dispatch_action(pane::CloseActiveItem::default());
14784 cx.run_until_parked();
14785
14786 pane.read_with(cx, |pane, _| {
14787 assert_eq!(pane.items_len(), 1);
14788 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14789 });
14790
14791 workspace.update_in(cx, |workspace, window, cx| {
14792 assert!(workspace.right_dock().read(cx).is_open());
14793 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14794 });
14795 }
14796
14797 #[gpui::test]
14798 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14799 init_test(cx);
14800 let fs = FakeFs::new(cx.executor());
14801
14802 let project_a = Project::test(fs.clone(), [], cx).await;
14803 let project_b = Project::test(fs, [], cx).await;
14804
14805 let multi_workspace_handle =
14806 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14807 cx.run_until_parked();
14808
14809 multi_workspace_handle
14810 .update(cx, |mw, _window, cx| {
14811 mw.open_sidebar(cx);
14812 })
14813 .unwrap();
14814
14815 let workspace_a = multi_workspace_handle
14816 .read_with(cx, |mw, _| mw.workspace().clone())
14817 .unwrap();
14818
14819 let _workspace_b = multi_workspace_handle
14820 .update(cx, |mw, window, cx| {
14821 mw.test_add_workspace(project_b, window, cx)
14822 })
14823 .unwrap();
14824
14825 // Switch to workspace A
14826 multi_workspace_handle
14827 .update(cx, |mw, window, cx| {
14828 let workspace = mw.workspaces().next().unwrap().clone();
14829 mw.activate(workspace, window, cx);
14830 })
14831 .unwrap();
14832
14833 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14834
14835 // Add a panel to workspace A's right dock and open the dock
14836 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14837 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14838 workspace.add_panel(panel.clone(), window, cx);
14839 workspace
14840 .right_dock()
14841 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14842 panel
14843 });
14844
14845 // Focus the panel through the workspace (matching existing test pattern)
14846 workspace_a.update_in(cx, |workspace, window, cx| {
14847 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14848 });
14849
14850 // Zoom the panel
14851 panel.update_in(cx, |panel, window, cx| {
14852 panel.set_zoomed(true, window, cx);
14853 });
14854
14855 // Verify the panel is zoomed and the dock is open
14856 workspace_a.update_in(cx, |workspace, window, cx| {
14857 assert!(
14858 workspace.right_dock().read(cx).is_open(),
14859 "dock should be open before switch"
14860 );
14861 assert!(
14862 panel.is_zoomed(window, cx),
14863 "panel should be zoomed before switch"
14864 );
14865 assert!(
14866 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14867 "panel should be focused before switch"
14868 );
14869 });
14870
14871 // Switch to workspace B
14872 multi_workspace_handle
14873 .update(cx, |mw, window, cx| {
14874 let workspace = mw.workspaces().nth(1).unwrap().clone();
14875 mw.activate(workspace, window, cx);
14876 })
14877 .unwrap();
14878 cx.run_until_parked();
14879
14880 // Switch back to workspace A
14881 multi_workspace_handle
14882 .update(cx, |mw, window, cx| {
14883 let workspace = mw.workspaces().next().unwrap().clone();
14884 mw.activate(workspace, window, cx);
14885 })
14886 .unwrap();
14887 cx.run_until_parked();
14888
14889 // Verify the panel is still zoomed and the dock is still open
14890 workspace_a.update_in(cx, |workspace, window, cx| {
14891 assert!(
14892 workspace.right_dock().read(cx).is_open(),
14893 "dock should still be open after switching back"
14894 );
14895 assert!(
14896 panel.is_zoomed(window, cx),
14897 "panel should still be zoomed after switching back"
14898 );
14899 });
14900 }
14901
14902 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14903 pane.read(cx)
14904 .items()
14905 .flat_map(|item| {
14906 item.project_paths(cx)
14907 .into_iter()
14908 .map(|path| path.path.display(PathStyle::local()).into_owned())
14909 })
14910 .collect()
14911 }
14912
14913 pub fn init_test(cx: &mut TestAppContext) {
14914 cx.update(|cx| {
14915 let settings_store = SettingsStore::test(cx);
14916 cx.set_global(settings_store);
14917 cx.set_global(db::AppDatabase::test_new());
14918 theme_settings::init(theme::LoadThemes::JustBase, cx);
14919 });
14920 }
14921
14922 #[gpui::test]
14923 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14924 use settings::{ThemeName, ThemeSelection};
14925 use theme::SystemAppearance;
14926 use zed_actions::theme::ToggleMode;
14927
14928 init_test(cx);
14929
14930 let fs = FakeFs::new(cx.executor());
14931 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14932
14933 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14934 .await;
14935
14936 // Build a test project and workspace view so the test can invoke
14937 // the workspace action handler the same way the UI would.
14938 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14939 let (workspace, cx) =
14940 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14941
14942 // Seed the settings file with a plain static light theme so the
14943 // first toggle always starts from a known persisted state.
14944 workspace.update_in(cx, |_workspace, _window, cx| {
14945 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14946 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14947 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14948 });
14949 });
14950 cx.executor().advance_clock(Duration::from_millis(200));
14951 cx.run_until_parked();
14952
14953 // Confirm the initial persisted settings contain the static theme
14954 // we just wrote before any toggling happens.
14955 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14956 assert!(settings_text.contains(r#""theme": "One Light""#));
14957
14958 // Toggle once. This should migrate the persisted theme settings
14959 // into light/dark slots and enable system mode.
14960 workspace.update_in(cx, |workspace, window, cx| {
14961 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14962 });
14963 cx.executor().advance_clock(Duration::from_millis(200));
14964 cx.run_until_parked();
14965
14966 // 1. Static -> Dynamic
14967 // this assertion checks theme changed from static to dynamic.
14968 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14969 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14970 assert_eq!(
14971 parsed["theme"],
14972 serde_json::json!({
14973 "mode": "system",
14974 "light": "One Light",
14975 "dark": "One Dark"
14976 })
14977 );
14978
14979 // 2. Toggle again, suppose it will change the mode to light
14980 workspace.update_in(cx, |workspace, window, cx| {
14981 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14982 });
14983 cx.executor().advance_clock(Duration::from_millis(200));
14984 cx.run_until_parked();
14985
14986 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14987 assert!(settings_text.contains(r#""mode": "light""#));
14988 }
14989
14990 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14991 let item = TestProjectItem::new(id, path, cx);
14992 item.update(cx, |item, _| {
14993 item.is_dirty = true;
14994 });
14995 item
14996 }
14997
14998 #[gpui::test]
14999 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
15000 cx: &mut gpui::TestAppContext,
15001 ) {
15002 init_test(cx);
15003 let fs = FakeFs::new(cx.executor());
15004
15005 let project = Project::test(fs, [], cx).await;
15006 let (workspace, cx) =
15007 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
15008
15009 let panel = workspace.update_in(cx, |workspace, window, cx| {
15010 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
15011 workspace.add_panel(panel.clone(), window, cx);
15012 workspace
15013 .right_dock()
15014 .update(cx, |dock, cx| dock.set_open(true, window, cx));
15015 panel
15016 });
15017
15018 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
15019 pane.update_in(cx, |pane, window, cx| {
15020 let item = cx.new(TestItem::new);
15021 pane.add_item(Box::new(item), true, true, None, window, cx);
15022 });
15023
15024 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
15025 // mirrors the real-world flow and avoids side effects from directly
15026 // focusing the panel while the center pane is active.
15027 workspace.update_in(cx, |workspace, window, cx| {
15028 workspace.toggle_panel_focus::<TestPanel>(window, cx);
15029 });
15030
15031 panel.update_in(cx, |panel, window, cx| {
15032 panel.set_zoomed(true, window, cx);
15033 });
15034
15035 workspace.update_in(cx, |workspace, window, cx| {
15036 assert!(workspace.right_dock().read(cx).is_open());
15037 assert!(panel.is_zoomed(window, cx));
15038 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
15039 });
15040
15041 // Simulate a spurious pane::Event::Focus on the center pane while the
15042 // panel still has focus. This mirrors what happens during macOS window
15043 // activation: the center pane fires a focus event even though actual
15044 // focus remains on the dock panel.
15045 pane.update_in(cx, |_, _, cx| {
15046 cx.emit(pane::Event::Focus);
15047 });
15048
15049 // The dock must remain open because the panel had focus at the time the
15050 // event was processed. Before the fix, dock_to_preserve was None for
15051 // panels that don't implement pane(), causing the dock to close.
15052 workspace.update_in(cx, |workspace, window, cx| {
15053 assert!(
15054 workspace.right_dock().read(cx).is_open(),
15055 "Dock should stay open when its zoomed panel (without pane()) still has focus"
15056 );
15057 assert!(panel.is_zoomed(window, cx));
15058 });
15059 }
15060
15061 #[gpui::test]
15062 async fn test_panels_stay_open_after_position_change_and_settings_update(
15063 cx: &mut gpui::TestAppContext,
15064 ) {
15065 init_test(cx);
15066 let fs = FakeFs::new(cx.executor());
15067 let project = Project::test(fs, [], cx).await;
15068 let (workspace, cx) =
15069 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
15070
15071 // Add two panels to the left dock and open it.
15072 let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
15073 let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
15074 let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
15075 workspace.add_panel(panel_a.clone(), window, cx);
15076 workspace.add_panel(panel_b.clone(), window, cx);
15077 workspace.left_dock().update(cx, |dock, cx| {
15078 dock.set_open(true, window, cx);
15079 dock.activate_panel(0, window, cx);
15080 });
15081 (panel_a, panel_b)
15082 });
15083
15084 workspace.update_in(cx, |workspace, _, cx| {
15085 assert!(workspace.left_dock().read(cx).is_open());
15086 });
15087
15088 // Simulate a feature flag changing default dock positions: both panels
15089 // move from Left to Right.
15090 workspace.update_in(cx, |_workspace, _window, cx| {
15091 panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
15092 panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
15093 cx.update_global::<SettingsStore, _>(|_, _| {});
15094 });
15095
15096 // Both panels should now be in the right dock.
15097 workspace.update_in(cx, |workspace, _, cx| {
15098 let right_dock = workspace.right_dock().read(cx);
15099 assert_eq!(right_dock.panels_len(), 2);
15100 });
15101
15102 // Open the right dock and activate panel_b (simulating the user
15103 // opening the panel after it moved).
15104 workspace.update_in(cx, |workspace, window, cx| {
15105 workspace.right_dock().update(cx, |dock, cx| {
15106 dock.set_open(true, window, cx);
15107 dock.activate_panel(1, window, cx);
15108 });
15109 });
15110
15111 // Now trigger another SettingsStore change
15112 workspace.update_in(cx, |_workspace, _window, cx| {
15113 cx.update_global::<SettingsStore, _>(|_, _| {});
15114 });
15115
15116 workspace.update_in(cx, |workspace, _, cx| {
15117 assert!(
15118 workspace.right_dock().read(cx).is_open(),
15119 "Right dock should still be open after a settings change"
15120 );
15121 assert_eq!(
15122 workspace.right_dock().read(cx).panels_len(),
15123 2,
15124 "Both panels should still be in the right dock"
15125 );
15126 });
15127 }
15128}