1pub mod dock;
2pub mod history_manager;
3pub mod invalid_item_view;
4pub mod item;
5mod modal_layer;
6mod multi_workspace;
7pub mod notifications;
8pub mod pane;
9pub mod pane_group;
10pub mod path_list {
11 pub use util::path_list::{PathList, SerializedPathList};
12}
13mod persistence;
14pub mod searchable;
15mod security_modal;
16pub mod shared_screen;
17use db::smol::future::yield_now;
18pub use shared_screen::SharedScreen;
19mod status_bar;
20pub mod tasks;
21mod theme_preview;
22mod toast_layer;
23mod toolbar;
24pub mod welcome;
25mod workspace_settings;
26
27pub use crate::notifications::NotificationFrame;
28pub use dock::Panel;
29pub use multi_workspace::{
30 DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace, MultiWorkspaceEvent,
31 NewWorkspaceInWindow, NextWorkspaceInWindow, PreviousWorkspaceInWindow,
32 SIDEBAR_RESIZE_HANDLE_SIZE, ToggleWorkspaceSidebar, multi_workspace_enabled,
33};
34pub use path_list::{PathList, SerializedPathList};
35pub use toast_layer::{ToastAction, ToastLayer, ToastView};
36
37use anyhow::{Context as _, Result, anyhow};
38use client::{
39 ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
40 proto::{self, ErrorCode, PanelId, PeerId},
41};
42use collections::{HashMap, HashSet, hash_map};
43use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
44use fs::Fs;
45use futures::{
46 Future, FutureExt, StreamExt,
47 channel::{
48 mpsc::{self, UnboundedReceiver, UnboundedSender},
49 oneshot,
50 },
51 future::{Shared, try_join_all},
52};
53use gpui::{
54 Action, AnyElement, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis,
55 Bounds, Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter,
56 FocusHandle, Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView,
57 MouseButton, PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful,
58 StyleRefinement, Subscription, SystemWindowTabController, Task, Tiling, WeakEntity,
59 WindowBounds, WindowHandle, WindowId, WindowOptions, actions, canvas, point, relative, size,
60 transparent_black,
61};
62pub use history_manager::*;
63pub use item::{
64 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
65 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
66};
67use itertools::Itertools;
68use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
69pub use modal_layer::*;
70use node_runtime::NodeRuntime;
71use notifications::{
72 DetachAndPromptErr, Notifications, dismiss_app_notification,
73 simple_message_notification::MessageNotification,
74};
75pub use pane::*;
76pub use pane_group::{
77 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneAxisState, PaneGroup,
78 PaneRenderContext, SplitDirection, pane_axis,
79};
80use persistence::{DB, SerializedWindowBounds, model::SerializedWorkspace};
81pub use persistence::{
82 DB as WORKSPACE_DB, WorkspaceDb, delete_unloaded_items,
83 model::{
84 DockStructure, ItemId, MultiWorkspaceId, SerializedMultiWorkspace,
85 SerializedWorkspaceLocation, SessionWorkspace,
86 },
87 read_serialized_multi_workspaces,
88};
89use postage::stream::Stream;
90use project::{
91 DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
92 WorktreeSettings,
93 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
94 project_settings::ProjectSettings,
95 toolchain_store::ToolchainStoreEvent,
96 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
97};
98use remote::{
99 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
100 remote_client::ConnectionIdentifier,
101};
102use schemars::JsonSchema;
103use serde::Deserialize;
104use session::AppSession;
105use settings::{
106 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
107};
108
109use sqlez::{
110 bindable::{Bind, Column, StaticColumnCount},
111 statement::Statement,
112};
113use status_bar::StatusBar;
114pub use status_bar::StatusItemView;
115use std::{
116 any::TypeId,
117 borrow::Cow,
118 cell::RefCell,
119 cmp,
120 collections::VecDeque,
121 env,
122 hash::Hash,
123 path::{Path, PathBuf},
124 process::ExitStatus,
125 rc::Rc,
126 sync::{
127 Arc, LazyLock, Weak,
128 atomic::{AtomicBool, AtomicUsize},
129 },
130 time::Duration,
131};
132use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
133use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
134pub use toolbar::{
135 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
136};
137pub use ui;
138use ui::{Window, prelude::*};
139use util::{
140 ResultExt, TryFutureExt,
141 paths::{PathStyle, SanitizedPath},
142 rel_path::RelPath,
143 serde::default_true,
144};
145use uuid::Uuid;
146pub use workspace_settings::{
147 AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
148 WorkspaceSettings,
149};
150use zed_actions::{Spawn, feedback::FileBugReport};
151
152use crate::{dock::DockPart, item::ItemBufferKind, notifications::NotificationId};
153use crate::{
154 persistence::{
155 SerializedAxis,
156 model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
157 },
158 security_modal::SecurityModal,
159};
160
161pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
162
163static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
164 env::var("ZED_WINDOW_SIZE")
165 .ok()
166 .as_deref()
167 .and_then(parse_pixel_size_env_var)
168});
169
170static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
171 env::var("ZED_WINDOW_POSITION")
172 .ok()
173 .as_deref()
174 .and_then(parse_pixel_position_env_var)
175});
176
177pub trait TerminalProvider {
178 fn spawn(
179 &self,
180 task: SpawnInTerminal,
181 window: &mut Window,
182 cx: &mut App,
183 ) -> Task<Option<Result<ExitStatus>>>;
184}
185
186pub trait DebuggerProvider {
187 // `active_buffer` is used to resolve build task's name against language-specific tasks.
188 fn start_session(
189 &self,
190 definition: DebugScenario,
191 task_context: SharedTaskContext,
192 active_buffer: Option<Entity<Buffer>>,
193 worktree_id: Option<WorktreeId>,
194 window: &mut Window,
195 cx: &mut App,
196 );
197
198 fn spawn_task_or_modal(
199 &self,
200 workspace: &mut Workspace,
201 action: &Spawn,
202 window: &mut Window,
203 cx: &mut Context<Workspace>,
204 );
205
206 fn task_scheduled(&self, cx: &mut App);
207 fn debug_scenario_scheduled(&self, cx: &mut App);
208 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
209
210 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
211}
212
213/// Opens a file or directory.
214#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
215#[action(namespace = workspace)]
216pub struct Open {
217 /// When true, opens in a new window. When false, adds to the current
218 /// window as a new workspace (multi-workspace).
219 #[serde(default = "Open::default_create_new_window")]
220 pub create_new_window: bool,
221}
222
223impl Open {
224 pub const DEFAULT: Self = Self {
225 create_new_window: true,
226 };
227
228 /// Used by `#[serde(default)]` on the `create_new_window` field so that
229 /// the serde default and `Open::DEFAULT` stay in sync.
230 fn default_create_new_window() -> bool {
231 Self::DEFAULT.create_new_window
232 }
233}
234
235impl Default for Open {
236 fn default() -> Self {
237 Self::DEFAULT
238 }
239}
240
241actions!(
242 workspace,
243 [
244 /// Activates the next pane in the workspace.
245 ActivateNextPane,
246 /// Activates the previous pane in the workspace.
247 ActivatePreviousPane,
248 /// Activates the last pane in the workspace.
249 ActivateLastPane,
250 /// Switches to the next window.
251 ActivateNextWindow,
252 /// Switches to the previous window.
253 ActivatePreviousWindow,
254 /// Adds a folder to the current project.
255 AddFolderToProject,
256 /// Clears all notifications.
257 ClearAllNotifications,
258 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
259 ClearNavigationHistory,
260 /// Closes the active dock.
261 CloseActiveDock,
262 /// Closes all docks.
263 CloseAllDocks,
264 /// Toggles all docks.
265 ToggleAllDocks,
266 /// Closes the current window.
267 CloseWindow,
268 /// Closes the current project.
269 CloseProject,
270 /// Opens the feedback dialog.
271 Feedback,
272 /// Follows the next collaborator in the session.
273 FollowNextCollaborator,
274 /// Moves the focused panel to the next position.
275 MoveFocusedPanelToNextPosition,
276 /// Creates a new file.
277 NewFile,
278 /// Creates a new file in a vertical split.
279 NewFileSplitVertical,
280 /// Creates a new file in a horizontal split.
281 NewFileSplitHorizontal,
282 /// Opens a new search.
283 NewSearch,
284 /// Opens a new window.
285 NewWindow,
286 /// Opens multiple files.
287 OpenFiles,
288 /// Opens the current location in terminal.
289 OpenInTerminal,
290 /// Opens the component preview.
291 OpenComponentPreview,
292 /// Reloads the active item.
293 ReloadActiveItem,
294 /// Resets the active dock to its default size.
295 ResetActiveDockSize,
296 /// Resets all open docks to their default sizes.
297 ResetOpenDocksSize,
298 /// Reloads the application
299 Reload,
300 /// Saves the current file with a new name.
301 SaveAs,
302 /// Saves without formatting.
303 SaveWithoutFormat,
304 /// Shuts down all debug adapters.
305 ShutdownDebugAdapters,
306 /// Suppresses the current notification.
307 SuppressNotification,
308 /// Toggles the bottom dock.
309 ToggleBottomDock,
310 /// Toggles centered layout mode.
311 ToggleCenteredLayout,
312 /// Toggles edit prediction feature globally for all files.
313 ToggleEditPrediction,
314 /// Toggles the left dock.
315 ToggleLeftDock,
316 /// Toggles the right dock.
317 ToggleRightDock,
318 /// Toggles zoom on the active pane.
319 ToggleZoom,
320 /// Toggles read-only mode for the active item (if supported by that item).
321 ToggleReadOnlyFile,
322 /// Zooms in on the active pane.
323 ZoomIn,
324 /// Zooms out of the active pane.
325 ZoomOut,
326 /// If any worktrees are in restricted mode, shows a modal with possible actions.
327 /// If the modal is shown already, closes it without trusting any worktree.
328 ToggleWorktreeSecurity,
329 /// Clears all trusted worktrees, placing them in restricted mode on next open.
330 /// Requires restart to take effect on already opened projects.
331 ClearTrustedWorktrees,
332 /// Stops following a collaborator.
333 Unfollow,
334 /// Restores the banner.
335 RestoreBanner,
336 /// Toggles expansion of the selected item.
337 ToggleExpandItem,
338 ]
339);
340
341/// Activates a specific pane by its index.
342#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
343#[action(namespace = workspace)]
344pub struct ActivatePane(pub usize);
345
346/// Moves an item to a specific pane by index.
347#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
348#[action(namespace = workspace)]
349#[serde(deny_unknown_fields)]
350pub struct MoveItemToPane {
351 #[serde(default = "default_1")]
352 pub destination: usize,
353 #[serde(default = "default_true")]
354 pub focus: bool,
355 #[serde(default)]
356 pub clone: bool,
357}
358
359fn default_1() -> usize {
360 1
361}
362
363/// Moves an item to a pane in the specified direction.
364#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
365#[action(namespace = workspace)]
366#[serde(deny_unknown_fields)]
367pub struct MoveItemToPaneInDirection {
368 #[serde(default = "default_right")]
369 pub direction: SplitDirection,
370 #[serde(default = "default_true")]
371 pub focus: bool,
372 #[serde(default)]
373 pub clone: bool,
374}
375
376/// Creates a new file in a split of the desired direction.
377#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
378#[action(namespace = workspace)]
379#[serde(deny_unknown_fields)]
380pub struct NewFileSplit(pub SplitDirection);
381
382fn default_right() -> SplitDirection {
383 SplitDirection::Right
384}
385
386/// Saves all open files in the workspace.
387#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
388#[action(namespace = workspace)]
389#[serde(deny_unknown_fields)]
390pub struct SaveAll {
391 #[serde(default)]
392 pub save_intent: Option<SaveIntent>,
393}
394
395/// Saves the current file with the specified options.
396#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
397#[action(namespace = workspace)]
398#[serde(deny_unknown_fields)]
399pub struct Save {
400 #[serde(default)]
401 pub save_intent: Option<SaveIntent>,
402}
403
404/// Closes all items and panes in the workspace.
405#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
406#[action(namespace = workspace)]
407#[serde(deny_unknown_fields)]
408pub struct CloseAllItemsAndPanes {
409 #[serde(default)]
410 pub save_intent: Option<SaveIntent>,
411}
412
413/// Closes all inactive tabs and panes in the workspace.
414#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
415#[action(namespace = workspace)]
416#[serde(deny_unknown_fields)]
417pub struct CloseInactiveTabsAndPanes {
418 #[serde(default)]
419 pub save_intent: Option<SaveIntent>,
420}
421
422/// Closes the active item across all panes.
423#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
424#[action(namespace = workspace)]
425#[serde(deny_unknown_fields)]
426pub struct CloseItemInAllPanes {
427 #[serde(default)]
428 pub save_intent: Option<SaveIntent>,
429 #[serde(default)]
430 pub close_pinned: bool,
431}
432
433/// Sends a sequence of keystrokes to the active element.
434#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
435#[action(namespace = workspace)]
436pub struct SendKeystrokes(pub String);
437
438actions!(
439 project_symbols,
440 [
441 /// Toggles the project symbols search.
442 #[action(name = "Toggle")]
443 ToggleProjectSymbols
444 ]
445);
446
447/// Toggles the file finder interface.
448#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
449#[action(namespace = file_finder, name = "Toggle")]
450#[serde(deny_unknown_fields)]
451pub struct ToggleFileFinder {
452 #[serde(default)]
453 pub separate_history: bool,
454}
455
456/// Opens a new terminal in the center.
457#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
458#[action(namespace = workspace)]
459#[serde(deny_unknown_fields)]
460pub struct NewCenterTerminal {
461 /// If true, creates a local terminal even in remote projects.
462 #[serde(default)]
463 pub local: bool,
464}
465
466/// Opens a new terminal.
467#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
468#[action(namespace = workspace)]
469#[serde(deny_unknown_fields)]
470pub struct NewTerminal {
471 /// If true, creates a local terminal even in remote projects.
472 #[serde(default)]
473 pub local: bool,
474}
475
476/// Increases size of a currently focused dock by a given amount of pixels.
477#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
478#[action(namespace = workspace)]
479#[serde(deny_unknown_fields)]
480pub struct IncreaseActiveDockSize {
481 /// For 0px parameter, uses UI font size value.
482 #[serde(default)]
483 pub px: u32,
484}
485
486/// Decreases size of a currently focused dock by a given amount of pixels.
487#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
488#[action(namespace = workspace)]
489#[serde(deny_unknown_fields)]
490pub struct DecreaseActiveDockSize {
491 /// For 0px parameter, uses UI font size value.
492 #[serde(default)]
493 pub px: u32,
494}
495
496/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
497#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
498#[action(namespace = workspace)]
499#[serde(deny_unknown_fields)]
500pub struct IncreaseOpenDocksSize {
501 /// For 0px parameter, uses UI font size value.
502 #[serde(default)]
503 pub px: u32,
504}
505
506/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
507#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
508#[action(namespace = workspace)]
509#[serde(deny_unknown_fields)]
510pub struct DecreaseOpenDocksSize {
511 /// For 0px parameter, uses UI font size value.
512 #[serde(default)]
513 pub px: u32,
514}
515
516actions!(
517 workspace,
518 [
519 /// Activates the pane to the left.
520 ActivatePaneLeft,
521 /// Activates the pane to the right.
522 ActivatePaneRight,
523 /// Activates the pane above.
524 ActivatePaneUp,
525 /// Activates the pane below.
526 ActivatePaneDown,
527 /// Swaps the current pane with the one to the left.
528 SwapPaneLeft,
529 /// Swaps the current pane with the one to the right.
530 SwapPaneRight,
531 /// Swaps the current pane with the one above.
532 SwapPaneUp,
533 /// Swaps the current pane with the one below.
534 SwapPaneDown,
535 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
536 SwapPaneAdjacent,
537 /// Move the current pane to be at the far left.
538 MovePaneLeft,
539 /// Move the current pane to be at the far right.
540 MovePaneRight,
541 /// Move the current pane to be at the very top.
542 MovePaneUp,
543 /// Move the current pane to be at the very bottom.
544 MovePaneDown,
545 ]
546);
547
548#[derive(PartialEq, Eq, Debug)]
549pub enum CloseIntent {
550 /// Quit the program entirely.
551 Quit,
552 /// Close a window.
553 CloseWindow,
554 /// Replace the workspace in an existing window.
555 ReplaceWindow,
556}
557
558#[derive(Clone)]
559pub struct Toast {
560 id: NotificationId,
561 msg: Cow<'static, str>,
562 autohide: bool,
563 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
564}
565
566impl Toast {
567 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
568 Toast {
569 id,
570 msg: msg.into(),
571 on_click: None,
572 autohide: false,
573 }
574 }
575
576 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
577 where
578 M: Into<Cow<'static, str>>,
579 F: Fn(&mut Window, &mut App) + 'static,
580 {
581 self.on_click = Some((message.into(), Arc::new(on_click)));
582 self
583 }
584
585 pub fn autohide(mut self) -> Self {
586 self.autohide = true;
587 self
588 }
589}
590
591impl PartialEq for Toast {
592 fn eq(&self, other: &Self) -> bool {
593 self.id == other.id
594 && self.msg == other.msg
595 && self.on_click.is_some() == other.on_click.is_some()
596 }
597}
598
599/// Opens a new terminal with the specified working directory.
600#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
601#[action(namespace = workspace)]
602#[serde(deny_unknown_fields)]
603pub struct OpenTerminal {
604 pub working_directory: PathBuf,
605 /// If true, creates a local terminal even in remote projects.
606 #[serde(default)]
607 pub local: bool,
608}
609
610#[derive(
611 Clone,
612 Copy,
613 Debug,
614 Default,
615 Hash,
616 PartialEq,
617 Eq,
618 PartialOrd,
619 Ord,
620 serde::Serialize,
621 serde::Deserialize,
622)]
623pub struct WorkspaceId(i64);
624
625impl WorkspaceId {
626 pub fn from_i64(value: i64) -> Self {
627 Self(value)
628 }
629}
630
631impl StaticColumnCount for WorkspaceId {}
632impl Bind for WorkspaceId {
633 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
634 self.0.bind(statement, start_index)
635 }
636}
637impl Column for WorkspaceId {
638 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
639 i64::column(statement, start_index)
640 .map(|(i, next_index)| (Self(i), next_index))
641 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
642 }
643}
644impl From<WorkspaceId> for i64 {
645 fn from(val: WorkspaceId) -> Self {
646 val.0
647 }
648}
649
650fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
651 if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
652 workspace_window
653 .update(cx, |multi_workspace, window, cx| {
654 let workspace = multi_workspace.workspace().clone();
655 workspace.update(cx, |workspace, cx| {
656 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
657 });
658 })
659 .ok();
660 } else {
661 let task = Workspace::new_local(Vec::new(), app_state.clone(), None, None, None, true, cx);
662 cx.spawn(async move |cx| {
663 let (window, _) = task.await?;
664 window.update(cx, |multi_workspace, window, cx| {
665 window.activate_window();
666 let workspace = multi_workspace.workspace().clone();
667 workspace.update(cx, |workspace, cx| {
668 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
669 });
670 })?;
671 anyhow::Ok(())
672 })
673 .detach_and_log_err(cx);
674 }
675}
676
677pub fn prompt_for_open_path_and_open(
678 workspace: &mut Workspace,
679 app_state: Arc<AppState>,
680 options: PathPromptOptions,
681 create_new_window: bool,
682 window: &mut Window,
683 cx: &mut Context<Workspace>,
684) {
685 let paths = workspace.prompt_for_open_path(
686 options,
687 DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
688 window,
689 cx,
690 );
691 let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
692 cx.spawn_in(window, async move |this, cx| {
693 let Some(paths) = paths.await.log_err().flatten() else {
694 return;
695 };
696 if !create_new_window {
697 if let Some(handle) = multi_workspace_handle {
698 if let Some(task) = handle
699 .update(cx, |multi_workspace, window, cx| {
700 multi_workspace.open_project(paths, window, cx)
701 })
702 .log_err()
703 {
704 task.await.log_err();
705 }
706 return;
707 }
708 }
709 if let Some(task) = this
710 .update_in(cx, |this, window, cx| {
711 this.open_workspace_for_paths(false, paths, window, cx)
712 })
713 .log_err()
714 {
715 task.await.log_err();
716 }
717 })
718 .detach();
719}
720
721pub fn init(app_state: Arc<AppState>, cx: &mut App) {
722 component::init();
723 theme_preview::init(cx);
724 toast_layer::init(cx);
725 history_manager::init(app_state.fs.clone(), cx);
726
727 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
728 .on_action(|_: &Reload, cx| reload(cx))
729 .on_action({
730 let app_state = Arc::downgrade(&app_state);
731 move |_: &Open, cx: &mut App| {
732 if let Some(app_state) = app_state.upgrade() {
733 prompt_and_open_paths(
734 app_state,
735 PathPromptOptions {
736 files: true,
737 directories: true,
738 multiple: true,
739 prompt: None,
740 },
741 cx,
742 );
743 }
744 }
745 })
746 .on_action({
747 let app_state = Arc::downgrade(&app_state);
748 move |_: &OpenFiles, cx: &mut App| {
749 let directories = cx.can_select_mixed_files_and_dirs();
750 if let Some(app_state) = app_state.upgrade() {
751 prompt_and_open_paths(
752 app_state,
753 PathPromptOptions {
754 files: true,
755 directories,
756 multiple: true,
757 prompt: None,
758 },
759 cx,
760 );
761 }
762 }
763 });
764}
765
766type BuildProjectItemFn =
767 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
768
769type BuildProjectItemForPathFn =
770 fn(
771 &Entity<Project>,
772 &ProjectPath,
773 &mut Window,
774 &mut App,
775 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
776
777#[derive(Clone, Default)]
778struct ProjectItemRegistry {
779 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
780 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
781}
782
783impl ProjectItemRegistry {
784 fn register<T: ProjectItem>(&mut self) {
785 self.build_project_item_fns_by_type.insert(
786 TypeId::of::<T::Item>(),
787 |item, project, pane, window, cx| {
788 let item = item.downcast().unwrap();
789 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
790 as Box<dyn ItemHandle>
791 },
792 );
793 self.build_project_item_for_path_fns
794 .push(|project, project_path, window, cx| {
795 let project_path = project_path.clone();
796 let is_file = project
797 .read(cx)
798 .entry_for_path(&project_path, cx)
799 .is_some_and(|entry| entry.is_file());
800 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
801 let is_local = project.read(cx).is_local();
802 let project_item =
803 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
804 let project = project.clone();
805 Some(window.spawn(cx, async move |cx| {
806 match project_item.await.with_context(|| {
807 format!(
808 "opening project path {:?}",
809 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
810 )
811 }) {
812 Ok(project_item) => {
813 let project_item = project_item;
814 let project_entry_id: Option<ProjectEntryId> =
815 project_item.read_with(cx, project::ProjectItem::entry_id);
816 let build_workspace_item = Box::new(
817 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
818 Box::new(cx.new(|cx| {
819 T::for_project_item(
820 project,
821 Some(pane),
822 project_item,
823 window,
824 cx,
825 )
826 })) as Box<dyn ItemHandle>
827 },
828 ) as Box<_>;
829 Ok((project_entry_id, build_workspace_item))
830 }
831 Err(e) => {
832 log::warn!("Failed to open a project item: {e:#}");
833 if e.error_code() == ErrorCode::Internal {
834 if let Some(abs_path) =
835 entry_abs_path.as_deref().filter(|_| is_file)
836 {
837 if let Some(broken_project_item_view) =
838 cx.update(|window, cx| {
839 T::for_broken_project_item(
840 abs_path, is_local, &e, window, cx,
841 )
842 })?
843 {
844 let build_workspace_item = Box::new(
845 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
846 cx.new(|_| broken_project_item_view).boxed_clone()
847 },
848 )
849 as Box<_>;
850 return Ok((None, build_workspace_item));
851 }
852 }
853 }
854 Err(e)
855 }
856 }
857 }))
858 });
859 }
860
861 fn open_path(
862 &self,
863 project: &Entity<Project>,
864 path: &ProjectPath,
865 window: &mut Window,
866 cx: &mut App,
867 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
868 let Some(open_project_item) = self
869 .build_project_item_for_path_fns
870 .iter()
871 .rev()
872 .find_map(|open_project_item| open_project_item(project, path, window, cx))
873 else {
874 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
875 };
876 open_project_item
877 }
878
879 fn build_item<T: project::ProjectItem>(
880 &self,
881 item: Entity<T>,
882 project: Entity<Project>,
883 pane: Option<&Pane>,
884 window: &mut Window,
885 cx: &mut App,
886 ) -> Option<Box<dyn ItemHandle>> {
887 let build = self
888 .build_project_item_fns_by_type
889 .get(&TypeId::of::<T>())?;
890 Some(build(item.into_any(), project, pane, window, cx))
891 }
892}
893
894type WorkspaceItemBuilder =
895 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
896
897impl Global for ProjectItemRegistry {}
898
899/// Registers a [ProjectItem] for the app. When opening a file, all the registered
900/// items will get a chance to open the file, starting from the project item that
901/// was added last.
902pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
903 cx.default_global::<ProjectItemRegistry>().register::<I>();
904}
905
906#[derive(Default)]
907pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
908
909struct FollowableViewDescriptor {
910 from_state_proto: fn(
911 Entity<Workspace>,
912 ViewId,
913 &mut Option<proto::view::Variant>,
914 &mut Window,
915 &mut App,
916 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
917 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
918}
919
920impl Global for FollowableViewRegistry {}
921
922impl FollowableViewRegistry {
923 pub fn register<I: FollowableItem>(cx: &mut App) {
924 cx.default_global::<Self>().0.insert(
925 TypeId::of::<I>(),
926 FollowableViewDescriptor {
927 from_state_proto: |workspace, id, state, window, cx| {
928 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
929 cx.foreground_executor()
930 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
931 })
932 },
933 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
934 },
935 );
936 }
937
938 pub fn from_state_proto(
939 workspace: Entity<Workspace>,
940 view_id: ViewId,
941 mut state: Option<proto::view::Variant>,
942 window: &mut Window,
943 cx: &mut App,
944 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
945 cx.update_default_global(|this: &mut Self, cx| {
946 this.0.values().find_map(|descriptor| {
947 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
948 })
949 })
950 }
951
952 pub fn to_followable_view(
953 view: impl Into<AnyView>,
954 cx: &App,
955 ) -> Option<Box<dyn FollowableItemHandle>> {
956 let this = cx.try_global::<Self>()?;
957 let view = view.into();
958 let descriptor = this.0.get(&view.entity_type())?;
959 Some((descriptor.to_followable_view)(&view))
960 }
961}
962
963#[derive(Copy, Clone)]
964struct SerializableItemDescriptor {
965 deserialize: fn(
966 Entity<Project>,
967 WeakEntity<Workspace>,
968 WorkspaceId,
969 ItemId,
970 &mut Window,
971 &mut Context<Pane>,
972 ) -> Task<Result<Box<dyn ItemHandle>>>,
973 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
974 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
975}
976
977#[derive(Default)]
978struct SerializableItemRegistry {
979 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
980 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
981}
982
983impl Global for SerializableItemRegistry {}
984
985impl SerializableItemRegistry {
986 fn deserialize(
987 item_kind: &str,
988 project: Entity<Project>,
989 workspace: WeakEntity<Workspace>,
990 workspace_id: WorkspaceId,
991 item_item: ItemId,
992 window: &mut Window,
993 cx: &mut Context<Pane>,
994 ) -> Task<Result<Box<dyn ItemHandle>>> {
995 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
996 return Task::ready(Err(anyhow!(
997 "cannot deserialize {}, descriptor not found",
998 item_kind
999 )));
1000 };
1001
1002 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
1003 }
1004
1005 fn cleanup(
1006 item_kind: &str,
1007 workspace_id: WorkspaceId,
1008 loaded_items: Vec<ItemId>,
1009 window: &mut Window,
1010 cx: &mut App,
1011 ) -> Task<Result<()>> {
1012 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1013 return Task::ready(Err(anyhow!(
1014 "cannot cleanup {}, descriptor not found",
1015 item_kind
1016 )));
1017 };
1018
1019 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
1020 }
1021
1022 fn view_to_serializable_item_handle(
1023 view: AnyView,
1024 cx: &App,
1025 ) -> Option<Box<dyn SerializableItemHandle>> {
1026 let this = cx.try_global::<Self>()?;
1027 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
1028 Some((descriptor.view_to_serializable_item)(view))
1029 }
1030
1031 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
1032 let this = cx.try_global::<Self>()?;
1033 this.descriptors_by_kind.get(item_kind).copied()
1034 }
1035}
1036
1037pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
1038 let serialized_item_kind = I::serialized_item_kind();
1039
1040 let registry = cx.default_global::<SerializableItemRegistry>();
1041 let descriptor = SerializableItemDescriptor {
1042 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
1043 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
1044 cx.foreground_executor()
1045 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
1046 },
1047 cleanup: |workspace_id, loaded_items, window, cx| {
1048 I::cleanup(workspace_id, loaded_items, window, cx)
1049 },
1050 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
1051 };
1052 registry
1053 .descriptors_by_kind
1054 .insert(Arc::from(serialized_item_kind), descriptor);
1055 registry
1056 .descriptors_by_type
1057 .insert(TypeId::of::<I>(), descriptor);
1058}
1059
1060pub struct AppState {
1061 pub languages: Arc<LanguageRegistry>,
1062 pub client: Arc<Client>,
1063 pub user_store: Entity<UserStore>,
1064 pub workspace_store: Entity<WorkspaceStore>,
1065 pub fs: Arc<dyn fs::Fs>,
1066 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1067 pub node_runtime: NodeRuntime,
1068 pub session: Entity<AppSession>,
1069}
1070
1071struct GlobalAppState(Weak<AppState>);
1072
1073impl Global for GlobalAppState {}
1074
1075pub struct WorkspaceStore {
1076 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1077 client: Arc<Client>,
1078 _subscriptions: Vec<client::Subscription>,
1079}
1080
1081#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1082pub enum CollaboratorId {
1083 PeerId(PeerId),
1084 Agent,
1085}
1086
1087impl From<PeerId> for CollaboratorId {
1088 fn from(peer_id: PeerId) -> Self {
1089 CollaboratorId::PeerId(peer_id)
1090 }
1091}
1092
1093impl From<&PeerId> for CollaboratorId {
1094 fn from(peer_id: &PeerId) -> Self {
1095 CollaboratorId::PeerId(*peer_id)
1096 }
1097}
1098
1099#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1100struct Follower {
1101 project_id: Option<u64>,
1102 peer_id: PeerId,
1103}
1104
1105impl AppState {
1106 #[track_caller]
1107 pub fn global(cx: &App) -> Weak<Self> {
1108 cx.global::<GlobalAppState>().0.clone()
1109 }
1110 pub fn try_global(cx: &App) -> Option<Weak<Self>> {
1111 cx.try_global::<GlobalAppState>()
1112 .map(|state| state.0.clone())
1113 }
1114 pub fn set_global(state: Weak<AppState>, cx: &mut App) {
1115 cx.set_global(GlobalAppState(state));
1116 }
1117
1118 #[cfg(any(test, feature = "test-support"))]
1119 pub fn test(cx: &mut App) -> Arc<Self> {
1120 use fs::Fs;
1121 use node_runtime::NodeRuntime;
1122 use session::Session;
1123 use settings::SettingsStore;
1124
1125 if !cx.has_global::<SettingsStore>() {
1126 let settings_store = SettingsStore::test(cx);
1127 cx.set_global(settings_store);
1128 }
1129
1130 let fs = fs::FakeFs::new(cx.background_executor().clone());
1131 <dyn Fs>::set_global(fs.clone(), cx);
1132 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1133 let clock = Arc::new(clock::FakeSystemClock::new());
1134 let http_client = http_client::FakeHttpClient::with_404_response();
1135 let client = Client::new(clock, http_client, cx);
1136 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1137 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1138 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1139
1140 theme::init(theme::LoadThemes::JustBase, cx);
1141 client::init(&client, cx);
1142
1143 Arc::new(Self {
1144 client,
1145 fs,
1146 languages,
1147 user_store,
1148 workspace_store,
1149 node_runtime: NodeRuntime::unavailable(),
1150 build_window_options: |_, _| Default::default(),
1151 session,
1152 })
1153 }
1154}
1155
1156struct DelayedDebouncedEditAction {
1157 task: Option<Task<()>>,
1158 cancel_channel: Option<oneshot::Sender<()>>,
1159}
1160
1161impl DelayedDebouncedEditAction {
1162 fn new() -> DelayedDebouncedEditAction {
1163 DelayedDebouncedEditAction {
1164 task: None,
1165 cancel_channel: None,
1166 }
1167 }
1168
1169 fn fire_new<F>(
1170 &mut self,
1171 delay: Duration,
1172 window: &mut Window,
1173 cx: &mut Context<Workspace>,
1174 func: F,
1175 ) where
1176 F: 'static
1177 + Send
1178 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1179 {
1180 if let Some(channel) = self.cancel_channel.take() {
1181 _ = channel.send(());
1182 }
1183
1184 let (sender, mut receiver) = oneshot::channel::<()>();
1185 self.cancel_channel = Some(sender);
1186
1187 let previous_task = self.task.take();
1188 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1189 let mut timer = cx.background_executor().timer(delay).fuse();
1190 if let Some(previous_task) = previous_task {
1191 previous_task.await;
1192 }
1193
1194 futures::select_biased! {
1195 _ = receiver => return,
1196 _ = timer => {}
1197 }
1198
1199 if let Some(result) = workspace
1200 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1201 .log_err()
1202 {
1203 result.await.log_err();
1204 }
1205 }));
1206 }
1207}
1208
1209pub enum Event {
1210 PaneAdded(Entity<Pane>),
1211 PaneRemoved,
1212 ItemAdded {
1213 item: Box<dyn ItemHandle>,
1214 },
1215 ActiveItemChanged,
1216 ItemRemoved {
1217 item_id: EntityId,
1218 },
1219 UserSavedItem {
1220 pane: WeakEntity<Pane>,
1221 item: Box<dyn WeakItemHandle>,
1222 save_intent: SaveIntent,
1223 },
1224 ContactRequestedJoin(u64),
1225 WorkspaceCreated(WeakEntity<Workspace>),
1226 OpenBundledFile {
1227 text: Cow<'static, str>,
1228 title: &'static str,
1229 language: &'static str,
1230 },
1231 ZoomChanged,
1232 ModalOpened,
1233 Activate,
1234 PanelAdded(AnyView),
1235}
1236
1237#[derive(Debug, Clone)]
1238pub enum OpenVisible {
1239 All,
1240 None,
1241 OnlyFiles,
1242 OnlyDirectories,
1243}
1244
1245enum WorkspaceLocation {
1246 // Valid local paths or SSH project to serialize
1247 Location(SerializedWorkspaceLocation, PathList),
1248 // No valid location found hence clear session id
1249 DetachFromSession,
1250 // No valid location found to serialize
1251 None,
1252}
1253
1254type PromptForNewPath = Box<
1255 dyn Fn(
1256 &mut Workspace,
1257 DirectoryLister,
1258 Option<String>,
1259 &mut Window,
1260 &mut Context<Workspace>,
1261 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1262>;
1263
1264type PromptForOpenPath = Box<
1265 dyn Fn(
1266 &mut Workspace,
1267 DirectoryLister,
1268 &mut Window,
1269 &mut Context<Workspace>,
1270 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1271>;
1272
1273#[derive(Default)]
1274struct DispatchingKeystrokes {
1275 dispatched: HashSet<Vec<Keystroke>>,
1276 queue: VecDeque<Keystroke>,
1277 task: Option<Shared<Task<()>>>,
1278}
1279
1280/// Collects everything project-related for a certain window opened.
1281/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1282///
1283/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1284/// The `Workspace` owns everybody's state and serves as a default, "global context",
1285/// that can be used to register a global action to be triggered from any place in the window.
1286pub struct Workspace {
1287 weak_self: WeakEntity<Self>,
1288 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1289 zoomed: Option<AnyWeakView>,
1290 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1291 zoomed_position: Option<DockPosition>,
1292 center: PaneGroup,
1293 left_dock: Entity<Dock>,
1294 bottom_dock: Entity<Dock>,
1295 right_dock: Entity<Dock>,
1296 panes: Vec<Entity<Pane>>,
1297 active_worktree_override: Option<WorktreeId>,
1298 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1299 active_pane: Entity<Pane>,
1300 last_active_center_pane: Option<WeakEntity<Pane>>,
1301 last_active_view_id: Option<proto::ViewId>,
1302 status_bar: Entity<StatusBar>,
1303 pub(crate) modal_layer: Entity<ModalLayer>,
1304 toast_layer: Entity<ToastLayer>,
1305 titlebar_item: Option<AnyView>,
1306 notifications: Notifications,
1307 suppressed_notifications: HashSet<NotificationId>,
1308 project: Entity<Project>,
1309 follower_states: HashMap<CollaboratorId, FollowerState>,
1310 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1311 window_edited: bool,
1312 last_window_title: Option<String>,
1313 dirty_items: HashMap<EntityId, Subscription>,
1314 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1315 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1316 database_id: Option<WorkspaceId>,
1317 app_state: Arc<AppState>,
1318 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1319 _subscriptions: Vec<Subscription>,
1320 _apply_leader_updates: Task<Result<()>>,
1321 _observe_current_user: Task<Result<()>>,
1322 _schedule_serialize_workspace: Option<Task<()>>,
1323 _serialize_workspace_task: Option<Task<()>>,
1324 _schedule_serialize_ssh_paths: Option<Task<()>>,
1325 pane_history_timestamp: Arc<AtomicUsize>,
1326 bounds: Bounds<Pixels>,
1327 pub centered_layout: bool,
1328 bounds_save_task_queued: Option<Task<()>>,
1329 on_prompt_for_new_path: Option<PromptForNewPath>,
1330 on_prompt_for_open_path: Option<PromptForOpenPath>,
1331 terminal_provider: Option<Box<dyn TerminalProvider>>,
1332 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1333 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1334 _items_serializer: Task<Result<()>>,
1335 session_id: Option<String>,
1336 scheduled_tasks: Vec<Task<()>>,
1337 last_open_dock_positions: Vec<DockPosition>,
1338 removing: bool,
1339 _panels_task: Option<Task<Result<()>>>,
1340}
1341
1342impl EventEmitter<Event> for Workspace {}
1343
1344#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1345pub struct ViewId {
1346 pub creator: CollaboratorId,
1347 pub id: u64,
1348}
1349
1350pub struct FollowerState {
1351 center_pane: Entity<Pane>,
1352 dock_pane: Option<Entity<Pane>>,
1353 active_view_id: Option<ViewId>,
1354 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1355}
1356
1357struct FollowerView {
1358 view: Box<dyn FollowableItemHandle>,
1359 location: Option<proto::PanelId>,
1360}
1361
1362impl Workspace {
1363 pub fn new(
1364 workspace_id: Option<WorkspaceId>,
1365 project: Entity<Project>,
1366 app_state: Arc<AppState>,
1367 window: &mut Window,
1368 cx: &mut Context<Self>,
1369 ) -> Self {
1370 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1371 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1372 if let TrustedWorktreesEvent::Trusted(..) = e {
1373 // Do not persist auto trusted worktrees
1374 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1375 worktrees_store.update(cx, |worktrees_store, cx| {
1376 worktrees_store.schedule_serialization(
1377 cx,
1378 |new_trusted_worktrees, cx| {
1379 let timeout =
1380 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1381 cx.background_spawn(async move {
1382 timeout.await;
1383 persistence::DB
1384 .save_trusted_worktrees(new_trusted_worktrees)
1385 .await
1386 .log_err();
1387 })
1388 },
1389 )
1390 });
1391 }
1392 }
1393 })
1394 .detach();
1395
1396 cx.observe_global::<SettingsStore>(|_, cx| {
1397 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1398 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1399 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1400 trusted_worktrees.auto_trust_all(cx);
1401 })
1402 }
1403 }
1404 })
1405 .detach();
1406 }
1407
1408 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1409 match event {
1410 project::Event::RemoteIdChanged(_) => {
1411 this.update_window_title(window, cx);
1412 }
1413
1414 project::Event::CollaboratorLeft(peer_id) => {
1415 this.collaborator_left(*peer_id, window, cx);
1416 }
1417
1418 &project::Event::WorktreeRemoved(id) | &project::Event::WorktreeAdded(id) => {
1419 this.update_window_title(window, cx);
1420 if this
1421 .project()
1422 .read(cx)
1423 .worktree_for_id(id, cx)
1424 .is_some_and(|wt| wt.read(cx).is_visible())
1425 {
1426 this.serialize_workspace(window, cx);
1427 this.update_history(cx);
1428 }
1429 }
1430 project::Event::WorktreeUpdatedEntries(..) => {
1431 this.update_window_title(window, cx);
1432 this.serialize_workspace(window, cx);
1433 }
1434
1435 project::Event::DisconnectedFromHost => {
1436 this.update_window_edited(window, cx);
1437 let leaders_to_unfollow =
1438 this.follower_states.keys().copied().collect::<Vec<_>>();
1439 for leader_id in leaders_to_unfollow {
1440 this.unfollow(leader_id, window, cx);
1441 }
1442 }
1443
1444 project::Event::DisconnectedFromRemote {
1445 server_not_running: _,
1446 } => {
1447 this.update_window_edited(window, cx);
1448 }
1449
1450 project::Event::Closed => {
1451 window.remove_window();
1452 }
1453
1454 project::Event::DeletedEntry(_, entry_id) => {
1455 for pane in this.panes.iter() {
1456 pane.update(cx, |pane, cx| {
1457 pane.handle_deleted_project_item(*entry_id, window, cx)
1458 });
1459 }
1460 }
1461
1462 project::Event::Toast {
1463 notification_id,
1464 message,
1465 link,
1466 } => this.show_notification(
1467 NotificationId::named(notification_id.clone()),
1468 cx,
1469 |cx| {
1470 let mut notification = MessageNotification::new(message.clone(), cx);
1471 if let Some(link) = link {
1472 notification = notification
1473 .more_info_message(link.label)
1474 .more_info_url(link.url);
1475 }
1476
1477 cx.new(|_| notification)
1478 },
1479 ),
1480
1481 project::Event::HideToast { notification_id } => {
1482 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1483 }
1484
1485 project::Event::LanguageServerPrompt(request) => {
1486 struct LanguageServerPrompt;
1487
1488 this.show_notification(
1489 NotificationId::composite::<LanguageServerPrompt>(request.id),
1490 cx,
1491 |cx| {
1492 cx.new(|cx| {
1493 notifications::LanguageServerPrompt::new(request.clone(), cx)
1494 })
1495 },
1496 );
1497 }
1498
1499 project::Event::AgentLocationChanged => {
1500 this.handle_agent_location_changed(window, cx)
1501 }
1502
1503 _ => {}
1504 }
1505 cx.notify()
1506 })
1507 .detach();
1508
1509 cx.subscribe_in(
1510 &project.read(cx).breakpoint_store(),
1511 window,
1512 |workspace, _, event, window, cx| match event {
1513 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1514 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1515 workspace.serialize_workspace(window, cx);
1516 }
1517 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1518 },
1519 )
1520 .detach();
1521 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1522 cx.subscribe_in(
1523 &toolchain_store,
1524 window,
1525 |workspace, _, event, window, cx| match event {
1526 ToolchainStoreEvent::CustomToolchainsModified => {
1527 workspace.serialize_workspace(window, cx);
1528 }
1529 _ => {}
1530 },
1531 )
1532 .detach();
1533 }
1534
1535 cx.on_focus_lost(window, |this, window, cx| {
1536 let focus_handle = this.focus_handle(cx);
1537 window.focus(&focus_handle, cx);
1538 })
1539 .detach();
1540
1541 let weak_handle = cx.entity().downgrade();
1542 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1543
1544 let center_pane = cx.new(|cx| {
1545 let mut center_pane = Pane::new(
1546 weak_handle.clone(),
1547 project.clone(),
1548 pane_history_timestamp.clone(),
1549 None,
1550 NewFile.boxed_clone(),
1551 true,
1552 window,
1553 cx,
1554 );
1555 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1556 center_pane.set_should_display_welcome_page(true);
1557 center_pane
1558 });
1559 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1560 .detach();
1561
1562 window.focus(¢er_pane.focus_handle(cx), cx);
1563
1564 cx.emit(Event::PaneAdded(center_pane.clone()));
1565
1566 let any_window_handle = window.window_handle();
1567 app_state.workspace_store.update(cx, |store, _| {
1568 store
1569 .workspaces
1570 .insert((any_window_handle, weak_handle.clone()));
1571 });
1572
1573 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1574 let mut connection_status = app_state.client.status();
1575 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1576 current_user.next().await;
1577 connection_status.next().await;
1578 let mut stream =
1579 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1580
1581 while stream.recv().await.is_some() {
1582 this.update(cx, |_, cx| cx.notify())?;
1583 }
1584 anyhow::Ok(())
1585 });
1586
1587 // All leader updates are enqueued and then processed in a single task, so
1588 // that each asynchronous operation can be run in order.
1589 let (leader_updates_tx, mut leader_updates_rx) =
1590 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1591 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1592 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1593 Self::process_leader_update(&this, leader_id, update, cx)
1594 .await
1595 .log_err();
1596 }
1597
1598 Ok(())
1599 });
1600
1601 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1602 let modal_layer = cx.new(|_| ModalLayer::new());
1603 let toast_layer = cx.new(|_| ToastLayer::new());
1604 cx.subscribe(
1605 &modal_layer,
1606 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1607 cx.emit(Event::ModalOpened);
1608 },
1609 )
1610 .detach();
1611
1612 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1613 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1614 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1615 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1616 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1617 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1618 let status_bar = cx.new(|cx| {
1619 let mut status_bar = StatusBar::new(¢er_pane.clone(), window, cx);
1620 status_bar.add_left_item(left_dock_buttons, window, cx);
1621 status_bar.add_right_item(right_dock_buttons, window, cx);
1622 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1623 status_bar
1624 });
1625
1626 let session_id = app_state.session.read(cx).id().to_owned();
1627
1628 let mut active_call = None;
1629 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1630 let subscriptions =
1631 vec![
1632 call.0
1633 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1634 ];
1635 active_call = Some((call, subscriptions));
1636 }
1637
1638 let (serializable_items_tx, serializable_items_rx) =
1639 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1640 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1641 Self::serialize_items(&this, serializable_items_rx, cx).await
1642 });
1643
1644 let subscriptions = vec![
1645 cx.observe_window_activation(window, Self::on_window_activation_changed),
1646 cx.observe_window_bounds(window, move |this, window, cx| {
1647 if this.bounds_save_task_queued.is_some() {
1648 return;
1649 }
1650 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1651 cx.background_executor()
1652 .timer(Duration::from_millis(100))
1653 .await;
1654 this.update_in(cx, |this, window, cx| {
1655 this.save_window_bounds(window, cx).detach();
1656 this.bounds_save_task_queued.take();
1657 })
1658 .ok();
1659 }));
1660 cx.notify();
1661 }),
1662 cx.observe_window_appearance(window, |_, window, cx| {
1663 let window_appearance = window.appearance();
1664
1665 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1666
1667 GlobalTheme::reload_theme(cx);
1668 GlobalTheme::reload_icon_theme(cx);
1669 }),
1670 cx.on_release({
1671 let weak_handle = weak_handle.clone();
1672 move |this, cx| {
1673 this.app_state.workspace_store.update(cx, move |store, _| {
1674 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1675 })
1676 }
1677 }),
1678 ];
1679
1680 cx.defer_in(window, move |this, window, cx| {
1681 this.update_window_title(window, cx);
1682 this.show_initial_notifications(cx);
1683 });
1684
1685 let mut center = PaneGroup::new(center_pane.clone());
1686 center.set_is_center(true);
1687 center.mark_positions(cx);
1688
1689 Workspace {
1690 weak_self: weak_handle.clone(),
1691 zoomed: None,
1692 zoomed_position: None,
1693 previous_dock_drag_coordinates: None,
1694 center,
1695 panes: vec![center_pane.clone()],
1696 panes_by_item: Default::default(),
1697 active_pane: center_pane.clone(),
1698 last_active_center_pane: Some(center_pane.downgrade()),
1699 last_active_view_id: None,
1700 status_bar,
1701 modal_layer,
1702 toast_layer,
1703 titlebar_item: None,
1704 active_worktree_override: None,
1705 notifications: Notifications::default(),
1706 suppressed_notifications: HashSet::default(),
1707 left_dock,
1708 bottom_dock,
1709 right_dock,
1710 _panels_task: None,
1711 project: project.clone(),
1712 follower_states: Default::default(),
1713 last_leaders_by_pane: Default::default(),
1714 dispatching_keystrokes: Default::default(),
1715 window_edited: false,
1716 last_window_title: None,
1717 dirty_items: Default::default(),
1718 active_call,
1719 database_id: workspace_id,
1720 app_state,
1721 _observe_current_user,
1722 _apply_leader_updates,
1723 _schedule_serialize_workspace: None,
1724 _serialize_workspace_task: None,
1725 _schedule_serialize_ssh_paths: None,
1726 leader_updates_tx,
1727 _subscriptions: subscriptions,
1728 pane_history_timestamp,
1729 workspace_actions: Default::default(),
1730 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1731 bounds: Default::default(),
1732 centered_layout: false,
1733 bounds_save_task_queued: None,
1734 on_prompt_for_new_path: None,
1735 on_prompt_for_open_path: None,
1736 terminal_provider: None,
1737 debugger_provider: None,
1738 serializable_items_tx,
1739 _items_serializer,
1740 session_id: Some(session_id),
1741
1742 scheduled_tasks: Vec::new(),
1743 last_open_dock_positions: Vec::new(),
1744 removing: false,
1745 }
1746 }
1747
1748 pub fn new_local(
1749 abs_paths: Vec<PathBuf>,
1750 app_state: Arc<AppState>,
1751 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1752 env: Option<HashMap<String, String>>,
1753 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1754 activate: bool,
1755 cx: &mut App,
1756 ) -> Task<
1757 anyhow::Result<(
1758 WindowHandle<MultiWorkspace>,
1759 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
1760 )>,
1761 > {
1762 let project_handle = Project::local(
1763 app_state.client.clone(),
1764 app_state.node_runtime.clone(),
1765 app_state.user_store.clone(),
1766 app_state.languages.clone(),
1767 app_state.fs.clone(),
1768 env,
1769 Default::default(),
1770 cx,
1771 );
1772
1773 cx.spawn(async move |cx| {
1774 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1775 for path in abs_paths.into_iter() {
1776 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1777 paths_to_open.push(canonical)
1778 } else {
1779 paths_to_open.push(path)
1780 }
1781 }
1782
1783 let serialized_workspace =
1784 persistence::DB.workspace_for_roots(paths_to_open.as_slice());
1785
1786 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1787 paths_to_open = paths.ordered_paths().cloned().collect();
1788 if !paths.is_lexicographically_ordered() {
1789 project_handle.update(cx, |project, cx| {
1790 project.set_worktrees_reordered(true, cx);
1791 });
1792 }
1793 }
1794
1795 // Get project paths for all of the abs_paths
1796 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1797 Vec::with_capacity(paths_to_open.len());
1798
1799 for path in paths_to_open.into_iter() {
1800 if let Some((_, project_entry)) = cx
1801 .update(|cx| {
1802 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1803 })
1804 .await
1805 .log_err()
1806 {
1807 project_paths.push((path, Some(project_entry)));
1808 } else {
1809 project_paths.push((path, None));
1810 }
1811 }
1812
1813 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1814 serialized_workspace.id
1815 } else {
1816 DB.next_id().await.unwrap_or_else(|_| Default::default())
1817 };
1818
1819 let toolchains = DB.toolchains(workspace_id).await?;
1820
1821 for (toolchain, worktree_path, path) in toolchains {
1822 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1823 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1824 this.find_worktree(&worktree_path, cx)
1825 .and_then(|(worktree, rel_path)| {
1826 if rel_path.is_empty() {
1827 Some(worktree.read(cx).id())
1828 } else {
1829 None
1830 }
1831 })
1832 }) else {
1833 // We did not find a worktree with a given path, but that's whatever.
1834 continue;
1835 };
1836 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1837 continue;
1838 }
1839
1840 project_handle
1841 .update(cx, |this, cx| {
1842 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1843 })
1844 .await;
1845 }
1846 if let Some(workspace) = serialized_workspace.as_ref() {
1847 project_handle.update(cx, |this, cx| {
1848 for (scope, toolchains) in &workspace.user_toolchains {
1849 for toolchain in toolchains {
1850 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1851 }
1852 }
1853 });
1854 }
1855
1856 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1857 if let Some(window) = requesting_window {
1858 let centered_layout = serialized_workspace
1859 .as_ref()
1860 .map(|w| w.centered_layout)
1861 .unwrap_or(false);
1862
1863 let workspace = window.update(cx, |multi_workspace, window, cx| {
1864 let workspace = cx.new(|cx| {
1865 let mut workspace = Workspace::new(
1866 Some(workspace_id),
1867 project_handle.clone(),
1868 app_state.clone(),
1869 window,
1870 cx,
1871 );
1872
1873 workspace.centered_layout = centered_layout;
1874
1875 // Call init callback to add items before window renders
1876 if let Some(init) = init {
1877 init(&mut workspace, window, cx);
1878 }
1879
1880 workspace
1881 });
1882 if activate {
1883 multi_workspace.activate(workspace.clone(), cx);
1884 } else {
1885 multi_workspace.add_workspace(workspace.clone(), cx);
1886 }
1887 workspace
1888 })?;
1889 (window, workspace)
1890 } else {
1891 let window_bounds_override = window_bounds_env_override();
1892
1893 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1894 (Some(WindowBounds::Windowed(bounds)), None)
1895 } else if let Some(workspace) = serialized_workspace.as_ref()
1896 && let Some(display) = workspace.display
1897 && let Some(bounds) = workspace.window_bounds.as_ref()
1898 {
1899 // Reopening an existing workspace - restore its saved bounds
1900 (Some(bounds.0), Some(display))
1901 } else if let Some((display, bounds)) =
1902 persistence::read_default_window_bounds()
1903 {
1904 // New or empty workspace - use the last known window bounds
1905 (Some(bounds), Some(display))
1906 } else {
1907 // New window - let GPUI's default_bounds() handle cascading
1908 (None, None)
1909 };
1910
1911 // Use the serialized workspace to construct the new window
1912 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1913 options.window_bounds = window_bounds;
1914 let centered_layout = serialized_workspace
1915 .as_ref()
1916 .map(|w| w.centered_layout)
1917 .unwrap_or(false);
1918 let window = cx.open_window(options, {
1919 let app_state = app_state.clone();
1920 let project_handle = project_handle.clone();
1921 move |window, cx| {
1922 let workspace = cx.new(|cx| {
1923 let mut workspace = Workspace::new(
1924 Some(workspace_id),
1925 project_handle,
1926 app_state,
1927 window,
1928 cx,
1929 );
1930 workspace.centered_layout = centered_layout;
1931
1932 // Call init callback to add items before window renders
1933 if let Some(init) = init {
1934 init(&mut workspace, window, cx);
1935 }
1936
1937 workspace
1938 });
1939 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1940 }
1941 })?;
1942 let workspace =
1943 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
1944 multi_workspace.workspace().clone()
1945 })?;
1946 (window, workspace)
1947 };
1948
1949 notify_if_database_failed(window, cx);
1950 // Check if this is an empty workspace (no paths to open)
1951 // An empty workspace is one where project_paths is empty
1952 let is_empty_workspace = project_paths.is_empty();
1953 // Check if serialized workspace has paths before it's moved
1954 let serialized_workspace_has_paths = serialized_workspace
1955 .as_ref()
1956 .map(|ws| !ws.paths.is_empty())
1957 .unwrap_or(false);
1958
1959 let opened_items = window
1960 .update(cx, |_, window, cx| {
1961 workspace.update(cx, |_workspace: &mut Workspace, cx| {
1962 open_items(serialized_workspace, project_paths, window, cx)
1963 })
1964 })?
1965 .await
1966 .unwrap_or_default();
1967
1968 // Restore default dock state for empty workspaces
1969 // Only restore if:
1970 // 1. This is an empty workspace (no paths), AND
1971 // 2. The serialized workspace either doesn't exist or has no paths
1972 if is_empty_workspace && !serialized_workspace_has_paths {
1973 if let Some(default_docks) = persistence::read_default_dock_state() {
1974 window
1975 .update(cx, |_, window, cx| {
1976 workspace.update(cx, |workspace, cx| {
1977 for (dock, serialized_dock) in [
1978 (&workspace.right_dock, &default_docks.right),
1979 (&workspace.left_dock, &default_docks.left),
1980 (&workspace.bottom_dock, &default_docks.bottom),
1981 ] {
1982 dock.update(cx, |dock, cx| {
1983 dock.serialized_dock = Some(serialized_dock.clone());
1984 dock.restore_state(window, cx);
1985 });
1986 }
1987 cx.notify();
1988 });
1989 })
1990 .log_err();
1991 }
1992 }
1993
1994 window
1995 .update(cx, |_, _window, cx| {
1996 workspace.update(cx, |this: &mut Workspace, cx| {
1997 this.update_history(cx);
1998 });
1999 })
2000 .log_err();
2001 Ok((window, opened_items))
2002 })
2003 }
2004
2005 pub fn weak_handle(&self) -> WeakEntity<Self> {
2006 self.weak_self.clone()
2007 }
2008
2009 pub fn left_dock(&self) -> &Entity<Dock> {
2010 &self.left_dock
2011 }
2012
2013 pub fn bottom_dock(&self) -> &Entity<Dock> {
2014 &self.bottom_dock
2015 }
2016
2017 pub fn set_bottom_dock_layout(
2018 &mut self,
2019 layout: BottomDockLayout,
2020 window: &mut Window,
2021 cx: &mut Context<Self>,
2022 ) {
2023 let fs = self.project().read(cx).fs();
2024 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2025 content.workspace.bottom_dock_layout = Some(layout);
2026 });
2027
2028 cx.notify();
2029 self.serialize_workspace(window, cx);
2030 }
2031
2032 pub fn right_dock(&self) -> &Entity<Dock> {
2033 &self.right_dock
2034 }
2035
2036 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2037 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2038 }
2039
2040 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2041 let left_dock = self.left_dock.read(cx);
2042 let left_visible = left_dock.is_open();
2043 let left_active_panel = left_dock
2044 .active_panel()
2045 .map(|panel| panel.persistent_name().to_string());
2046 // `zoomed_position` is kept in sync with individual panel zoom state
2047 // by the dock code in `Dock::new` and `Dock::add_panel`.
2048 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2049
2050 let right_dock = self.right_dock.read(cx);
2051 let right_visible = right_dock.is_open();
2052 let right_active_panel = right_dock
2053 .active_panel()
2054 .map(|panel| panel.persistent_name().to_string());
2055 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2056
2057 let bottom_dock = self.bottom_dock.read(cx);
2058 let bottom_visible = bottom_dock.is_open();
2059 let bottom_active_panel = bottom_dock
2060 .active_panel()
2061 .map(|panel| panel.persistent_name().to_string());
2062 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2063
2064 DockStructure {
2065 left: DockData {
2066 visible: left_visible,
2067 active_panel: left_active_panel,
2068 zoom: left_dock_zoom,
2069 },
2070 right: DockData {
2071 visible: right_visible,
2072 active_panel: right_active_panel,
2073 zoom: right_dock_zoom,
2074 },
2075 bottom: DockData {
2076 visible: bottom_visible,
2077 active_panel: bottom_active_panel,
2078 zoom: bottom_dock_zoom,
2079 },
2080 }
2081 }
2082
2083 pub fn set_dock_structure(
2084 &self,
2085 docks: DockStructure,
2086 window: &mut Window,
2087 cx: &mut Context<Self>,
2088 ) {
2089 for (dock, data) in [
2090 (&self.left_dock, docks.left),
2091 (&self.bottom_dock, docks.bottom),
2092 (&self.right_dock, docks.right),
2093 ] {
2094 dock.update(cx, |dock, cx| {
2095 dock.serialized_dock = Some(data);
2096 dock.restore_state(window, cx);
2097 });
2098 }
2099 }
2100
2101 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2102 self.items(cx)
2103 .filter_map(|item| {
2104 let project_path = item.project_path(cx)?;
2105 self.project.read(cx).absolute_path(&project_path, cx)
2106 })
2107 .collect()
2108 }
2109
2110 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2111 match position {
2112 DockPosition::Left => &self.left_dock,
2113 DockPosition::Bottom => &self.bottom_dock,
2114 DockPosition::Right => &self.right_dock,
2115 }
2116 }
2117
2118 pub fn is_edited(&self) -> bool {
2119 self.window_edited
2120 }
2121
2122 pub fn add_panel<T: Panel>(
2123 &mut self,
2124 panel: Entity<T>,
2125 window: &mut Window,
2126 cx: &mut Context<Self>,
2127 ) {
2128 let focus_handle = panel.panel_focus_handle(cx);
2129 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2130 .detach();
2131
2132 let dock_position = panel.position(window, cx);
2133 let dock = self.dock_at_position(dock_position);
2134 let any_panel = panel.to_any();
2135
2136 dock.update(cx, |dock, cx| {
2137 dock.add_panel(panel, self.weak_self.clone(), window, cx)
2138 });
2139
2140 cx.emit(Event::PanelAdded(any_panel));
2141 }
2142
2143 pub fn remove_panel<T: Panel>(
2144 &mut self,
2145 panel: &Entity<T>,
2146 window: &mut Window,
2147 cx: &mut Context<Self>,
2148 ) {
2149 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2150 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2151 }
2152 }
2153
2154 pub fn status_bar(&self) -> &Entity<StatusBar> {
2155 &self.status_bar
2156 }
2157
2158 pub fn status_bar_visible(&self, cx: &App) -> bool {
2159 StatusBarSettings::get_global(cx).show
2160 }
2161
2162 pub fn app_state(&self) -> &Arc<AppState> {
2163 &self.app_state
2164 }
2165
2166 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2167 self._panels_task = Some(task);
2168 }
2169
2170 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2171 self._panels_task.take()
2172 }
2173
2174 pub fn user_store(&self) -> &Entity<UserStore> {
2175 &self.app_state.user_store
2176 }
2177
2178 pub fn project(&self) -> &Entity<Project> {
2179 &self.project
2180 }
2181
2182 pub fn path_style(&self, cx: &App) -> PathStyle {
2183 self.project.read(cx).path_style(cx)
2184 }
2185
2186 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2187 let mut history: HashMap<EntityId, usize> = HashMap::default();
2188
2189 for pane_handle in &self.panes {
2190 let pane = pane_handle.read(cx);
2191
2192 for entry in pane.activation_history() {
2193 history.insert(
2194 entry.entity_id,
2195 history
2196 .get(&entry.entity_id)
2197 .cloned()
2198 .unwrap_or(0)
2199 .max(entry.timestamp),
2200 );
2201 }
2202 }
2203
2204 history
2205 }
2206
2207 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2208 let mut recent_item: Option<Entity<T>> = None;
2209 let mut recent_timestamp = 0;
2210 for pane_handle in &self.panes {
2211 let pane = pane_handle.read(cx);
2212 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2213 pane.items().map(|item| (item.item_id(), item)).collect();
2214 for entry in pane.activation_history() {
2215 if entry.timestamp > recent_timestamp
2216 && let Some(&item) = item_map.get(&entry.entity_id)
2217 && let Some(typed_item) = item.act_as::<T>(cx)
2218 {
2219 recent_timestamp = entry.timestamp;
2220 recent_item = Some(typed_item);
2221 }
2222 }
2223 }
2224 recent_item
2225 }
2226
2227 pub fn recent_navigation_history_iter(
2228 &self,
2229 cx: &App,
2230 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2231 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2232 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2233
2234 for pane in &self.panes {
2235 let pane = pane.read(cx);
2236
2237 pane.nav_history()
2238 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2239 if let Some(fs_path) = &fs_path {
2240 abs_paths_opened
2241 .entry(fs_path.clone())
2242 .or_default()
2243 .insert(project_path.clone());
2244 }
2245 let timestamp = entry.timestamp;
2246 match history.entry(project_path) {
2247 hash_map::Entry::Occupied(mut entry) => {
2248 let (_, old_timestamp) = entry.get();
2249 if ×tamp > old_timestamp {
2250 entry.insert((fs_path, timestamp));
2251 }
2252 }
2253 hash_map::Entry::Vacant(entry) => {
2254 entry.insert((fs_path, timestamp));
2255 }
2256 }
2257 });
2258
2259 if let Some(item) = pane.active_item()
2260 && let Some(project_path) = item.project_path(cx)
2261 {
2262 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2263
2264 if let Some(fs_path) = &fs_path {
2265 abs_paths_opened
2266 .entry(fs_path.clone())
2267 .or_default()
2268 .insert(project_path.clone());
2269 }
2270
2271 history.insert(project_path, (fs_path, std::usize::MAX));
2272 }
2273 }
2274
2275 history
2276 .into_iter()
2277 .sorted_by_key(|(_, (_, order))| *order)
2278 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2279 .rev()
2280 .filter(move |(history_path, abs_path)| {
2281 let latest_project_path_opened = abs_path
2282 .as_ref()
2283 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2284 .and_then(|project_paths| {
2285 project_paths
2286 .iter()
2287 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2288 });
2289
2290 latest_project_path_opened.is_none_or(|path| path == history_path)
2291 })
2292 }
2293
2294 pub fn recent_navigation_history(
2295 &self,
2296 limit: Option<usize>,
2297 cx: &App,
2298 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2299 self.recent_navigation_history_iter(cx)
2300 .take(limit.unwrap_or(usize::MAX))
2301 .collect()
2302 }
2303
2304 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2305 for pane in &self.panes {
2306 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2307 }
2308 }
2309
2310 fn navigate_history(
2311 &mut self,
2312 pane: WeakEntity<Pane>,
2313 mode: NavigationMode,
2314 window: &mut Window,
2315 cx: &mut Context<Workspace>,
2316 ) -> Task<Result<()>> {
2317 self.navigate_history_impl(
2318 pane,
2319 mode,
2320 window,
2321 &mut |history, cx| history.pop(mode, cx),
2322 cx,
2323 )
2324 }
2325
2326 fn navigate_tag_history(
2327 &mut self,
2328 pane: WeakEntity<Pane>,
2329 mode: TagNavigationMode,
2330 window: &mut Window,
2331 cx: &mut Context<Workspace>,
2332 ) -> Task<Result<()>> {
2333 self.navigate_history_impl(
2334 pane,
2335 NavigationMode::Normal,
2336 window,
2337 &mut |history, _cx| history.pop_tag(mode),
2338 cx,
2339 )
2340 }
2341
2342 fn navigate_history_impl(
2343 &mut self,
2344 pane: WeakEntity<Pane>,
2345 mode: NavigationMode,
2346 window: &mut Window,
2347 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2348 cx: &mut Context<Workspace>,
2349 ) -> Task<Result<()>> {
2350 let to_load = if let Some(pane) = pane.upgrade() {
2351 pane.update(cx, |pane, cx| {
2352 window.focus(&pane.focus_handle(cx), cx);
2353 loop {
2354 // Retrieve the weak item handle from the history.
2355 let entry = cb(pane.nav_history_mut(), cx)?;
2356
2357 // If the item is still present in this pane, then activate it.
2358 if let Some(index) = entry
2359 .item
2360 .upgrade()
2361 .and_then(|v| pane.index_for_item(v.as_ref()))
2362 {
2363 let prev_active_item_index = pane.active_item_index();
2364 pane.nav_history_mut().set_mode(mode);
2365 pane.activate_item(index, true, true, window, cx);
2366 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2367
2368 let mut navigated = prev_active_item_index != pane.active_item_index();
2369 if let Some(data) = entry.data {
2370 navigated |= pane.active_item()?.navigate(data, window, cx);
2371 }
2372
2373 if navigated {
2374 break None;
2375 }
2376 } else {
2377 // If the item is no longer present in this pane, then retrieve its
2378 // path info in order to reopen it.
2379 break pane
2380 .nav_history()
2381 .path_for_item(entry.item.id())
2382 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2383 }
2384 }
2385 })
2386 } else {
2387 None
2388 };
2389
2390 if let Some((project_path, abs_path, entry)) = to_load {
2391 // If the item was no longer present, then load it again from its previous path, first try the local path
2392 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2393
2394 cx.spawn_in(window, async move |workspace, cx| {
2395 let open_by_project_path = open_by_project_path.await;
2396 let mut navigated = false;
2397 match open_by_project_path
2398 .with_context(|| format!("Navigating to {project_path:?}"))
2399 {
2400 Ok((project_entry_id, build_item)) => {
2401 let prev_active_item_id = pane.update(cx, |pane, _| {
2402 pane.nav_history_mut().set_mode(mode);
2403 pane.active_item().map(|p| p.item_id())
2404 })?;
2405
2406 pane.update_in(cx, |pane, window, cx| {
2407 let item = pane.open_item(
2408 project_entry_id,
2409 project_path,
2410 true,
2411 entry.is_preview,
2412 true,
2413 None,
2414 window, cx,
2415 build_item,
2416 );
2417 navigated |= Some(item.item_id()) != prev_active_item_id;
2418 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2419 if let Some(data) = entry.data {
2420 navigated |= item.navigate(data, window, cx);
2421 }
2422 })?;
2423 }
2424 Err(open_by_project_path_e) => {
2425 // Fall back to opening by abs path, in case an external file was opened and closed,
2426 // and its worktree is now dropped
2427 if let Some(abs_path) = abs_path {
2428 let prev_active_item_id = pane.update(cx, |pane, _| {
2429 pane.nav_history_mut().set_mode(mode);
2430 pane.active_item().map(|p| p.item_id())
2431 })?;
2432 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2433 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2434 })?;
2435 match open_by_abs_path
2436 .await
2437 .with_context(|| format!("Navigating to {abs_path:?}"))
2438 {
2439 Ok(item) => {
2440 pane.update_in(cx, |pane, window, cx| {
2441 navigated |= Some(item.item_id()) != prev_active_item_id;
2442 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2443 if let Some(data) = entry.data {
2444 navigated |= item.navigate(data, window, cx);
2445 }
2446 })?;
2447 }
2448 Err(open_by_abs_path_e) => {
2449 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2450 }
2451 }
2452 }
2453 }
2454 }
2455
2456 if !navigated {
2457 workspace
2458 .update_in(cx, |workspace, window, cx| {
2459 Self::navigate_history(workspace, pane, mode, window, cx)
2460 })?
2461 .await?;
2462 }
2463
2464 Ok(())
2465 })
2466 } else {
2467 Task::ready(Ok(()))
2468 }
2469 }
2470
2471 pub fn go_back(
2472 &mut self,
2473 pane: WeakEntity<Pane>,
2474 window: &mut Window,
2475 cx: &mut Context<Workspace>,
2476 ) -> Task<Result<()>> {
2477 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2478 }
2479
2480 pub fn go_forward(
2481 &mut self,
2482 pane: WeakEntity<Pane>,
2483 window: &mut Window,
2484 cx: &mut Context<Workspace>,
2485 ) -> Task<Result<()>> {
2486 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2487 }
2488
2489 pub fn reopen_closed_item(
2490 &mut self,
2491 window: &mut Window,
2492 cx: &mut Context<Workspace>,
2493 ) -> Task<Result<()>> {
2494 self.navigate_history(
2495 self.active_pane().downgrade(),
2496 NavigationMode::ReopeningClosedItem,
2497 window,
2498 cx,
2499 )
2500 }
2501
2502 pub fn client(&self) -> &Arc<Client> {
2503 &self.app_state.client
2504 }
2505
2506 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2507 self.titlebar_item = Some(item);
2508 cx.notify();
2509 }
2510
2511 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2512 self.on_prompt_for_new_path = Some(prompt)
2513 }
2514
2515 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2516 self.on_prompt_for_open_path = Some(prompt)
2517 }
2518
2519 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2520 self.terminal_provider = Some(Box::new(provider));
2521 }
2522
2523 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2524 self.debugger_provider = Some(Arc::new(provider));
2525 }
2526
2527 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2528 self.debugger_provider.clone()
2529 }
2530
2531 pub fn prompt_for_open_path(
2532 &mut self,
2533 path_prompt_options: PathPromptOptions,
2534 lister: DirectoryLister,
2535 window: &mut Window,
2536 cx: &mut Context<Self>,
2537 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2538 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2539 let prompt = self.on_prompt_for_open_path.take().unwrap();
2540 let rx = prompt(self, lister, window, cx);
2541 self.on_prompt_for_open_path = Some(prompt);
2542 rx
2543 } else {
2544 let (tx, rx) = oneshot::channel();
2545 let abs_path = cx.prompt_for_paths(path_prompt_options);
2546
2547 cx.spawn_in(window, async move |workspace, cx| {
2548 let Ok(result) = abs_path.await else {
2549 return Ok(());
2550 };
2551
2552 match result {
2553 Ok(result) => {
2554 tx.send(result).ok();
2555 }
2556 Err(err) => {
2557 let rx = workspace.update_in(cx, |workspace, window, cx| {
2558 workspace.show_portal_error(err.to_string(), cx);
2559 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2560 let rx = prompt(workspace, lister, window, cx);
2561 workspace.on_prompt_for_open_path = Some(prompt);
2562 rx
2563 })?;
2564 if let Ok(path) = rx.await {
2565 tx.send(path).ok();
2566 }
2567 }
2568 };
2569 anyhow::Ok(())
2570 })
2571 .detach();
2572
2573 rx
2574 }
2575 }
2576
2577 pub fn prompt_for_new_path(
2578 &mut self,
2579 lister: DirectoryLister,
2580 suggested_name: Option<String>,
2581 window: &mut Window,
2582 cx: &mut Context<Self>,
2583 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2584 if self.project.read(cx).is_via_collab()
2585 || self.project.read(cx).is_via_remote_server()
2586 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2587 {
2588 let prompt = self.on_prompt_for_new_path.take().unwrap();
2589 let rx = prompt(self, lister, suggested_name, window, cx);
2590 self.on_prompt_for_new_path = Some(prompt);
2591 return rx;
2592 }
2593
2594 let (tx, rx) = oneshot::channel();
2595 cx.spawn_in(window, async move |workspace, cx| {
2596 let abs_path = workspace.update(cx, |workspace, cx| {
2597 let relative_to = workspace
2598 .most_recent_active_path(cx)
2599 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2600 .or_else(|| {
2601 let project = workspace.project.read(cx);
2602 project.visible_worktrees(cx).find_map(|worktree| {
2603 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2604 })
2605 })
2606 .or_else(std::env::home_dir)
2607 .unwrap_or_else(|| PathBuf::from(""));
2608 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2609 })?;
2610 let abs_path = match abs_path.await? {
2611 Ok(path) => path,
2612 Err(err) => {
2613 let rx = workspace.update_in(cx, |workspace, window, cx| {
2614 workspace.show_portal_error(err.to_string(), cx);
2615
2616 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2617 let rx = prompt(workspace, lister, suggested_name, window, cx);
2618 workspace.on_prompt_for_new_path = Some(prompt);
2619 rx
2620 })?;
2621 if let Ok(path) = rx.await {
2622 tx.send(path).ok();
2623 }
2624 return anyhow::Ok(());
2625 }
2626 };
2627
2628 tx.send(abs_path.map(|path| vec![path])).ok();
2629 anyhow::Ok(())
2630 })
2631 .detach();
2632
2633 rx
2634 }
2635
2636 pub fn titlebar_item(&self) -> Option<AnyView> {
2637 self.titlebar_item.clone()
2638 }
2639
2640 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2641 /// When set, git-related operations should use this worktree instead of deriving
2642 /// the active worktree from the focused file.
2643 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2644 self.active_worktree_override
2645 }
2646
2647 pub fn set_active_worktree_override(
2648 &mut self,
2649 worktree_id: Option<WorktreeId>,
2650 cx: &mut Context<Self>,
2651 ) {
2652 self.active_worktree_override = worktree_id;
2653 cx.notify();
2654 }
2655
2656 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2657 self.active_worktree_override = None;
2658 cx.notify();
2659 }
2660
2661 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2662 ///
2663 /// If the given workspace has a local project, then it will be passed
2664 /// to the callback. Otherwise, a new empty window will be created.
2665 pub fn with_local_workspace<T, F>(
2666 &mut self,
2667 window: &mut Window,
2668 cx: &mut Context<Self>,
2669 callback: F,
2670 ) -> Task<Result<T>>
2671 where
2672 T: 'static,
2673 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2674 {
2675 if self.project.read(cx).is_local() {
2676 Task::ready(Ok(callback(self, window, cx)))
2677 } else {
2678 let env = self.project.read(cx).cli_environment(cx);
2679 let task = Self::new_local(
2680 Vec::new(),
2681 self.app_state.clone(),
2682 None,
2683 env,
2684 None,
2685 true,
2686 cx,
2687 );
2688 cx.spawn_in(window, async move |_vh, cx| {
2689 let (multi_workspace_window, _) = task.await?;
2690 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2691 let workspace = multi_workspace.workspace().clone();
2692 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2693 })
2694 })
2695 }
2696 }
2697
2698 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2699 ///
2700 /// If the given workspace has a local project, then it will be passed
2701 /// to the callback. Otherwise, a new empty window will be created.
2702 pub fn with_local_or_wsl_workspace<T, F>(
2703 &mut self,
2704 window: &mut Window,
2705 cx: &mut Context<Self>,
2706 callback: F,
2707 ) -> Task<Result<T>>
2708 where
2709 T: 'static,
2710 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2711 {
2712 let project = self.project.read(cx);
2713 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
2714 Task::ready(Ok(callback(self, window, cx)))
2715 } else {
2716 let env = self.project.read(cx).cli_environment(cx);
2717 let task = Self::new_local(
2718 Vec::new(),
2719 self.app_state.clone(),
2720 None,
2721 env,
2722 None,
2723 true,
2724 cx,
2725 );
2726 cx.spawn_in(window, async move |_vh, cx| {
2727 let (multi_workspace_window, _) = task.await?;
2728 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2729 let workspace = multi_workspace.workspace().clone();
2730 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2731 })
2732 })
2733 }
2734 }
2735
2736 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2737 self.project.read(cx).worktrees(cx)
2738 }
2739
2740 pub fn visible_worktrees<'a>(
2741 &self,
2742 cx: &'a App,
2743 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2744 self.project.read(cx).visible_worktrees(cx)
2745 }
2746
2747 #[cfg(any(test, feature = "test-support"))]
2748 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
2749 let futures = self
2750 .worktrees(cx)
2751 .filter_map(|worktree| worktree.read(cx).as_local())
2752 .map(|worktree| worktree.scan_complete())
2753 .collect::<Vec<_>>();
2754 async move {
2755 for future in futures {
2756 future.await;
2757 }
2758 }
2759 }
2760
2761 pub fn close_global(cx: &mut App) {
2762 cx.defer(|cx| {
2763 cx.windows().iter().find(|window| {
2764 window
2765 .update(cx, |_, window, _| {
2766 if window.is_window_active() {
2767 //This can only get called when the window's project connection has been lost
2768 //so we don't need to prompt the user for anything and instead just close the window
2769 window.remove_window();
2770 true
2771 } else {
2772 false
2773 }
2774 })
2775 .unwrap_or(false)
2776 });
2777 });
2778 }
2779
2780 pub fn move_focused_panel_to_next_position(
2781 &mut self,
2782 _: &MoveFocusedPanelToNextPosition,
2783 window: &mut Window,
2784 cx: &mut Context<Self>,
2785 ) {
2786 let docks = self.all_docks();
2787 let active_dock = docks
2788 .into_iter()
2789 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
2790
2791 if let Some(dock) = active_dock {
2792 dock.update(cx, |dock, cx| {
2793 let active_panel = dock
2794 .active_panel()
2795 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
2796
2797 if let Some(panel) = active_panel {
2798 panel.move_to_next_position(window, cx);
2799 }
2800 })
2801 }
2802 }
2803
2804 pub fn prepare_to_close(
2805 &mut self,
2806 close_intent: CloseIntent,
2807 window: &mut Window,
2808 cx: &mut Context<Self>,
2809 ) -> Task<Result<bool>> {
2810 let active_call = self.active_global_call();
2811
2812 cx.spawn_in(window, async move |this, cx| {
2813 this.update(cx, |this, _| {
2814 if close_intent == CloseIntent::CloseWindow {
2815 this.removing = true;
2816 }
2817 })?;
2818
2819 let workspace_count = cx.update(|_window, cx| {
2820 cx.windows()
2821 .iter()
2822 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
2823 .count()
2824 })?;
2825
2826 #[cfg(target_os = "macos")]
2827 let save_last_workspace = false;
2828
2829 // On Linux and Windows, closing the last window should restore the last workspace.
2830 #[cfg(not(target_os = "macos"))]
2831 let save_last_workspace = {
2832 let remaining_workspaces = cx.update(|_window, cx| {
2833 cx.windows()
2834 .iter()
2835 .filter_map(|window| window.downcast::<MultiWorkspace>())
2836 .filter_map(|multi_workspace| {
2837 multi_workspace
2838 .update(cx, |multi_workspace, _, cx| {
2839 multi_workspace.workspace().read(cx).removing
2840 })
2841 .ok()
2842 })
2843 .filter(|removing| !removing)
2844 .count()
2845 })?;
2846
2847 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
2848 };
2849
2850 if let Some(active_call) = active_call
2851 && workspace_count == 1
2852 && cx
2853 .update(|_window, cx| active_call.0.is_in_room(cx))
2854 .unwrap_or(false)
2855 {
2856 if close_intent == CloseIntent::CloseWindow {
2857 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
2858 let answer = cx.update(|window, cx| {
2859 window.prompt(
2860 PromptLevel::Warning,
2861 "Do you want to leave the current call?",
2862 None,
2863 &["Close window and hang up", "Cancel"],
2864 cx,
2865 )
2866 })?;
2867
2868 if answer.await.log_err() == Some(1) {
2869 return anyhow::Ok(false);
2870 } else {
2871 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
2872 task.await.log_err();
2873 }
2874 }
2875 }
2876 if close_intent == CloseIntent::ReplaceWindow {
2877 _ = cx.update(|_window, cx| {
2878 let multi_workspace = cx
2879 .windows()
2880 .iter()
2881 .filter_map(|window| window.downcast::<MultiWorkspace>())
2882 .next()
2883 .unwrap();
2884 let project = multi_workspace
2885 .read(cx)?
2886 .workspace()
2887 .read(cx)
2888 .project
2889 .clone();
2890 if project.read(cx).is_shared() {
2891 active_call.0.unshare_project(project, cx)?;
2892 }
2893 Ok::<_, anyhow::Error>(())
2894 });
2895 }
2896 }
2897
2898 let save_result = this
2899 .update_in(cx, |this, window, cx| {
2900 this.save_all_internal(SaveIntent::Close, window, cx)
2901 })?
2902 .await;
2903
2904 // If we're not quitting, but closing, we remove the workspace from
2905 // the current session.
2906 if close_intent != CloseIntent::Quit
2907 && !save_last_workspace
2908 && save_result.as_ref().is_ok_and(|&res| res)
2909 {
2910 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
2911 .await;
2912 }
2913
2914 save_result
2915 })
2916 }
2917
2918 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
2919 self.save_all_internal(
2920 action.save_intent.unwrap_or(SaveIntent::SaveAll),
2921 window,
2922 cx,
2923 )
2924 .detach_and_log_err(cx);
2925 }
2926
2927 fn send_keystrokes(
2928 &mut self,
2929 action: &SendKeystrokes,
2930 window: &mut Window,
2931 cx: &mut Context<Self>,
2932 ) {
2933 let keystrokes: Vec<Keystroke> = action
2934 .0
2935 .split(' ')
2936 .flat_map(|k| Keystroke::parse(k).log_err())
2937 .map(|k| {
2938 cx.keyboard_mapper()
2939 .map_key_equivalent(k, false)
2940 .inner()
2941 .clone()
2942 })
2943 .collect();
2944 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
2945 }
2946
2947 pub fn send_keystrokes_impl(
2948 &mut self,
2949 keystrokes: Vec<Keystroke>,
2950 window: &mut Window,
2951 cx: &mut Context<Self>,
2952 ) -> Shared<Task<()>> {
2953 let mut state = self.dispatching_keystrokes.borrow_mut();
2954 if !state.dispatched.insert(keystrokes.clone()) {
2955 cx.propagate();
2956 return state.task.clone().unwrap();
2957 }
2958
2959 state.queue.extend(keystrokes);
2960
2961 let keystrokes = self.dispatching_keystrokes.clone();
2962 if state.task.is_none() {
2963 state.task = Some(
2964 window
2965 .spawn(cx, async move |cx| {
2966 // limit to 100 keystrokes to avoid infinite recursion.
2967 for _ in 0..100 {
2968 let keystroke = {
2969 let mut state = keystrokes.borrow_mut();
2970 let Some(keystroke) = state.queue.pop_front() else {
2971 state.dispatched.clear();
2972 state.task.take();
2973 return;
2974 };
2975 keystroke
2976 };
2977 cx.update(|window, cx| {
2978 let focused = window.focused(cx);
2979 window.dispatch_keystroke(keystroke.clone(), cx);
2980 if window.focused(cx) != focused {
2981 // dispatch_keystroke may cause the focus to change.
2982 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
2983 // And we need that to happen before the next keystroke to keep vim mode happy...
2984 // (Note that the tests always do this implicitly, so you must manually test with something like:
2985 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
2986 // )
2987 window.draw(cx).clear();
2988 }
2989 })
2990 .ok();
2991
2992 // Yield between synthetic keystrokes so deferred focus and
2993 // other effects can settle before dispatching the next key.
2994 yield_now().await;
2995 }
2996
2997 *keystrokes.borrow_mut() = Default::default();
2998 log::error!("over 100 keystrokes passed to send_keystrokes");
2999 })
3000 .shared(),
3001 );
3002 }
3003 state.task.clone().unwrap()
3004 }
3005
3006 fn save_all_internal(
3007 &mut self,
3008 mut save_intent: SaveIntent,
3009 window: &mut Window,
3010 cx: &mut Context<Self>,
3011 ) -> Task<Result<bool>> {
3012 if self.project.read(cx).is_disconnected(cx) {
3013 return Task::ready(Ok(true));
3014 }
3015 let dirty_items = self
3016 .panes
3017 .iter()
3018 .flat_map(|pane| {
3019 pane.read(cx).items().filter_map(|item| {
3020 if item.is_dirty(cx) {
3021 item.tab_content_text(0, cx);
3022 Some((pane.downgrade(), item.boxed_clone()))
3023 } else {
3024 None
3025 }
3026 })
3027 })
3028 .collect::<Vec<_>>();
3029
3030 let project = self.project.clone();
3031 cx.spawn_in(window, async move |workspace, cx| {
3032 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3033 let (serialize_tasks, remaining_dirty_items) =
3034 workspace.update_in(cx, |workspace, window, cx| {
3035 let mut remaining_dirty_items = Vec::new();
3036 let mut serialize_tasks = Vec::new();
3037 for (pane, item) in dirty_items {
3038 if let Some(task) = item
3039 .to_serializable_item_handle(cx)
3040 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3041 {
3042 serialize_tasks.push(task);
3043 } else {
3044 remaining_dirty_items.push((pane, item));
3045 }
3046 }
3047 (serialize_tasks, remaining_dirty_items)
3048 })?;
3049
3050 futures::future::try_join_all(serialize_tasks).await?;
3051
3052 if !remaining_dirty_items.is_empty() {
3053 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3054 }
3055
3056 if remaining_dirty_items.len() > 1 {
3057 let answer = workspace.update_in(cx, |_, window, cx| {
3058 let detail = Pane::file_names_for_prompt(
3059 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3060 cx,
3061 );
3062 window.prompt(
3063 PromptLevel::Warning,
3064 "Do you want to save all changes in the following files?",
3065 Some(&detail),
3066 &["Save all", "Discard all", "Cancel"],
3067 cx,
3068 )
3069 })?;
3070 match answer.await.log_err() {
3071 Some(0) => save_intent = SaveIntent::SaveAll,
3072 Some(1) => save_intent = SaveIntent::Skip,
3073 Some(2) => return Ok(false),
3074 _ => {}
3075 }
3076 }
3077
3078 remaining_dirty_items
3079 } else {
3080 dirty_items
3081 };
3082
3083 for (pane, item) in dirty_items {
3084 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3085 (
3086 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3087 item.project_entry_ids(cx),
3088 )
3089 })?;
3090 if (singleton || !project_entry_ids.is_empty())
3091 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3092 {
3093 return Ok(false);
3094 }
3095 }
3096 Ok(true)
3097 })
3098 }
3099
3100 pub fn open_workspace_for_paths(
3101 &mut self,
3102 replace_current_window: bool,
3103 paths: Vec<PathBuf>,
3104 window: &mut Window,
3105 cx: &mut Context<Self>,
3106 ) -> Task<Result<()>> {
3107 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
3108 let is_remote = self.project.read(cx).is_via_collab();
3109 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3110 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3111
3112 let window_to_replace = if replace_current_window {
3113 window_handle
3114 } else if is_remote || has_worktree || has_dirty_items {
3115 None
3116 } else {
3117 window_handle
3118 };
3119 let app_state = self.app_state.clone();
3120
3121 cx.spawn(async move |_, cx| {
3122 cx.update(|cx| {
3123 open_paths(
3124 &paths,
3125 app_state,
3126 OpenOptions {
3127 replace_window: window_to_replace,
3128 ..Default::default()
3129 },
3130 cx,
3131 )
3132 })
3133 .await?;
3134 Ok(())
3135 })
3136 }
3137
3138 #[allow(clippy::type_complexity)]
3139 pub fn open_paths(
3140 &mut self,
3141 mut abs_paths: Vec<PathBuf>,
3142 options: OpenOptions,
3143 pane: Option<WeakEntity<Pane>>,
3144 window: &mut Window,
3145 cx: &mut Context<Self>,
3146 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3147 let fs = self.app_state.fs.clone();
3148
3149 let caller_ordered_abs_paths = abs_paths.clone();
3150
3151 // Sort the paths to ensure we add worktrees for parents before their children.
3152 abs_paths.sort_unstable();
3153 cx.spawn_in(window, async move |this, cx| {
3154 let mut tasks = Vec::with_capacity(abs_paths.len());
3155
3156 for abs_path in &abs_paths {
3157 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3158 OpenVisible::All => Some(true),
3159 OpenVisible::None => Some(false),
3160 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3161 Some(Some(metadata)) => Some(!metadata.is_dir),
3162 Some(None) => Some(true),
3163 None => None,
3164 },
3165 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3166 Some(Some(metadata)) => Some(metadata.is_dir),
3167 Some(None) => Some(false),
3168 None => None,
3169 },
3170 };
3171 let project_path = match visible {
3172 Some(visible) => match this
3173 .update(cx, |this, cx| {
3174 Workspace::project_path_for_path(
3175 this.project.clone(),
3176 abs_path,
3177 visible,
3178 cx,
3179 )
3180 })
3181 .log_err()
3182 {
3183 Some(project_path) => project_path.await.log_err(),
3184 None => None,
3185 },
3186 None => None,
3187 };
3188
3189 let this = this.clone();
3190 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3191 let fs = fs.clone();
3192 let pane = pane.clone();
3193 let task = cx.spawn(async move |cx| {
3194 let (_worktree, project_path) = project_path?;
3195 if fs.is_dir(&abs_path).await {
3196 // Opening a directory should not race to update the active entry.
3197 // We'll select/reveal a deterministic final entry after all paths finish opening.
3198 None
3199 } else {
3200 Some(
3201 this.update_in(cx, |this, window, cx| {
3202 this.open_path(
3203 project_path,
3204 pane,
3205 options.focus.unwrap_or(true),
3206 window,
3207 cx,
3208 )
3209 })
3210 .ok()?
3211 .await,
3212 )
3213 }
3214 });
3215 tasks.push(task);
3216 }
3217
3218 let results = futures::future::join_all(tasks).await;
3219
3220 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3221 let mut winner: Option<(PathBuf, bool)> = None;
3222 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3223 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3224 if !metadata.is_dir {
3225 winner = Some((abs_path, false));
3226 break;
3227 }
3228 if winner.is_none() {
3229 winner = Some((abs_path, true));
3230 }
3231 } else if winner.is_none() {
3232 winner = Some((abs_path, false));
3233 }
3234 }
3235
3236 // Compute the winner entry id on the foreground thread and emit once, after all
3237 // paths finish opening. This avoids races between concurrently-opening paths
3238 // (directories in particular) and makes the resulting project panel selection
3239 // deterministic.
3240 if let Some((winner_abs_path, winner_is_dir)) = winner {
3241 'emit_winner: {
3242 let winner_abs_path: Arc<Path> =
3243 SanitizedPath::new(&winner_abs_path).as_path().into();
3244
3245 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3246 OpenVisible::All => true,
3247 OpenVisible::None => false,
3248 OpenVisible::OnlyFiles => !winner_is_dir,
3249 OpenVisible::OnlyDirectories => winner_is_dir,
3250 };
3251
3252 let Some(worktree_task) = this
3253 .update(cx, |workspace, cx| {
3254 workspace.project.update(cx, |project, cx| {
3255 project.find_or_create_worktree(
3256 winner_abs_path.as_ref(),
3257 visible,
3258 cx,
3259 )
3260 })
3261 })
3262 .ok()
3263 else {
3264 break 'emit_winner;
3265 };
3266
3267 let Ok((worktree, _)) = worktree_task.await else {
3268 break 'emit_winner;
3269 };
3270
3271 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3272 let worktree = worktree.read(cx);
3273 let worktree_abs_path = worktree.abs_path();
3274 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3275 worktree.root_entry()
3276 } else {
3277 winner_abs_path
3278 .strip_prefix(worktree_abs_path.as_ref())
3279 .ok()
3280 .and_then(|relative_path| {
3281 let relative_path =
3282 RelPath::new(relative_path, PathStyle::local())
3283 .log_err()?;
3284 worktree.entry_for_path(&relative_path)
3285 })
3286 }?;
3287 Some(entry.id)
3288 }) else {
3289 break 'emit_winner;
3290 };
3291
3292 this.update(cx, |workspace, cx| {
3293 workspace.project.update(cx, |_, cx| {
3294 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3295 });
3296 })
3297 .ok();
3298 }
3299 }
3300
3301 results
3302 })
3303 }
3304
3305 pub fn open_resolved_path(
3306 &mut self,
3307 path: ResolvedPath,
3308 window: &mut Window,
3309 cx: &mut Context<Self>,
3310 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3311 match path {
3312 ResolvedPath::ProjectPath { project_path, .. } => {
3313 self.open_path(project_path, None, true, window, cx)
3314 }
3315 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3316 PathBuf::from(path),
3317 OpenOptions {
3318 visible: Some(OpenVisible::None),
3319 ..Default::default()
3320 },
3321 window,
3322 cx,
3323 ),
3324 }
3325 }
3326
3327 pub fn absolute_path_of_worktree(
3328 &self,
3329 worktree_id: WorktreeId,
3330 cx: &mut Context<Self>,
3331 ) -> Option<PathBuf> {
3332 self.project
3333 .read(cx)
3334 .worktree_for_id(worktree_id, cx)
3335 // TODO: use `abs_path` or `root_dir`
3336 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3337 }
3338
3339 fn add_folder_to_project(
3340 &mut self,
3341 _: &AddFolderToProject,
3342 window: &mut Window,
3343 cx: &mut Context<Self>,
3344 ) {
3345 let project = self.project.read(cx);
3346 if project.is_via_collab() {
3347 self.show_error(
3348 &anyhow!("You cannot add folders to someone else's project"),
3349 cx,
3350 );
3351 return;
3352 }
3353 let paths = self.prompt_for_open_path(
3354 PathPromptOptions {
3355 files: false,
3356 directories: true,
3357 multiple: true,
3358 prompt: None,
3359 },
3360 DirectoryLister::Project(self.project.clone()),
3361 window,
3362 cx,
3363 );
3364 cx.spawn_in(window, async move |this, cx| {
3365 if let Some(paths) = paths.await.log_err().flatten() {
3366 let results = this
3367 .update_in(cx, |this, window, cx| {
3368 this.open_paths(
3369 paths,
3370 OpenOptions {
3371 visible: Some(OpenVisible::All),
3372 ..Default::default()
3373 },
3374 None,
3375 window,
3376 cx,
3377 )
3378 })?
3379 .await;
3380 for result in results.into_iter().flatten() {
3381 result.log_err();
3382 }
3383 }
3384 anyhow::Ok(())
3385 })
3386 .detach_and_log_err(cx);
3387 }
3388
3389 pub fn project_path_for_path(
3390 project: Entity<Project>,
3391 abs_path: &Path,
3392 visible: bool,
3393 cx: &mut App,
3394 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3395 let entry = project.update(cx, |project, cx| {
3396 project.find_or_create_worktree(abs_path, visible, cx)
3397 });
3398 cx.spawn(async move |cx| {
3399 let (worktree, path) = entry.await?;
3400 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3401 Ok((worktree, ProjectPath { worktree_id, path }))
3402 })
3403 }
3404
3405 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3406 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3407 }
3408
3409 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3410 self.items_of_type(cx).max_by_key(|item| item.item_id())
3411 }
3412
3413 pub fn items_of_type<'a, T: Item>(
3414 &'a self,
3415 cx: &'a App,
3416 ) -> impl 'a + Iterator<Item = Entity<T>> {
3417 self.panes
3418 .iter()
3419 .flat_map(|pane| pane.read(cx).items_of_type())
3420 }
3421
3422 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3423 self.active_pane().read(cx).active_item()
3424 }
3425
3426 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3427 let item = self.active_item(cx)?;
3428 item.to_any_view().downcast::<I>().ok()
3429 }
3430
3431 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3432 self.active_item(cx).and_then(|item| item.project_path(cx))
3433 }
3434
3435 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3436 self.recent_navigation_history_iter(cx)
3437 .filter_map(|(path, abs_path)| {
3438 let worktree = self
3439 .project
3440 .read(cx)
3441 .worktree_for_id(path.worktree_id, cx)?;
3442 if worktree.read(cx).is_visible() {
3443 abs_path
3444 } else {
3445 None
3446 }
3447 })
3448 .next()
3449 }
3450
3451 pub fn save_active_item(
3452 &mut self,
3453 save_intent: SaveIntent,
3454 window: &mut Window,
3455 cx: &mut App,
3456 ) -> Task<Result<()>> {
3457 let project = self.project.clone();
3458 let pane = self.active_pane();
3459 let item = pane.read(cx).active_item();
3460 let pane = pane.downgrade();
3461
3462 window.spawn(cx, async move |cx| {
3463 if let Some(item) = item {
3464 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3465 .await
3466 .map(|_| ())
3467 } else {
3468 Ok(())
3469 }
3470 })
3471 }
3472
3473 pub fn close_inactive_items_and_panes(
3474 &mut self,
3475 action: &CloseInactiveTabsAndPanes,
3476 window: &mut Window,
3477 cx: &mut Context<Self>,
3478 ) {
3479 if let Some(task) = self.close_all_internal(
3480 true,
3481 action.save_intent.unwrap_or(SaveIntent::Close),
3482 window,
3483 cx,
3484 ) {
3485 task.detach_and_log_err(cx)
3486 }
3487 }
3488
3489 pub fn close_all_items_and_panes(
3490 &mut self,
3491 action: &CloseAllItemsAndPanes,
3492 window: &mut Window,
3493 cx: &mut Context<Self>,
3494 ) {
3495 if let Some(task) = self.close_all_internal(
3496 false,
3497 action.save_intent.unwrap_or(SaveIntent::Close),
3498 window,
3499 cx,
3500 ) {
3501 task.detach_and_log_err(cx)
3502 }
3503 }
3504
3505 /// Closes the active item across all panes.
3506 pub fn close_item_in_all_panes(
3507 &mut self,
3508 action: &CloseItemInAllPanes,
3509 window: &mut Window,
3510 cx: &mut Context<Self>,
3511 ) {
3512 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3513 return;
3514 };
3515
3516 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3517 let close_pinned = action.close_pinned;
3518
3519 if let Some(project_path) = active_item.project_path(cx) {
3520 self.close_items_with_project_path(
3521 &project_path,
3522 save_intent,
3523 close_pinned,
3524 window,
3525 cx,
3526 );
3527 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3528 let item_id = active_item.item_id();
3529 self.active_pane().update(cx, |pane, cx| {
3530 pane.close_item_by_id(item_id, save_intent, window, cx)
3531 .detach_and_log_err(cx);
3532 });
3533 }
3534 }
3535
3536 /// Closes all items with the given project path across all panes.
3537 pub fn close_items_with_project_path(
3538 &mut self,
3539 project_path: &ProjectPath,
3540 save_intent: SaveIntent,
3541 close_pinned: bool,
3542 window: &mut Window,
3543 cx: &mut Context<Self>,
3544 ) {
3545 let panes = self.panes().to_vec();
3546 for pane in panes {
3547 pane.update(cx, |pane, cx| {
3548 pane.close_items_for_project_path(
3549 project_path,
3550 save_intent,
3551 close_pinned,
3552 window,
3553 cx,
3554 )
3555 .detach_and_log_err(cx);
3556 });
3557 }
3558 }
3559
3560 fn close_all_internal(
3561 &mut self,
3562 retain_active_pane: bool,
3563 save_intent: SaveIntent,
3564 window: &mut Window,
3565 cx: &mut Context<Self>,
3566 ) -> Option<Task<Result<()>>> {
3567 let current_pane = self.active_pane();
3568
3569 let mut tasks = Vec::new();
3570
3571 if retain_active_pane {
3572 let current_pane_close = current_pane.update(cx, |pane, cx| {
3573 pane.close_other_items(
3574 &CloseOtherItems {
3575 save_intent: None,
3576 close_pinned: false,
3577 },
3578 None,
3579 window,
3580 cx,
3581 )
3582 });
3583
3584 tasks.push(current_pane_close);
3585 }
3586
3587 for pane in self.panes() {
3588 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3589 continue;
3590 }
3591
3592 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3593 pane.close_all_items(
3594 &CloseAllItems {
3595 save_intent: Some(save_intent),
3596 close_pinned: false,
3597 },
3598 window,
3599 cx,
3600 )
3601 });
3602
3603 tasks.push(close_pane_items)
3604 }
3605
3606 if tasks.is_empty() {
3607 None
3608 } else {
3609 Some(cx.spawn_in(window, async move |_, _| {
3610 for task in tasks {
3611 task.await?
3612 }
3613 Ok(())
3614 }))
3615 }
3616 }
3617
3618 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3619 self.dock_at_position(position).read(cx).is_open()
3620 }
3621
3622 pub fn toggle_dock(
3623 &mut self,
3624 dock_side: DockPosition,
3625 window: &mut Window,
3626 cx: &mut Context<Self>,
3627 ) {
3628 let mut focus_center = false;
3629 let mut reveal_dock = false;
3630
3631 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3632 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3633
3634 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3635 telemetry::event!(
3636 "Panel Button Clicked",
3637 name = panel.persistent_name(),
3638 toggle_state = !was_visible
3639 );
3640 }
3641 if was_visible {
3642 self.save_open_dock_positions(cx);
3643 }
3644
3645 let dock = self.dock_at_position(dock_side);
3646 dock.update(cx, |dock, cx| {
3647 dock.set_open(!was_visible, window, cx);
3648
3649 if dock.active_panel().is_none() {
3650 let Some(panel_ix) = dock
3651 .first_enabled_panel_idx(cx)
3652 .log_with_level(log::Level::Info)
3653 else {
3654 return;
3655 };
3656 dock.activate_panel(panel_ix, window, cx);
3657 }
3658
3659 if let Some(active_panel) = dock.active_panel() {
3660 if was_visible {
3661 if active_panel
3662 .panel_focus_handle(cx)
3663 .contains_focused(window, cx)
3664 {
3665 focus_center = true;
3666 }
3667 } else {
3668 let focus_handle = &active_panel.panel_focus_handle(cx);
3669 window.focus(focus_handle, cx);
3670 reveal_dock = true;
3671 }
3672 }
3673 });
3674
3675 if reveal_dock {
3676 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3677 }
3678
3679 if focus_center {
3680 self.active_pane
3681 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3682 }
3683
3684 cx.notify();
3685 self.serialize_workspace(window, cx);
3686 }
3687
3688 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3689 self.all_docks().into_iter().find(|&dock| {
3690 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3691 })
3692 }
3693
3694 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3695 if let Some(dock) = self.active_dock(window, cx).cloned() {
3696 self.save_open_dock_positions(cx);
3697 dock.update(cx, |dock, cx| {
3698 dock.set_open(false, window, cx);
3699 });
3700 return true;
3701 }
3702 false
3703 }
3704
3705 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3706 self.save_open_dock_positions(cx);
3707 for dock in self.all_docks() {
3708 dock.update(cx, |dock, cx| {
3709 dock.set_open(false, window, cx);
3710 });
3711 }
3712
3713 cx.focus_self(window);
3714 cx.notify();
3715 self.serialize_workspace(window, cx);
3716 }
3717
3718 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
3719 self.all_docks()
3720 .into_iter()
3721 .filter_map(|dock| {
3722 let dock_ref = dock.read(cx);
3723 if dock_ref.is_open() {
3724 Some(dock_ref.position())
3725 } else {
3726 None
3727 }
3728 })
3729 .collect()
3730 }
3731
3732 /// Saves the positions of currently open docks.
3733 ///
3734 /// Updates `last_open_dock_positions` with positions of all currently open
3735 /// docks, to later be restored by the 'Toggle All Docks' action.
3736 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
3737 let open_dock_positions = self.get_open_dock_positions(cx);
3738 if !open_dock_positions.is_empty() {
3739 self.last_open_dock_positions = open_dock_positions;
3740 }
3741 }
3742
3743 /// Toggles all docks between open and closed states.
3744 ///
3745 /// If any docks are open, closes all and remembers their positions. If all
3746 /// docks are closed, restores the last remembered dock configuration.
3747 fn toggle_all_docks(
3748 &mut self,
3749 _: &ToggleAllDocks,
3750 window: &mut Window,
3751 cx: &mut Context<Self>,
3752 ) {
3753 let open_dock_positions = self.get_open_dock_positions(cx);
3754
3755 if !open_dock_positions.is_empty() {
3756 self.close_all_docks(window, cx);
3757 } else if !self.last_open_dock_positions.is_empty() {
3758 self.restore_last_open_docks(window, cx);
3759 }
3760 }
3761
3762 /// Reopens docks from the most recently remembered configuration.
3763 ///
3764 /// Opens all docks whose positions are stored in `last_open_dock_positions`
3765 /// and clears the stored positions.
3766 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3767 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
3768
3769 for position in positions_to_open {
3770 let dock = self.dock_at_position(position);
3771 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
3772 }
3773
3774 cx.focus_self(window);
3775 cx.notify();
3776 self.serialize_workspace(window, cx);
3777 }
3778
3779 /// Transfer focus to the panel of the given type.
3780 pub fn focus_panel<T: Panel>(
3781 &mut self,
3782 window: &mut Window,
3783 cx: &mut Context<Self>,
3784 ) -> Option<Entity<T>> {
3785 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
3786 panel.to_any().downcast().ok()
3787 }
3788
3789 /// Focus the panel of the given type if it isn't already focused. If it is
3790 /// already focused, then transfer focus back to the workspace center.
3791 /// When the `close_panel_on_toggle` setting is enabled, also closes the
3792 /// panel when transferring focus back to the center.
3793 pub fn toggle_panel_focus<T: Panel>(
3794 &mut self,
3795 window: &mut Window,
3796 cx: &mut Context<Self>,
3797 ) -> bool {
3798 let mut did_focus_panel = false;
3799 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
3800 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
3801 did_focus_panel
3802 });
3803
3804 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
3805 self.close_panel::<T>(window, cx);
3806 }
3807
3808 telemetry::event!(
3809 "Panel Button Clicked",
3810 name = T::persistent_name(),
3811 toggle_state = did_focus_panel
3812 );
3813
3814 did_focus_panel
3815 }
3816
3817 pub fn activate_panel_for_proto_id(
3818 &mut self,
3819 panel_id: PanelId,
3820 window: &mut Window,
3821 cx: &mut Context<Self>,
3822 ) -> Option<Arc<dyn PanelHandle>> {
3823 let mut panel = None;
3824 for dock in self.all_docks() {
3825 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
3826 panel = dock.update(cx, |dock, cx| {
3827 dock.activate_panel(panel_index, window, cx);
3828 dock.set_open(true, window, cx);
3829 dock.active_panel().cloned()
3830 });
3831 break;
3832 }
3833 }
3834
3835 if panel.is_some() {
3836 cx.notify();
3837 self.serialize_workspace(window, cx);
3838 }
3839
3840 panel
3841 }
3842
3843 /// Focus or unfocus the given panel type, depending on the given callback.
3844 fn focus_or_unfocus_panel<T: Panel>(
3845 &mut self,
3846 window: &mut Window,
3847 cx: &mut Context<Self>,
3848 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
3849 ) -> Option<Arc<dyn PanelHandle>> {
3850 let mut result_panel = None;
3851 let mut serialize = false;
3852 for dock in self.all_docks() {
3853 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3854 let mut focus_center = false;
3855 let panel = dock.update(cx, |dock, cx| {
3856 dock.activate_panel(panel_index, window, cx);
3857
3858 let panel = dock.active_panel().cloned();
3859 if let Some(panel) = panel.as_ref() {
3860 if should_focus(&**panel, window, cx) {
3861 dock.set_open(true, window, cx);
3862 panel.panel_focus_handle(cx).focus(window, cx);
3863 } else {
3864 focus_center = true;
3865 }
3866 }
3867 panel
3868 });
3869
3870 if focus_center {
3871 self.active_pane
3872 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3873 }
3874
3875 result_panel = panel;
3876 serialize = true;
3877 break;
3878 }
3879 }
3880
3881 if serialize {
3882 self.serialize_workspace(window, cx);
3883 }
3884
3885 cx.notify();
3886 result_panel
3887 }
3888
3889 /// Open the panel of the given type
3890 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3891 for dock in self.all_docks() {
3892 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3893 dock.update(cx, |dock, cx| {
3894 dock.activate_panel(panel_index, window, cx);
3895 dock.set_open(true, window, cx);
3896 });
3897 }
3898 }
3899 }
3900
3901 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
3902 for dock in self.all_docks().iter() {
3903 dock.update(cx, |dock, cx| {
3904 if dock.panel::<T>().is_some() {
3905 dock.set_open(false, window, cx)
3906 }
3907 })
3908 }
3909 }
3910
3911 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
3912 self.all_docks()
3913 .iter()
3914 .find_map(|dock| dock.read(cx).panel::<T>())
3915 }
3916
3917 fn dismiss_zoomed_items_to_reveal(
3918 &mut self,
3919 dock_to_reveal: Option<DockPosition>,
3920 window: &mut Window,
3921 cx: &mut Context<Self>,
3922 ) {
3923 // If a center pane is zoomed, unzoom it.
3924 for pane in &self.panes {
3925 if pane != &self.active_pane || dock_to_reveal.is_some() {
3926 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
3927 }
3928 }
3929
3930 // If another dock is zoomed, hide it.
3931 let mut focus_center = false;
3932 for dock in self.all_docks() {
3933 dock.update(cx, |dock, cx| {
3934 if Some(dock.position()) != dock_to_reveal
3935 && let Some(panel) = dock.active_panel()
3936 && panel.is_zoomed(window, cx)
3937 {
3938 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
3939 dock.set_open(false, window, cx);
3940 }
3941 });
3942 }
3943
3944 if focus_center {
3945 self.active_pane
3946 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3947 }
3948
3949 if self.zoomed_position != dock_to_reveal {
3950 self.zoomed = None;
3951 self.zoomed_position = None;
3952 cx.emit(Event::ZoomChanged);
3953 }
3954
3955 cx.notify();
3956 }
3957
3958 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
3959 let pane = cx.new(|cx| {
3960 let mut pane = Pane::new(
3961 self.weak_handle(),
3962 self.project.clone(),
3963 self.pane_history_timestamp.clone(),
3964 None,
3965 NewFile.boxed_clone(),
3966 true,
3967 window,
3968 cx,
3969 );
3970 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
3971 pane
3972 });
3973 cx.subscribe_in(&pane, window, Self::handle_pane_event)
3974 .detach();
3975 self.panes.push(pane.clone());
3976
3977 window.focus(&pane.focus_handle(cx), cx);
3978
3979 cx.emit(Event::PaneAdded(pane.clone()));
3980 pane
3981 }
3982
3983 pub fn add_item_to_center(
3984 &mut self,
3985 item: Box<dyn ItemHandle>,
3986 window: &mut Window,
3987 cx: &mut Context<Self>,
3988 ) -> bool {
3989 if let Some(center_pane) = self.last_active_center_pane.clone() {
3990 if let Some(center_pane) = center_pane.upgrade() {
3991 center_pane.update(cx, |pane, cx| {
3992 pane.add_item(item, true, true, None, window, cx)
3993 });
3994 true
3995 } else {
3996 false
3997 }
3998 } else {
3999 false
4000 }
4001 }
4002
4003 pub fn add_item_to_active_pane(
4004 &mut self,
4005 item: Box<dyn ItemHandle>,
4006 destination_index: Option<usize>,
4007 focus_item: bool,
4008 window: &mut Window,
4009 cx: &mut App,
4010 ) {
4011 self.add_item(
4012 self.active_pane.clone(),
4013 item,
4014 destination_index,
4015 false,
4016 focus_item,
4017 window,
4018 cx,
4019 )
4020 }
4021
4022 pub fn add_item(
4023 &mut self,
4024 pane: Entity<Pane>,
4025 item: Box<dyn ItemHandle>,
4026 destination_index: Option<usize>,
4027 activate_pane: bool,
4028 focus_item: bool,
4029 window: &mut Window,
4030 cx: &mut App,
4031 ) {
4032 pane.update(cx, |pane, cx| {
4033 pane.add_item(
4034 item,
4035 activate_pane,
4036 focus_item,
4037 destination_index,
4038 window,
4039 cx,
4040 )
4041 });
4042 }
4043
4044 pub fn split_item(
4045 &mut self,
4046 split_direction: SplitDirection,
4047 item: Box<dyn ItemHandle>,
4048 window: &mut Window,
4049 cx: &mut Context<Self>,
4050 ) {
4051 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4052 self.add_item(new_pane, item, None, true, true, window, cx);
4053 }
4054
4055 pub fn open_abs_path(
4056 &mut self,
4057 abs_path: PathBuf,
4058 options: OpenOptions,
4059 window: &mut Window,
4060 cx: &mut Context<Self>,
4061 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4062 cx.spawn_in(window, async move |workspace, cx| {
4063 let open_paths_task_result = workspace
4064 .update_in(cx, |workspace, window, cx| {
4065 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4066 })
4067 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4068 .await;
4069 anyhow::ensure!(
4070 open_paths_task_result.len() == 1,
4071 "open abs path {abs_path:?} task returned incorrect number of results"
4072 );
4073 match open_paths_task_result
4074 .into_iter()
4075 .next()
4076 .expect("ensured single task result")
4077 {
4078 Some(open_result) => {
4079 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4080 }
4081 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4082 }
4083 })
4084 }
4085
4086 pub fn split_abs_path(
4087 &mut self,
4088 abs_path: PathBuf,
4089 visible: bool,
4090 window: &mut Window,
4091 cx: &mut Context<Self>,
4092 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4093 let project_path_task =
4094 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4095 cx.spawn_in(window, async move |this, cx| {
4096 let (_, path) = project_path_task.await?;
4097 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4098 .await
4099 })
4100 }
4101
4102 pub fn open_path(
4103 &mut self,
4104 path: impl Into<ProjectPath>,
4105 pane: Option<WeakEntity<Pane>>,
4106 focus_item: bool,
4107 window: &mut Window,
4108 cx: &mut App,
4109 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4110 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4111 }
4112
4113 pub fn open_path_preview(
4114 &mut self,
4115 path: impl Into<ProjectPath>,
4116 pane: Option<WeakEntity<Pane>>,
4117 focus_item: bool,
4118 allow_preview: bool,
4119 activate: bool,
4120 window: &mut Window,
4121 cx: &mut App,
4122 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4123 let pane = pane.unwrap_or_else(|| {
4124 self.last_active_center_pane.clone().unwrap_or_else(|| {
4125 self.panes
4126 .first()
4127 .expect("There must be an active pane")
4128 .downgrade()
4129 })
4130 });
4131
4132 let project_path = path.into();
4133 let task = self.load_path(project_path.clone(), window, cx);
4134 window.spawn(cx, async move |cx| {
4135 let (project_entry_id, build_item) = task.await?;
4136
4137 pane.update_in(cx, |pane, window, cx| {
4138 pane.open_item(
4139 project_entry_id,
4140 project_path,
4141 focus_item,
4142 allow_preview,
4143 activate,
4144 None,
4145 window,
4146 cx,
4147 build_item,
4148 )
4149 })
4150 })
4151 }
4152
4153 pub fn split_path(
4154 &mut self,
4155 path: impl Into<ProjectPath>,
4156 window: &mut Window,
4157 cx: &mut Context<Self>,
4158 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4159 self.split_path_preview(path, false, None, window, cx)
4160 }
4161
4162 pub fn split_path_preview(
4163 &mut self,
4164 path: impl Into<ProjectPath>,
4165 allow_preview: bool,
4166 split_direction: Option<SplitDirection>,
4167 window: &mut Window,
4168 cx: &mut Context<Self>,
4169 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4170 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4171 self.panes
4172 .first()
4173 .expect("There must be an active pane")
4174 .downgrade()
4175 });
4176
4177 if let Member::Pane(center_pane) = &self.center.root
4178 && center_pane.read(cx).items_len() == 0
4179 {
4180 return self.open_path(path, Some(pane), true, window, cx);
4181 }
4182
4183 let project_path = path.into();
4184 let task = self.load_path(project_path.clone(), window, cx);
4185 cx.spawn_in(window, async move |this, cx| {
4186 let (project_entry_id, build_item) = task.await?;
4187 this.update_in(cx, move |this, window, cx| -> Option<_> {
4188 let pane = pane.upgrade()?;
4189 let new_pane = this.split_pane(
4190 pane,
4191 split_direction.unwrap_or(SplitDirection::Right),
4192 window,
4193 cx,
4194 );
4195 new_pane.update(cx, |new_pane, cx| {
4196 Some(new_pane.open_item(
4197 project_entry_id,
4198 project_path,
4199 true,
4200 allow_preview,
4201 true,
4202 None,
4203 window,
4204 cx,
4205 build_item,
4206 ))
4207 })
4208 })
4209 .map(|option| option.context("pane was dropped"))?
4210 })
4211 }
4212
4213 fn load_path(
4214 &mut self,
4215 path: ProjectPath,
4216 window: &mut Window,
4217 cx: &mut App,
4218 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4219 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4220 registry.open_path(self.project(), &path, window, cx)
4221 }
4222
4223 pub fn find_project_item<T>(
4224 &self,
4225 pane: &Entity<Pane>,
4226 project_item: &Entity<T::Item>,
4227 cx: &App,
4228 ) -> Option<Entity<T>>
4229 where
4230 T: ProjectItem,
4231 {
4232 use project::ProjectItem as _;
4233 let project_item = project_item.read(cx);
4234 let entry_id = project_item.entry_id(cx);
4235 let project_path = project_item.project_path(cx);
4236
4237 let mut item = None;
4238 if let Some(entry_id) = entry_id {
4239 item = pane.read(cx).item_for_entry(entry_id, cx);
4240 }
4241 if item.is_none()
4242 && let Some(project_path) = project_path
4243 {
4244 item = pane.read(cx).item_for_path(project_path, cx);
4245 }
4246
4247 item.and_then(|item| item.downcast::<T>())
4248 }
4249
4250 pub fn is_project_item_open<T>(
4251 &self,
4252 pane: &Entity<Pane>,
4253 project_item: &Entity<T::Item>,
4254 cx: &App,
4255 ) -> bool
4256 where
4257 T: ProjectItem,
4258 {
4259 self.find_project_item::<T>(pane, project_item, cx)
4260 .is_some()
4261 }
4262
4263 pub fn open_project_item<T>(
4264 &mut self,
4265 pane: Entity<Pane>,
4266 project_item: Entity<T::Item>,
4267 activate_pane: bool,
4268 focus_item: bool,
4269 keep_old_preview: bool,
4270 allow_new_preview: bool,
4271 window: &mut Window,
4272 cx: &mut Context<Self>,
4273 ) -> Entity<T>
4274 where
4275 T: ProjectItem,
4276 {
4277 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4278
4279 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4280 if !keep_old_preview
4281 && let Some(old_id) = old_item_id
4282 && old_id != item.item_id()
4283 {
4284 // switching to a different item, so unpreview old active item
4285 pane.update(cx, |pane, _| {
4286 pane.unpreview_item_if_preview(old_id);
4287 });
4288 }
4289
4290 self.activate_item(&item, activate_pane, focus_item, window, cx);
4291 if !allow_new_preview {
4292 pane.update(cx, |pane, _| {
4293 pane.unpreview_item_if_preview(item.item_id());
4294 });
4295 }
4296 return item;
4297 }
4298
4299 let item = pane.update(cx, |pane, cx| {
4300 cx.new(|cx| {
4301 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4302 })
4303 });
4304 let mut destination_index = None;
4305 pane.update(cx, |pane, cx| {
4306 if !keep_old_preview && let Some(old_id) = old_item_id {
4307 pane.unpreview_item_if_preview(old_id);
4308 }
4309 if allow_new_preview {
4310 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4311 }
4312 });
4313
4314 self.add_item(
4315 pane,
4316 Box::new(item.clone()),
4317 destination_index,
4318 activate_pane,
4319 focus_item,
4320 window,
4321 cx,
4322 );
4323 item
4324 }
4325
4326 pub fn open_shared_screen(
4327 &mut self,
4328 peer_id: PeerId,
4329 window: &mut Window,
4330 cx: &mut Context<Self>,
4331 ) {
4332 if let Some(shared_screen) =
4333 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4334 {
4335 self.active_pane.update(cx, |pane, cx| {
4336 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4337 });
4338 }
4339 }
4340
4341 pub fn activate_item(
4342 &mut self,
4343 item: &dyn ItemHandle,
4344 activate_pane: bool,
4345 focus_item: bool,
4346 window: &mut Window,
4347 cx: &mut App,
4348 ) -> bool {
4349 let result = self.panes.iter().find_map(|pane| {
4350 pane.read(cx)
4351 .index_for_item(item)
4352 .map(|ix| (pane.clone(), ix))
4353 });
4354 if let Some((pane, ix)) = result {
4355 pane.update(cx, |pane, cx| {
4356 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4357 });
4358 true
4359 } else {
4360 false
4361 }
4362 }
4363
4364 fn activate_pane_at_index(
4365 &mut self,
4366 action: &ActivatePane,
4367 window: &mut Window,
4368 cx: &mut Context<Self>,
4369 ) {
4370 let panes = self.center.panes();
4371 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4372 window.focus(&pane.focus_handle(cx), cx);
4373 } else {
4374 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4375 .detach();
4376 }
4377 }
4378
4379 fn move_item_to_pane_at_index(
4380 &mut self,
4381 action: &MoveItemToPane,
4382 window: &mut Window,
4383 cx: &mut Context<Self>,
4384 ) {
4385 let panes = self.center.panes();
4386 let destination = match panes.get(action.destination) {
4387 Some(&destination) => destination.clone(),
4388 None => {
4389 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4390 return;
4391 }
4392 let direction = SplitDirection::Right;
4393 let split_off_pane = self
4394 .find_pane_in_direction(direction, cx)
4395 .unwrap_or_else(|| self.active_pane.clone());
4396 let new_pane = self.add_pane(window, cx);
4397 self.center.split(&split_off_pane, &new_pane, direction, cx);
4398 new_pane
4399 }
4400 };
4401
4402 if action.clone {
4403 if self
4404 .active_pane
4405 .read(cx)
4406 .active_item()
4407 .is_some_and(|item| item.can_split(cx))
4408 {
4409 clone_active_item(
4410 self.database_id(),
4411 &self.active_pane,
4412 &destination,
4413 action.focus,
4414 window,
4415 cx,
4416 );
4417 return;
4418 }
4419 }
4420 move_active_item(
4421 &self.active_pane,
4422 &destination,
4423 action.focus,
4424 true,
4425 window,
4426 cx,
4427 )
4428 }
4429
4430 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4431 let panes = self.center.panes();
4432 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4433 let next_ix = (ix + 1) % panes.len();
4434 let next_pane = panes[next_ix].clone();
4435 window.focus(&next_pane.focus_handle(cx), cx);
4436 }
4437 }
4438
4439 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4440 let panes = self.center.panes();
4441 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4442 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4443 let prev_pane = panes[prev_ix].clone();
4444 window.focus(&prev_pane.focus_handle(cx), cx);
4445 }
4446 }
4447
4448 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4449 let last_pane = self.center.last_pane();
4450 window.focus(&last_pane.focus_handle(cx), cx);
4451 }
4452
4453 pub fn activate_pane_in_direction(
4454 &mut self,
4455 direction: SplitDirection,
4456 window: &mut Window,
4457 cx: &mut App,
4458 ) {
4459 use ActivateInDirectionTarget as Target;
4460 enum Origin {
4461 LeftDock,
4462 RightDock,
4463 BottomDock,
4464 Center,
4465 }
4466
4467 let origin: Origin = [
4468 (&self.left_dock, Origin::LeftDock),
4469 (&self.right_dock, Origin::RightDock),
4470 (&self.bottom_dock, Origin::BottomDock),
4471 ]
4472 .into_iter()
4473 .find_map(|(dock, origin)| {
4474 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4475 Some(origin)
4476 } else {
4477 None
4478 }
4479 })
4480 .unwrap_or(Origin::Center);
4481
4482 let get_last_active_pane = || {
4483 let pane = self
4484 .last_active_center_pane
4485 .clone()
4486 .unwrap_or_else(|| {
4487 self.panes
4488 .first()
4489 .expect("There must be an active pane")
4490 .downgrade()
4491 })
4492 .upgrade()?;
4493 (pane.read(cx).items_len() != 0).then_some(pane)
4494 };
4495
4496 let try_dock =
4497 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4498
4499 let target = match (origin, direction) {
4500 // We're in the center, so we first try to go to a different pane,
4501 // otherwise try to go to a dock.
4502 (Origin::Center, direction) => {
4503 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4504 Some(Target::Pane(pane))
4505 } else {
4506 match direction {
4507 SplitDirection::Up => None,
4508 SplitDirection::Down => try_dock(&self.bottom_dock),
4509 SplitDirection::Left => try_dock(&self.left_dock),
4510 SplitDirection::Right => try_dock(&self.right_dock),
4511 }
4512 }
4513 }
4514
4515 (Origin::LeftDock, SplitDirection::Right) => {
4516 if let Some(last_active_pane) = get_last_active_pane() {
4517 Some(Target::Pane(last_active_pane))
4518 } else {
4519 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4520 }
4521 }
4522
4523 (Origin::LeftDock, SplitDirection::Down)
4524 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4525
4526 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4527 (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
4528 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4529
4530 (Origin::RightDock, SplitDirection::Left) => {
4531 if let Some(last_active_pane) = get_last_active_pane() {
4532 Some(Target::Pane(last_active_pane))
4533 } else {
4534 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
4535 }
4536 }
4537
4538 _ => None,
4539 };
4540
4541 match target {
4542 Some(ActivateInDirectionTarget::Pane(pane)) => {
4543 let pane = pane.read(cx);
4544 if let Some(item) = pane.active_item() {
4545 item.item_focus_handle(cx).focus(window, cx);
4546 } else {
4547 log::error!(
4548 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4549 );
4550 }
4551 }
4552 Some(ActivateInDirectionTarget::Dock(dock)) => {
4553 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4554 window.defer(cx, move |window, cx| {
4555 let dock = dock.read(cx);
4556 if let Some(panel) = dock.active_panel() {
4557 panel.panel_focus_handle(cx).focus(window, cx);
4558 } else {
4559 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4560 }
4561 })
4562 }
4563 None => {}
4564 }
4565 }
4566
4567 pub fn move_item_to_pane_in_direction(
4568 &mut self,
4569 action: &MoveItemToPaneInDirection,
4570 window: &mut Window,
4571 cx: &mut Context<Self>,
4572 ) {
4573 let destination = match self.find_pane_in_direction(action.direction, cx) {
4574 Some(destination) => destination,
4575 None => {
4576 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4577 return;
4578 }
4579 let new_pane = self.add_pane(window, cx);
4580 self.center
4581 .split(&self.active_pane, &new_pane, action.direction, cx);
4582 new_pane
4583 }
4584 };
4585
4586 if action.clone {
4587 if self
4588 .active_pane
4589 .read(cx)
4590 .active_item()
4591 .is_some_and(|item| item.can_split(cx))
4592 {
4593 clone_active_item(
4594 self.database_id(),
4595 &self.active_pane,
4596 &destination,
4597 action.focus,
4598 window,
4599 cx,
4600 );
4601 return;
4602 }
4603 }
4604 move_active_item(
4605 &self.active_pane,
4606 &destination,
4607 action.focus,
4608 true,
4609 window,
4610 cx,
4611 );
4612 }
4613
4614 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4615 self.center.bounding_box_for_pane(pane)
4616 }
4617
4618 pub fn find_pane_in_direction(
4619 &mut self,
4620 direction: SplitDirection,
4621 cx: &App,
4622 ) -> Option<Entity<Pane>> {
4623 self.center
4624 .find_pane_in_direction(&self.active_pane, direction, cx)
4625 .cloned()
4626 }
4627
4628 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4629 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4630 self.center.swap(&self.active_pane, &to, cx);
4631 cx.notify();
4632 }
4633 }
4634
4635 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4636 if self
4637 .center
4638 .move_to_border(&self.active_pane, direction, cx)
4639 .unwrap()
4640 {
4641 cx.notify();
4642 }
4643 }
4644
4645 pub fn resize_pane(
4646 &mut self,
4647 axis: gpui::Axis,
4648 amount: Pixels,
4649 window: &mut Window,
4650 cx: &mut Context<Self>,
4651 ) {
4652 let docks = self.all_docks();
4653 let active_dock = docks
4654 .into_iter()
4655 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4656
4657 if let Some(dock) = active_dock {
4658 let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
4659 return;
4660 };
4661 match dock.read(cx).position() {
4662 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4663 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4664 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4665 }
4666 } else {
4667 self.center
4668 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
4669 }
4670 cx.notify();
4671 }
4672
4673 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
4674 self.center.reset_pane_sizes(cx);
4675 cx.notify();
4676 }
4677
4678 fn handle_pane_focused(
4679 &mut self,
4680 pane: Entity<Pane>,
4681 window: &mut Window,
4682 cx: &mut Context<Self>,
4683 ) {
4684 // This is explicitly hoisted out of the following check for pane identity as
4685 // terminal panel panes are not registered as a center panes.
4686 self.status_bar.update(cx, |status_bar, cx| {
4687 status_bar.set_active_pane(&pane, window, cx);
4688 });
4689 if self.active_pane != pane {
4690 self.set_active_pane(&pane, window, cx);
4691 }
4692
4693 if self.last_active_center_pane.is_none() {
4694 self.last_active_center_pane = Some(pane.downgrade());
4695 }
4696
4697 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
4698 // This prevents the dock from closing when focus events fire during window activation.
4699 // We also preserve any dock whose active panel itself has focus — this covers
4700 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
4701 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
4702 let dock_read = dock.read(cx);
4703 if let Some(panel) = dock_read.active_panel() {
4704 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
4705 || panel.panel_focus_handle(cx).contains_focused(window, cx)
4706 {
4707 return Some(dock_read.position());
4708 }
4709 }
4710 None
4711 });
4712
4713 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
4714 if pane.read(cx).is_zoomed() {
4715 self.zoomed = Some(pane.downgrade().into());
4716 } else {
4717 self.zoomed = None;
4718 }
4719 self.zoomed_position = None;
4720 cx.emit(Event::ZoomChanged);
4721 self.update_active_view_for_followers(window, cx);
4722 pane.update(cx, |pane, _| {
4723 pane.track_alternate_file_items();
4724 });
4725
4726 cx.notify();
4727 }
4728
4729 fn set_active_pane(
4730 &mut self,
4731 pane: &Entity<Pane>,
4732 window: &mut Window,
4733 cx: &mut Context<Self>,
4734 ) {
4735 self.active_pane = pane.clone();
4736 self.active_item_path_changed(true, window, cx);
4737 self.last_active_center_pane = Some(pane.downgrade());
4738 }
4739
4740 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4741 self.update_active_view_for_followers(window, cx);
4742 }
4743
4744 fn handle_pane_event(
4745 &mut self,
4746 pane: &Entity<Pane>,
4747 event: &pane::Event,
4748 window: &mut Window,
4749 cx: &mut Context<Self>,
4750 ) {
4751 let mut serialize_workspace = true;
4752 match event {
4753 pane::Event::AddItem { item } => {
4754 item.added_to_pane(self, pane.clone(), window, cx);
4755 cx.emit(Event::ItemAdded {
4756 item: item.boxed_clone(),
4757 });
4758 }
4759 pane::Event::Split { direction, mode } => {
4760 match mode {
4761 SplitMode::ClonePane => {
4762 self.split_and_clone(pane.clone(), *direction, window, cx)
4763 .detach();
4764 }
4765 SplitMode::EmptyPane => {
4766 self.split_pane(pane.clone(), *direction, window, cx);
4767 }
4768 SplitMode::MovePane => {
4769 self.split_and_move(pane.clone(), *direction, window, cx);
4770 }
4771 };
4772 }
4773 pane::Event::JoinIntoNext => {
4774 self.join_pane_into_next(pane.clone(), window, cx);
4775 }
4776 pane::Event::JoinAll => {
4777 self.join_all_panes(window, cx);
4778 }
4779 pane::Event::Remove { focus_on_pane } => {
4780 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
4781 }
4782 pane::Event::ActivateItem {
4783 local,
4784 focus_changed,
4785 } => {
4786 window.invalidate_character_coordinates();
4787
4788 pane.update(cx, |pane, _| {
4789 pane.track_alternate_file_items();
4790 });
4791 if *local {
4792 self.unfollow_in_pane(pane, window, cx);
4793 }
4794 serialize_workspace = *focus_changed || pane != self.active_pane();
4795 if pane == self.active_pane() {
4796 self.active_item_path_changed(*focus_changed, window, cx);
4797 self.update_active_view_for_followers(window, cx);
4798 } else if *local {
4799 self.set_active_pane(pane, window, cx);
4800 }
4801 }
4802 pane::Event::UserSavedItem { item, save_intent } => {
4803 cx.emit(Event::UserSavedItem {
4804 pane: pane.downgrade(),
4805 item: item.boxed_clone(),
4806 save_intent: *save_intent,
4807 });
4808 serialize_workspace = false;
4809 }
4810 pane::Event::ChangeItemTitle => {
4811 if *pane == self.active_pane {
4812 self.active_item_path_changed(false, window, cx);
4813 }
4814 serialize_workspace = false;
4815 }
4816 pane::Event::RemovedItem { item } => {
4817 cx.emit(Event::ActiveItemChanged);
4818 self.update_window_edited(window, cx);
4819 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
4820 && entry.get().entity_id() == pane.entity_id()
4821 {
4822 entry.remove();
4823 }
4824 cx.emit(Event::ItemRemoved {
4825 item_id: item.item_id(),
4826 });
4827 }
4828 pane::Event::Focus => {
4829 window.invalidate_character_coordinates();
4830 self.handle_pane_focused(pane.clone(), window, cx);
4831 }
4832 pane::Event::ZoomIn => {
4833 if *pane == self.active_pane {
4834 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
4835 if pane.read(cx).has_focus(window, cx) {
4836 self.zoomed = Some(pane.downgrade().into());
4837 self.zoomed_position = None;
4838 cx.emit(Event::ZoomChanged);
4839 }
4840 cx.notify();
4841 }
4842 }
4843 pane::Event::ZoomOut => {
4844 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4845 if self.zoomed_position.is_none() {
4846 self.zoomed = None;
4847 cx.emit(Event::ZoomChanged);
4848 }
4849 cx.notify();
4850 }
4851 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
4852 }
4853
4854 if serialize_workspace {
4855 self.serialize_workspace(window, cx);
4856 }
4857 }
4858
4859 pub fn unfollow_in_pane(
4860 &mut self,
4861 pane: &Entity<Pane>,
4862 window: &mut Window,
4863 cx: &mut Context<Workspace>,
4864 ) -> Option<CollaboratorId> {
4865 let leader_id = self.leader_for_pane(pane)?;
4866 self.unfollow(leader_id, window, cx);
4867 Some(leader_id)
4868 }
4869
4870 pub fn split_pane(
4871 &mut self,
4872 pane_to_split: Entity<Pane>,
4873 split_direction: SplitDirection,
4874 window: &mut Window,
4875 cx: &mut Context<Self>,
4876 ) -> Entity<Pane> {
4877 let new_pane = self.add_pane(window, cx);
4878 self.center
4879 .split(&pane_to_split, &new_pane, split_direction, cx);
4880 cx.notify();
4881 new_pane
4882 }
4883
4884 pub fn split_and_move(
4885 &mut self,
4886 pane: Entity<Pane>,
4887 direction: SplitDirection,
4888 window: &mut Window,
4889 cx: &mut Context<Self>,
4890 ) {
4891 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
4892 return;
4893 };
4894 let new_pane = self.add_pane(window, cx);
4895 new_pane.update(cx, |pane, cx| {
4896 pane.add_item(item, true, true, None, window, cx)
4897 });
4898 self.center.split(&pane, &new_pane, direction, cx);
4899 cx.notify();
4900 }
4901
4902 pub fn split_and_clone(
4903 &mut self,
4904 pane: Entity<Pane>,
4905 direction: SplitDirection,
4906 window: &mut Window,
4907 cx: &mut Context<Self>,
4908 ) -> Task<Option<Entity<Pane>>> {
4909 let Some(item) = pane.read(cx).active_item() else {
4910 return Task::ready(None);
4911 };
4912 if !item.can_split(cx) {
4913 return Task::ready(None);
4914 }
4915 let task = item.clone_on_split(self.database_id(), window, cx);
4916 cx.spawn_in(window, async move |this, cx| {
4917 if let Some(clone) = task.await {
4918 this.update_in(cx, |this, window, cx| {
4919 let new_pane = this.add_pane(window, cx);
4920 let nav_history = pane.read(cx).fork_nav_history();
4921 new_pane.update(cx, |pane, cx| {
4922 pane.set_nav_history(nav_history, cx);
4923 pane.add_item(clone, true, true, None, window, cx)
4924 });
4925 this.center.split(&pane, &new_pane, direction, cx);
4926 cx.notify();
4927 new_pane
4928 })
4929 .ok()
4930 } else {
4931 None
4932 }
4933 })
4934 }
4935
4936 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4937 let active_item = self.active_pane.read(cx).active_item();
4938 for pane in &self.panes {
4939 join_pane_into_active(&self.active_pane, pane, window, cx);
4940 }
4941 if let Some(active_item) = active_item {
4942 self.activate_item(active_item.as_ref(), true, true, window, cx);
4943 }
4944 cx.notify();
4945 }
4946
4947 pub fn join_pane_into_next(
4948 &mut self,
4949 pane: Entity<Pane>,
4950 window: &mut Window,
4951 cx: &mut Context<Self>,
4952 ) {
4953 let next_pane = self
4954 .find_pane_in_direction(SplitDirection::Right, cx)
4955 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
4956 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
4957 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
4958 let Some(next_pane) = next_pane else {
4959 return;
4960 };
4961 move_all_items(&pane, &next_pane, window, cx);
4962 cx.notify();
4963 }
4964
4965 fn remove_pane(
4966 &mut self,
4967 pane: Entity<Pane>,
4968 focus_on: Option<Entity<Pane>>,
4969 window: &mut Window,
4970 cx: &mut Context<Self>,
4971 ) {
4972 if self.center.remove(&pane, cx).unwrap() {
4973 self.force_remove_pane(&pane, &focus_on, window, cx);
4974 self.unfollow_in_pane(&pane, window, cx);
4975 self.last_leaders_by_pane.remove(&pane.downgrade());
4976 for removed_item in pane.read(cx).items() {
4977 self.panes_by_item.remove(&removed_item.item_id());
4978 }
4979
4980 cx.notify();
4981 } else {
4982 self.active_item_path_changed(true, window, cx);
4983 }
4984 cx.emit(Event::PaneRemoved);
4985 }
4986
4987 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
4988 &mut self.panes
4989 }
4990
4991 pub fn panes(&self) -> &[Entity<Pane>] {
4992 &self.panes
4993 }
4994
4995 pub fn active_pane(&self) -> &Entity<Pane> {
4996 &self.active_pane
4997 }
4998
4999 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5000 for dock in self.all_docks() {
5001 if dock.focus_handle(cx).contains_focused(window, cx)
5002 && let Some(pane) = dock
5003 .read(cx)
5004 .active_panel()
5005 .and_then(|panel| panel.pane(cx))
5006 {
5007 return pane;
5008 }
5009 }
5010 self.active_pane().clone()
5011 }
5012
5013 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5014 self.find_pane_in_direction(SplitDirection::Right, cx)
5015 .unwrap_or_else(|| {
5016 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5017 })
5018 }
5019
5020 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5021 self.pane_for_item_id(handle.item_id())
5022 }
5023
5024 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5025 let weak_pane = self.panes_by_item.get(&item_id)?;
5026 weak_pane.upgrade()
5027 }
5028
5029 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5030 self.panes
5031 .iter()
5032 .find(|pane| pane.entity_id() == entity_id)
5033 .cloned()
5034 }
5035
5036 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5037 self.follower_states.retain(|leader_id, state| {
5038 if *leader_id == CollaboratorId::PeerId(peer_id) {
5039 for item in state.items_by_leader_view_id.values() {
5040 item.view.set_leader_id(None, window, cx);
5041 }
5042 false
5043 } else {
5044 true
5045 }
5046 });
5047 cx.notify();
5048 }
5049
5050 pub fn start_following(
5051 &mut self,
5052 leader_id: impl Into<CollaboratorId>,
5053 window: &mut Window,
5054 cx: &mut Context<Self>,
5055 ) -> Option<Task<Result<()>>> {
5056 let leader_id = leader_id.into();
5057 let pane = self.active_pane().clone();
5058
5059 self.last_leaders_by_pane
5060 .insert(pane.downgrade(), leader_id);
5061 self.unfollow(leader_id, window, cx);
5062 self.unfollow_in_pane(&pane, window, cx);
5063 self.follower_states.insert(
5064 leader_id,
5065 FollowerState {
5066 center_pane: pane.clone(),
5067 dock_pane: None,
5068 active_view_id: None,
5069 items_by_leader_view_id: Default::default(),
5070 },
5071 );
5072 cx.notify();
5073
5074 match leader_id {
5075 CollaboratorId::PeerId(leader_peer_id) => {
5076 let room_id = self.active_call()?.room_id(cx)?;
5077 let project_id = self.project.read(cx).remote_id();
5078 let request = self.app_state.client.request(proto::Follow {
5079 room_id,
5080 project_id,
5081 leader_id: Some(leader_peer_id),
5082 });
5083
5084 Some(cx.spawn_in(window, async move |this, cx| {
5085 let response = request.await?;
5086 this.update(cx, |this, _| {
5087 let state = this
5088 .follower_states
5089 .get_mut(&leader_id)
5090 .context("following interrupted")?;
5091 state.active_view_id = response
5092 .active_view
5093 .as_ref()
5094 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5095 anyhow::Ok(())
5096 })??;
5097 if let Some(view) = response.active_view {
5098 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5099 }
5100 this.update_in(cx, |this, window, cx| {
5101 this.leader_updated(leader_id, window, cx)
5102 })?;
5103 Ok(())
5104 }))
5105 }
5106 CollaboratorId::Agent => {
5107 self.leader_updated(leader_id, window, cx)?;
5108 Some(Task::ready(Ok(())))
5109 }
5110 }
5111 }
5112
5113 pub fn follow_next_collaborator(
5114 &mut self,
5115 _: &FollowNextCollaborator,
5116 window: &mut Window,
5117 cx: &mut Context<Self>,
5118 ) {
5119 let collaborators = self.project.read(cx).collaborators();
5120 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5121 let mut collaborators = collaborators.keys().copied();
5122 for peer_id in collaborators.by_ref() {
5123 if CollaboratorId::PeerId(peer_id) == leader_id {
5124 break;
5125 }
5126 }
5127 collaborators.next().map(CollaboratorId::PeerId)
5128 } else if let Some(last_leader_id) =
5129 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5130 {
5131 match last_leader_id {
5132 CollaboratorId::PeerId(peer_id) => {
5133 if collaborators.contains_key(peer_id) {
5134 Some(*last_leader_id)
5135 } else {
5136 None
5137 }
5138 }
5139 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5140 }
5141 } else {
5142 None
5143 };
5144
5145 let pane = self.active_pane.clone();
5146 let Some(leader_id) = next_leader_id.or_else(|| {
5147 Some(CollaboratorId::PeerId(
5148 collaborators.keys().copied().next()?,
5149 ))
5150 }) else {
5151 return;
5152 };
5153 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5154 return;
5155 }
5156 if let Some(task) = self.start_following(leader_id, window, cx) {
5157 task.detach_and_log_err(cx)
5158 }
5159 }
5160
5161 pub fn follow(
5162 &mut self,
5163 leader_id: impl Into<CollaboratorId>,
5164 window: &mut Window,
5165 cx: &mut Context<Self>,
5166 ) {
5167 let leader_id = leader_id.into();
5168
5169 if let CollaboratorId::PeerId(peer_id) = leader_id {
5170 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5171 return;
5172 };
5173 let Some(remote_participant) =
5174 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5175 else {
5176 return;
5177 };
5178
5179 let project = self.project.read(cx);
5180
5181 let other_project_id = match remote_participant.location {
5182 ParticipantLocation::External => None,
5183 ParticipantLocation::UnsharedProject => None,
5184 ParticipantLocation::SharedProject { project_id } => {
5185 if Some(project_id) == project.remote_id() {
5186 None
5187 } else {
5188 Some(project_id)
5189 }
5190 }
5191 };
5192
5193 // if they are active in another project, follow there.
5194 if let Some(project_id) = other_project_id {
5195 let app_state = self.app_state.clone();
5196 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5197 .detach_and_log_err(cx);
5198 }
5199 }
5200
5201 // if you're already following, find the right pane and focus it.
5202 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5203 window.focus(&follower_state.pane().focus_handle(cx), cx);
5204
5205 return;
5206 }
5207
5208 // Otherwise, follow.
5209 if let Some(task) = self.start_following(leader_id, window, cx) {
5210 task.detach_and_log_err(cx)
5211 }
5212 }
5213
5214 pub fn unfollow(
5215 &mut self,
5216 leader_id: impl Into<CollaboratorId>,
5217 window: &mut Window,
5218 cx: &mut Context<Self>,
5219 ) -> Option<()> {
5220 cx.notify();
5221
5222 let leader_id = leader_id.into();
5223 let state = self.follower_states.remove(&leader_id)?;
5224 for (_, item) in state.items_by_leader_view_id {
5225 item.view.set_leader_id(None, window, cx);
5226 }
5227
5228 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5229 let project_id = self.project.read(cx).remote_id();
5230 let room_id = self.active_call()?.room_id(cx)?;
5231 self.app_state
5232 .client
5233 .send(proto::Unfollow {
5234 room_id,
5235 project_id,
5236 leader_id: Some(leader_peer_id),
5237 })
5238 .log_err();
5239 }
5240
5241 Some(())
5242 }
5243
5244 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5245 self.follower_states.contains_key(&id.into())
5246 }
5247
5248 fn active_item_path_changed(
5249 &mut self,
5250 focus_changed: bool,
5251 window: &mut Window,
5252 cx: &mut Context<Self>,
5253 ) {
5254 cx.emit(Event::ActiveItemChanged);
5255 let active_entry = self.active_project_path(cx);
5256 self.project.update(cx, |project, cx| {
5257 project.set_active_path(active_entry.clone(), cx)
5258 });
5259
5260 if focus_changed && let Some(project_path) = &active_entry {
5261 let git_store_entity = self.project.read(cx).git_store().clone();
5262 git_store_entity.update(cx, |git_store, cx| {
5263 git_store.set_active_repo_for_path(project_path, cx);
5264 });
5265 }
5266
5267 self.update_window_title(window, cx);
5268 }
5269
5270 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5271 let project = self.project().read(cx);
5272 let mut title = String::new();
5273
5274 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5275 let name = {
5276 let settings_location = SettingsLocation {
5277 worktree_id: worktree.read(cx).id(),
5278 path: RelPath::empty(),
5279 };
5280
5281 let settings = WorktreeSettings::get(Some(settings_location), cx);
5282 match &settings.project_name {
5283 Some(name) => name.as_str(),
5284 None => worktree.read(cx).root_name_str(),
5285 }
5286 };
5287 if i > 0 {
5288 title.push_str(", ");
5289 }
5290 title.push_str(name);
5291 }
5292
5293 if title.is_empty() {
5294 title = "empty project".to_string();
5295 }
5296
5297 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5298 let filename = path.path.file_name().or_else(|| {
5299 Some(
5300 project
5301 .worktree_for_id(path.worktree_id, cx)?
5302 .read(cx)
5303 .root_name_str(),
5304 )
5305 });
5306
5307 if let Some(filename) = filename {
5308 title.push_str(" — ");
5309 title.push_str(filename.as_ref());
5310 }
5311 }
5312
5313 if project.is_via_collab() {
5314 title.push_str(" ↙");
5315 } else if project.is_shared() {
5316 title.push_str(" ↗");
5317 }
5318
5319 if let Some(last_title) = self.last_window_title.as_ref()
5320 && &title == last_title
5321 {
5322 return;
5323 }
5324 window.set_window_title(&title);
5325 SystemWindowTabController::update_tab_title(
5326 cx,
5327 window.window_handle().window_id(),
5328 SharedString::from(&title),
5329 );
5330 self.last_window_title = Some(title);
5331 }
5332
5333 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5334 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5335 if is_edited != self.window_edited {
5336 self.window_edited = is_edited;
5337 window.set_window_edited(self.window_edited)
5338 }
5339 }
5340
5341 fn update_item_dirty_state(
5342 &mut self,
5343 item: &dyn ItemHandle,
5344 window: &mut Window,
5345 cx: &mut App,
5346 ) {
5347 let is_dirty = item.is_dirty(cx);
5348 let item_id = item.item_id();
5349 let was_dirty = self.dirty_items.contains_key(&item_id);
5350 if is_dirty == was_dirty {
5351 return;
5352 }
5353 if was_dirty {
5354 self.dirty_items.remove(&item_id);
5355 self.update_window_edited(window, cx);
5356 return;
5357 }
5358
5359 let workspace = self.weak_handle();
5360 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5361 return;
5362 };
5363 let on_release_callback = Box::new(move |cx: &mut App| {
5364 window_handle
5365 .update(cx, |_, window, cx| {
5366 workspace
5367 .update(cx, |workspace, cx| {
5368 workspace.dirty_items.remove(&item_id);
5369 workspace.update_window_edited(window, cx)
5370 })
5371 .ok();
5372 })
5373 .ok();
5374 });
5375
5376 let s = item.on_release(cx, on_release_callback);
5377 self.dirty_items.insert(item_id, s);
5378 self.update_window_edited(window, cx);
5379 }
5380
5381 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5382 if self.notifications.is_empty() {
5383 None
5384 } else {
5385 Some(
5386 div()
5387 .absolute()
5388 .right_3()
5389 .bottom_3()
5390 .w_112()
5391 .h_full()
5392 .flex()
5393 .flex_col()
5394 .justify_end()
5395 .gap_2()
5396 .children(
5397 self.notifications
5398 .iter()
5399 .map(|(_, notification)| notification.clone().into_any()),
5400 ),
5401 )
5402 }
5403 }
5404
5405 // RPC handlers
5406
5407 fn active_view_for_follower(
5408 &self,
5409 follower_project_id: Option<u64>,
5410 window: &mut Window,
5411 cx: &mut Context<Self>,
5412 ) -> Option<proto::View> {
5413 let (item, panel_id) = self.active_item_for_followers(window, cx);
5414 let item = item?;
5415 let leader_id = self
5416 .pane_for(&*item)
5417 .and_then(|pane| self.leader_for_pane(&pane));
5418 let leader_peer_id = match leader_id {
5419 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5420 Some(CollaboratorId::Agent) | None => None,
5421 };
5422
5423 let item_handle = item.to_followable_item_handle(cx)?;
5424 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5425 let variant = item_handle.to_state_proto(window, cx)?;
5426
5427 if item_handle.is_project_item(window, cx)
5428 && (follower_project_id.is_none()
5429 || follower_project_id != self.project.read(cx).remote_id())
5430 {
5431 return None;
5432 }
5433
5434 Some(proto::View {
5435 id: id.to_proto(),
5436 leader_id: leader_peer_id,
5437 variant: Some(variant),
5438 panel_id: panel_id.map(|id| id as i32),
5439 })
5440 }
5441
5442 fn handle_follow(
5443 &mut self,
5444 follower_project_id: Option<u64>,
5445 window: &mut Window,
5446 cx: &mut Context<Self>,
5447 ) -> proto::FollowResponse {
5448 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5449
5450 cx.notify();
5451 proto::FollowResponse {
5452 views: active_view.iter().cloned().collect(),
5453 active_view,
5454 }
5455 }
5456
5457 fn handle_update_followers(
5458 &mut self,
5459 leader_id: PeerId,
5460 message: proto::UpdateFollowers,
5461 _window: &mut Window,
5462 _cx: &mut Context<Self>,
5463 ) {
5464 self.leader_updates_tx
5465 .unbounded_send((leader_id, message))
5466 .ok();
5467 }
5468
5469 async fn process_leader_update(
5470 this: &WeakEntity<Self>,
5471 leader_id: PeerId,
5472 update: proto::UpdateFollowers,
5473 cx: &mut AsyncWindowContext,
5474 ) -> Result<()> {
5475 match update.variant.context("invalid update")? {
5476 proto::update_followers::Variant::CreateView(view) => {
5477 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5478 let should_add_view = this.update(cx, |this, _| {
5479 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5480 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5481 } else {
5482 anyhow::Ok(false)
5483 }
5484 })??;
5485
5486 if should_add_view {
5487 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5488 }
5489 }
5490 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5491 let should_add_view = this.update(cx, |this, _| {
5492 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5493 state.active_view_id = update_active_view
5494 .view
5495 .as_ref()
5496 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5497
5498 if state.active_view_id.is_some_and(|view_id| {
5499 !state.items_by_leader_view_id.contains_key(&view_id)
5500 }) {
5501 anyhow::Ok(true)
5502 } else {
5503 anyhow::Ok(false)
5504 }
5505 } else {
5506 anyhow::Ok(false)
5507 }
5508 })??;
5509
5510 if should_add_view && let Some(view) = update_active_view.view {
5511 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5512 }
5513 }
5514 proto::update_followers::Variant::UpdateView(update_view) => {
5515 let variant = update_view.variant.context("missing update view variant")?;
5516 let id = update_view.id.context("missing update view id")?;
5517 let mut tasks = Vec::new();
5518 this.update_in(cx, |this, window, cx| {
5519 let project = this.project.clone();
5520 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5521 let view_id = ViewId::from_proto(id.clone())?;
5522 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5523 tasks.push(item.view.apply_update_proto(
5524 &project,
5525 variant.clone(),
5526 window,
5527 cx,
5528 ));
5529 }
5530 }
5531 anyhow::Ok(())
5532 })??;
5533 try_join_all(tasks).await.log_err();
5534 }
5535 }
5536 this.update_in(cx, |this, window, cx| {
5537 this.leader_updated(leader_id, window, cx)
5538 })?;
5539 Ok(())
5540 }
5541
5542 async fn add_view_from_leader(
5543 this: WeakEntity<Self>,
5544 leader_id: PeerId,
5545 view: &proto::View,
5546 cx: &mut AsyncWindowContext,
5547 ) -> Result<()> {
5548 let this = this.upgrade().context("workspace dropped")?;
5549
5550 let Some(id) = view.id.clone() else {
5551 anyhow::bail!("no id for view");
5552 };
5553 let id = ViewId::from_proto(id)?;
5554 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5555
5556 let pane = this.update(cx, |this, _cx| {
5557 let state = this
5558 .follower_states
5559 .get(&leader_id.into())
5560 .context("stopped following")?;
5561 anyhow::Ok(state.pane().clone())
5562 })?;
5563 let existing_item = pane.update_in(cx, |pane, window, cx| {
5564 let client = this.read(cx).client().clone();
5565 pane.items().find_map(|item| {
5566 let item = item.to_followable_item_handle(cx)?;
5567 if item.remote_id(&client, window, cx) == Some(id) {
5568 Some(item)
5569 } else {
5570 None
5571 }
5572 })
5573 })?;
5574 let item = if let Some(existing_item) = existing_item {
5575 existing_item
5576 } else {
5577 let variant = view.variant.clone();
5578 anyhow::ensure!(variant.is_some(), "missing view variant");
5579
5580 let task = cx.update(|window, cx| {
5581 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5582 })?;
5583
5584 let Some(task) = task else {
5585 anyhow::bail!(
5586 "failed to construct view from leader (maybe from a different version of zed?)"
5587 );
5588 };
5589
5590 let mut new_item = task.await?;
5591 pane.update_in(cx, |pane, window, cx| {
5592 let mut item_to_remove = None;
5593 for (ix, item) in pane.items().enumerate() {
5594 if let Some(item) = item.to_followable_item_handle(cx) {
5595 match new_item.dedup(item.as_ref(), window, cx) {
5596 Some(item::Dedup::KeepExisting) => {
5597 new_item =
5598 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5599 break;
5600 }
5601 Some(item::Dedup::ReplaceExisting) => {
5602 item_to_remove = Some((ix, item.item_id()));
5603 break;
5604 }
5605 None => {}
5606 }
5607 }
5608 }
5609
5610 if let Some((ix, id)) = item_to_remove {
5611 pane.remove_item(id, false, false, window, cx);
5612 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5613 }
5614 })?;
5615
5616 new_item
5617 };
5618
5619 this.update_in(cx, |this, window, cx| {
5620 let state = this.follower_states.get_mut(&leader_id.into())?;
5621 item.set_leader_id(Some(leader_id.into()), window, cx);
5622 state.items_by_leader_view_id.insert(
5623 id,
5624 FollowerView {
5625 view: item,
5626 location: panel_id,
5627 },
5628 );
5629
5630 Some(())
5631 })
5632 .context("no follower state")?;
5633
5634 Ok(())
5635 }
5636
5637 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5638 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5639 return;
5640 };
5641
5642 if let Some(agent_location) = self.project.read(cx).agent_location() {
5643 let buffer_entity_id = agent_location.buffer.entity_id();
5644 let view_id = ViewId {
5645 creator: CollaboratorId::Agent,
5646 id: buffer_entity_id.as_u64(),
5647 };
5648 follower_state.active_view_id = Some(view_id);
5649
5650 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5651 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5652 hash_map::Entry::Vacant(entry) => {
5653 let existing_view =
5654 follower_state
5655 .center_pane
5656 .read(cx)
5657 .items()
5658 .find_map(|item| {
5659 let item = item.to_followable_item_handle(cx)?;
5660 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5661 && item.project_item_model_ids(cx).as_slice()
5662 == [buffer_entity_id]
5663 {
5664 Some(item)
5665 } else {
5666 None
5667 }
5668 });
5669 let view = existing_view.or_else(|| {
5670 agent_location.buffer.upgrade().and_then(|buffer| {
5671 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
5672 registry.build_item(buffer, self.project.clone(), None, window, cx)
5673 })?
5674 .to_followable_item_handle(cx)
5675 })
5676 });
5677
5678 view.map(|view| {
5679 entry.insert(FollowerView {
5680 view,
5681 location: None,
5682 })
5683 })
5684 }
5685 };
5686
5687 if let Some(item) = item {
5688 item.view
5689 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
5690 item.view
5691 .update_agent_location(agent_location.position, window, cx);
5692 }
5693 } else {
5694 follower_state.active_view_id = None;
5695 }
5696
5697 self.leader_updated(CollaboratorId::Agent, window, cx);
5698 }
5699
5700 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
5701 let mut is_project_item = true;
5702 let mut update = proto::UpdateActiveView::default();
5703 if window.is_window_active() {
5704 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
5705
5706 if let Some(item) = active_item
5707 && item.item_focus_handle(cx).contains_focused(window, cx)
5708 {
5709 let leader_id = self
5710 .pane_for(&*item)
5711 .and_then(|pane| self.leader_for_pane(&pane));
5712 let leader_peer_id = match leader_id {
5713 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5714 Some(CollaboratorId::Agent) | None => None,
5715 };
5716
5717 if let Some(item) = item.to_followable_item_handle(cx) {
5718 let id = item
5719 .remote_id(&self.app_state.client, window, cx)
5720 .map(|id| id.to_proto());
5721
5722 if let Some(id) = id
5723 && let Some(variant) = item.to_state_proto(window, cx)
5724 {
5725 let view = Some(proto::View {
5726 id,
5727 leader_id: leader_peer_id,
5728 variant: Some(variant),
5729 panel_id: panel_id.map(|id| id as i32),
5730 });
5731
5732 is_project_item = item.is_project_item(window, cx);
5733 update = proto::UpdateActiveView { view };
5734 };
5735 }
5736 }
5737 }
5738
5739 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
5740 if active_view_id != self.last_active_view_id.as_ref() {
5741 self.last_active_view_id = active_view_id.cloned();
5742 self.update_followers(
5743 is_project_item,
5744 proto::update_followers::Variant::UpdateActiveView(update),
5745 window,
5746 cx,
5747 );
5748 }
5749 }
5750
5751 fn active_item_for_followers(
5752 &self,
5753 window: &mut Window,
5754 cx: &mut App,
5755 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
5756 let mut active_item = None;
5757 let mut panel_id = None;
5758 for dock in self.all_docks() {
5759 if dock.focus_handle(cx).contains_focused(window, cx)
5760 && let Some(panel) = dock.read(cx).active_panel()
5761 && let Some(pane) = panel.pane(cx)
5762 && let Some(item) = pane.read(cx).active_item()
5763 {
5764 active_item = Some(item);
5765 panel_id = panel.remote_id();
5766 break;
5767 }
5768 }
5769
5770 if active_item.is_none() {
5771 active_item = self.active_pane().read(cx).active_item();
5772 }
5773 (active_item, panel_id)
5774 }
5775
5776 fn update_followers(
5777 &self,
5778 project_only: bool,
5779 update: proto::update_followers::Variant,
5780 _: &mut Window,
5781 cx: &mut App,
5782 ) -> Option<()> {
5783 // If this update only applies to for followers in the current project,
5784 // then skip it unless this project is shared. If it applies to all
5785 // followers, regardless of project, then set `project_id` to none,
5786 // indicating that it goes to all followers.
5787 let project_id = if project_only {
5788 Some(self.project.read(cx).remote_id()?)
5789 } else {
5790 None
5791 };
5792 self.app_state().workspace_store.update(cx, |store, cx| {
5793 store.update_followers(project_id, update, cx)
5794 })
5795 }
5796
5797 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
5798 self.follower_states.iter().find_map(|(leader_id, state)| {
5799 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
5800 Some(*leader_id)
5801 } else {
5802 None
5803 }
5804 })
5805 }
5806
5807 fn leader_updated(
5808 &mut self,
5809 leader_id: impl Into<CollaboratorId>,
5810 window: &mut Window,
5811 cx: &mut Context<Self>,
5812 ) -> Option<Box<dyn ItemHandle>> {
5813 cx.notify();
5814
5815 let leader_id = leader_id.into();
5816 let (panel_id, item) = match leader_id {
5817 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
5818 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
5819 };
5820
5821 let state = self.follower_states.get(&leader_id)?;
5822 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
5823 let pane;
5824 if let Some(panel_id) = panel_id {
5825 pane = self
5826 .activate_panel_for_proto_id(panel_id, window, cx)?
5827 .pane(cx)?;
5828 let state = self.follower_states.get_mut(&leader_id)?;
5829 state.dock_pane = Some(pane.clone());
5830 } else {
5831 pane = state.center_pane.clone();
5832 let state = self.follower_states.get_mut(&leader_id)?;
5833 if let Some(dock_pane) = state.dock_pane.take() {
5834 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
5835 }
5836 }
5837
5838 pane.update(cx, |pane, cx| {
5839 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
5840 if let Some(index) = pane.index_for_item(item.as_ref()) {
5841 pane.activate_item(index, false, false, window, cx);
5842 } else {
5843 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
5844 }
5845
5846 if focus_active_item {
5847 pane.focus_active_item(window, cx)
5848 }
5849 });
5850
5851 Some(item)
5852 }
5853
5854 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
5855 let state = self.follower_states.get(&CollaboratorId::Agent)?;
5856 let active_view_id = state.active_view_id?;
5857 Some(
5858 state
5859 .items_by_leader_view_id
5860 .get(&active_view_id)?
5861 .view
5862 .boxed_clone(),
5863 )
5864 }
5865
5866 fn active_item_for_peer(
5867 &self,
5868 peer_id: PeerId,
5869 window: &mut Window,
5870 cx: &mut Context<Self>,
5871 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
5872 let call = self.active_call()?;
5873 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
5874 let leader_in_this_app;
5875 let leader_in_this_project;
5876 match participant.location {
5877 ParticipantLocation::SharedProject { project_id } => {
5878 leader_in_this_app = true;
5879 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
5880 }
5881 ParticipantLocation::UnsharedProject => {
5882 leader_in_this_app = true;
5883 leader_in_this_project = false;
5884 }
5885 ParticipantLocation::External => {
5886 leader_in_this_app = false;
5887 leader_in_this_project = false;
5888 }
5889 };
5890 let state = self.follower_states.get(&peer_id.into())?;
5891 let mut item_to_activate = None;
5892 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
5893 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
5894 && (leader_in_this_project || !item.view.is_project_item(window, cx))
5895 {
5896 item_to_activate = Some((item.location, item.view.boxed_clone()));
5897 }
5898 } else if let Some(shared_screen) =
5899 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
5900 {
5901 item_to_activate = Some((None, Box::new(shared_screen)));
5902 }
5903 item_to_activate
5904 }
5905
5906 fn shared_screen_for_peer(
5907 &self,
5908 peer_id: PeerId,
5909 pane: &Entity<Pane>,
5910 window: &mut Window,
5911 cx: &mut App,
5912 ) -> Option<Entity<SharedScreen>> {
5913 self.active_call()?
5914 .create_shared_screen(peer_id, pane, window, cx)
5915 }
5916
5917 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5918 if window.is_window_active() {
5919 self.update_active_view_for_followers(window, cx);
5920
5921 if let Some(database_id) = self.database_id {
5922 cx.background_spawn(persistence::DB.update_timestamp(database_id))
5923 .detach();
5924 }
5925 } else {
5926 for pane in &self.panes {
5927 pane.update(cx, |pane, cx| {
5928 if let Some(item) = pane.active_item() {
5929 item.workspace_deactivated(window, cx);
5930 }
5931 for item in pane.items() {
5932 if matches!(
5933 item.workspace_settings(cx).autosave,
5934 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
5935 ) {
5936 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
5937 .detach_and_log_err(cx);
5938 }
5939 }
5940 });
5941 }
5942 }
5943 }
5944
5945 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
5946 self.active_call.as_ref().map(|(call, _)| &*call.0)
5947 }
5948
5949 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
5950 self.active_call.as_ref().map(|(call, _)| call.clone())
5951 }
5952
5953 fn on_active_call_event(
5954 &mut self,
5955 event: &ActiveCallEvent,
5956 window: &mut Window,
5957 cx: &mut Context<Self>,
5958 ) {
5959 match event {
5960 ActiveCallEvent::ParticipantLocationChanged { participant_id }
5961 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
5962 self.leader_updated(participant_id, window, cx);
5963 }
5964 }
5965 }
5966
5967 pub fn database_id(&self) -> Option<WorkspaceId> {
5968 self.database_id
5969 }
5970
5971 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
5972 self.database_id = Some(id);
5973 }
5974
5975 pub fn session_id(&self) -> Option<String> {
5976 self.session_id.clone()
5977 }
5978
5979 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
5980 let Some(display) = window.display(cx) else {
5981 return Task::ready(());
5982 };
5983 let Ok(display_uuid) = display.uuid() else {
5984 return Task::ready(());
5985 };
5986
5987 let window_bounds = window.inner_window_bounds();
5988 let database_id = self.database_id;
5989 let has_paths = !self.root_paths(cx).is_empty();
5990
5991 cx.background_executor().spawn(async move {
5992 if !has_paths {
5993 persistence::write_default_window_bounds(window_bounds, display_uuid)
5994 .await
5995 .log_err();
5996 }
5997 if let Some(database_id) = database_id {
5998 DB.set_window_open_status(
5999 database_id,
6000 SerializedWindowBounds(window_bounds),
6001 display_uuid,
6002 )
6003 .await
6004 .log_err();
6005 } else {
6006 persistence::write_default_window_bounds(window_bounds, display_uuid)
6007 .await
6008 .log_err();
6009 }
6010 })
6011 }
6012
6013 /// Bypass the 200ms serialization throttle and write workspace state to
6014 /// the DB immediately. Returns a task the caller can await to ensure the
6015 /// write completes. Used by the quit handler so the most recent state
6016 /// isn't lost to a pending throttle timer when the process exits.
6017 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6018 self._schedule_serialize_workspace.take();
6019 self._serialize_workspace_task.take();
6020 self.bounds_save_task_queued.take();
6021
6022 let bounds_task = self.save_window_bounds(window, cx);
6023 let serialize_task = self.serialize_workspace_internal(window, cx);
6024 cx.spawn(async move |_| {
6025 bounds_task.await;
6026 serialize_task.await;
6027 })
6028 }
6029
6030 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6031 let project = self.project().read(cx);
6032 project
6033 .visible_worktrees(cx)
6034 .map(|worktree| worktree.read(cx).abs_path())
6035 .collect::<Vec<_>>()
6036 }
6037
6038 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6039 match member {
6040 Member::Axis(PaneAxis { members, .. }) => {
6041 for child in members.iter() {
6042 self.remove_panes(child.clone(), window, cx)
6043 }
6044 }
6045 Member::Pane(pane) => {
6046 self.force_remove_pane(&pane, &None, window, cx);
6047 }
6048 }
6049 }
6050
6051 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6052 self.session_id.take();
6053 self.serialize_workspace_internal(window, cx)
6054 }
6055
6056 fn force_remove_pane(
6057 &mut self,
6058 pane: &Entity<Pane>,
6059 focus_on: &Option<Entity<Pane>>,
6060 window: &mut Window,
6061 cx: &mut Context<Workspace>,
6062 ) {
6063 self.panes.retain(|p| p != pane);
6064 if let Some(focus_on) = focus_on {
6065 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6066 } else if self.active_pane() == pane {
6067 self.panes
6068 .last()
6069 .unwrap()
6070 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6071 }
6072 if self.last_active_center_pane == Some(pane.downgrade()) {
6073 self.last_active_center_pane = None;
6074 }
6075 cx.notify();
6076 }
6077
6078 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6079 if self._schedule_serialize_workspace.is_none() {
6080 self._schedule_serialize_workspace =
6081 Some(cx.spawn_in(window, async move |this, cx| {
6082 cx.background_executor()
6083 .timer(SERIALIZATION_THROTTLE_TIME)
6084 .await;
6085 this.update_in(cx, |this, window, cx| {
6086 this._serialize_workspace_task =
6087 Some(this.serialize_workspace_internal(window, cx));
6088 this._schedule_serialize_workspace.take();
6089 })
6090 .log_err();
6091 }));
6092 }
6093 }
6094
6095 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6096 let Some(database_id) = self.database_id() else {
6097 return Task::ready(());
6098 };
6099
6100 fn serialize_pane_handle(
6101 pane_handle: &Entity<Pane>,
6102 window: &mut Window,
6103 cx: &mut App,
6104 ) -> SerializedPane {
6105 let (items, active, pinned_count) = {
6106 let pane = pane_handle.read(cx);
6107 let active_item_id = pane.active_item().map(|item| item.item_id());
6108 (
6109 pane.items()
6110 .filter_map(|handle| {
6111 let handle = handle.to_serializable_item_handle(cx)?;
6112
6113 Some(SerializedItem {
6114 kind: Arc::from(handle.serialized_item_kind()),
6115 item_id: handle.item_id().as_u64(),
6116 active: Some(handle.item_id()) == active_item_id,
6117 preview: pane.is_active_preview_item(handle.item_id()),
6118 })
6119 })
6120 .collect::<Vec<_>>(),
6121 pane.has_focus(window, cx),
6122 pane.pinned_count(),
6123 )
6124 };
6125
6126 SerializedPane::new(items, active, pinned_count)
6127 }
6128
6129 fn build_serialized_pane_group(
6130 pane_group: &Member,
6131 window: &mut Window,
6132 cx: &mut App,
6133 ) -> SerializedPaneGroup {
6134 match pane_group {
6135 Member::Axis(PaneAxis {
6136 axis,
6137 members,
6138 state,
6139 }) => SerializedPaneGroup::Group {
6140 axis: SerializedAxis(*axis),
6141 children: members
6142 .iter()
6143 .map(|member| build_serialized_pane_group(member, window, cx))
6144 .collect::<Vec<_>>(),
6145 flexes: Some(state.flexes()),
6146 },
6147 Member::Pane(pane_handle) => {
6148 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6149 }
6150 }
6151 }
6152
6153 fn build_serialized_docks(
6154 this: &Workspace,
6155 window: &mut Window,
6156 cx: &mut App,
6157 ) -> DockStructure {
6158 this.capture_dock_state(window, cx)
6159 }
6160
6161 match self.workspace_location(cx) {
6162 WorkspaceLocation::Location(location, paths) => {
6163 let breakpoints = self.project.update(cx, |project, cx| {
6164 project
6165 .breakpoint_store()
6166 .read(cx)
6167 .all_source_breakpoints(cx)
6168 });
6169 let user_toolchains = self
6170 .project
6171 .read(cx)
6172 .user_toolchains(cx)
6173 .unwrap_or_default();
6174
6175 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6176 let docks = build_serialized_docks(self, window, cx);
6177 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6178
6179 let serialized_workspace = SerializedWorkspace {
6180 id: database_id,
6181 location,
6182 paths,
6183 center_group,
6184 window_bounds,
6185 display: Default::default(),
6186 docks,
6187 centered_layout: self.centered_layout,
6188 session_id: self.session_id.clone(),
6189 breakpoints,
6190 window_id: Some(window.window_handle().window_id().as_u64()),
6191 user_toolchains,
6192 };
6193
6194 window.spawn(cx, async move |_| {
6195 persistence::DB.save_workspace(serialized_workspace).await;
6196 })
6197 }
6198 WorkspaceLocation::DetachFromSession => {
6199 let window_bounds = SerializedWindowBounds(window.window_bounds());
6200 let display = window.display(cx).and_then(|d| d.uuid().ok());
6201 // Save dock state for empty local workspaces
6202 let docks = build_serialized_docks(self, window, cx);
6203 window.spawn(cx, async move |_| {
6204 persistence::DB
6205 .set_window_open_status(
6206 database_id,
6207 window_bounds,
6208 display.unwrap_or_default(),
6209 )
6210 .await
6211 .log_err();
6212 persistence::DB
6213 .set_session_id(database_id, None)
6214 .await
6215 .log_err();
6216 persistence::write_default_dock_state(docks).await.log_err();
6217 })
6218 }
6219 WorkspaceLocation::None => {
6220 // Save dock state for empty non-local workspaces
6221 let docks = build_serialized_docks(self, window, cx);
6222 window.spawn(cx, async move |_| {
6223 persistence::write_default_dock_state(docks).await.log_err();
6224 })
6225 }
6226 }
6227 }
6228
6229 fn has_any_items_open(&self, cx: &App) -> bool {
6230 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6231 }
6232
6233 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6234 let paths = PathList::new(&self.root_paths(cx));
6235 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6236 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6237 } else if self.project.read(cx).is_local() {
6238 if !paths.is_empty() || self.has_any_items_open(cx) {
6239 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6240 } else {
6241 WorkspaceLocation::DetachFromSession
6242 }
6243 } else {
6244 WorkspaceLocation::None
6245 }
6246 }
6247
6248 fn update_history(&self, cx: &mut App) {
6249 let Some(id) = self.database_id() else {
6250 return;
6251 };
6252 if !self.project.read(cx).is_local() {
6253 return;
6254 }
6255 if let Some(manager) = HistoryManager::global(cx) {
6256 let paths = PathList::new(&self.root_paths(cx));
6257 manager.update(cx, |this, cx| {
6258 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6259 });
6260 }
6261 }
6262
6263 async fn serialize_items(
6264 this: &WeakEntity<Self>,
6265 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6266 cx: &mut AsyncWindowContext,
6267 ) -> Result<()> {
6268 const CHUNK_SIZE: usize = 200;
6269
6270 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6271
6272 while let Some(items_received) = serializable_items.next().await {
6273 let unique_items =
6274 items_received
6275 .into_iter()
6276 .fold(HashMap::default(), |mut acc, item| {
6277 acc.entry(item.item_id()).or_insert(item);
6278 acc
6279 });
6280
6281 // We use into_iter() here so that the references to the items are moved into
6282 // the tasks and not kept alive while we're sleeping.
6283 for (_, item) in unique_items.into_iter() {
6284 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6285 item.serialize(workspace, false, window, cx)
6286 }) {
6287 cx.background_spawn(async move { task.await.log_err() })
6288 .detach();
6289 }
6290 }
6291
6292 cx.background_executor()
6293 .timer(SERIALIZATION_THROTTLE_TIME)
6294 .await;
6295 }
6296
6297 Ok(())
6298 }
6299
6300 pub(crate) fn enqueue_item_serialization(
6301 &mut self,
6302 item: Box<dyn SerializableItemHandle>,
6303 ) -> Result<()> {
6304 self.serializable_items_tx
6305 .unbounded_send(item)
6306 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6307 }
6308
6309 pub(crate) fn load_workspace(
6310 serialized_workspace: SerializedWorkspace,
6311 paths_to_open: Vec<Option<ProjectPath>>,
6312 window: &mut Window,
6313 cx: &mut Context<Workspace>,
6314 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6315 cx.spawn_in(window, async move |workspace, cx| {
6316 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6317
6318 let mut center_group = None;
6319 let mut center_items = None;
6320
6321 // Traverse the splits tree and add to things
6322 if let Some((group, active_pane, items)) = serialized_workspace
6323 .center_group
6324 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6325 .await
6326 {
6327 center_items = Some(items);
6328 center_group = Some((group, active_pane))
6329 }
6330
6331 let mut items_by_project_path = HashMap::default();
6332 let mut item_ids_by_kind = HashMap::default();
6333 let mut all_deserialized_items = Vec::default();
6334 cx.update(|_, cx| {
6335 for item in center_items.unwrap_or_default().into_iter().flatten() {
6336 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6337 item_ids_by_kind
6338 .entry(serializable_item_handle.serialized_item_kind())
6339 .or_insert(Vec::new())
6340 .push(item.item_id().as_u64() as ItemId);
6341 }
6342
6343 if let Some(project_path) = item.project_path(cx) {
6344 items_by_project_path.insert(project_path, item.clone());
6345 }
6346 all_deserialized_items.push(item);
6347 }
6348 })?;
6349
6350 let opened_items = paths_to_open
6351 .into_iter()
6352 .map(|path_to_open| {
6353 path_to_open
6354 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6355 })
6356 .collect::<Vec<_>>();
6357
6358 // Remove old panes from workspace panes list
6359 workspace.update_in(cx, |workspace, window, cx| {
6360 if let Some((center_group, active_pane)) = center_group {
6361 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6362
6363 // Swap workspace center group
6364 workspace.center = PaneGroup::with_root(center_group);
6365 workspace.center.set_is_center(true);
6366 workspace.center.mark_positions(cx);
6367
6368 if let Some(active_pane) = active_pane {
6369 workspace.set_active_pane(&active_pane, window, cx);
6370 cx.focus_self(window);
6371 } else {
6372 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6373 }
6374 }
6375
6376 let docks = serialized_workspace.docks;
6377
6378 for (dock, serialized_dock) in [
6379 (&mut workspace.right_dock, docks.right),
6380 (&mut workspace.left_dock, docks.left),
6381 (&mut workspace.bottom_dock, docks.bottom),
6382 ]
6383 .iter_mut()
6384 {
6385 dock.update(cx, |dock, cx| {
6386 dock.serialized_dock = Some(serialized_dock.clone());
6387 dock.restore_state(window, cx);
6388 });
6389 }
6390
6391 cx.notify();
6392 })?;
6393
6394 let _ = project
6395 .update(cx, |project, cx| {
6396 project
6397 .breakpoint_store()
6398 .update(cx, |breakpoint_store, cx| {
6399 breakpoint_store
6400 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6401 })
6402 })
6403 .await;
6404
6405 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6406 // after loading the items, we might have different items and in order to avoid
6407 // the database filling up, we delete items that haven't been loaded now.
6408 //
6409 // The items that have been loaded, have been saved after they've been added to the workspace.
6410 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6411 item_ids_by_kind
6412 .into_iter()
6413 .map(|(item_kind, loaded_items)| {
6414 SerializableItemRegistry::cleanup(
6415 item_kind,
6416 serialized_workspace.id,
6417 loaded_items,
6418 window,
6419 cx,
6420 )
6421 .log_err()
6422 })
6423 .collect::<Vec<_>>()
6424 })?;
6425
6426 futures::future::join_all(clean_up_tasks).await;
6427
6428 workspace
6429 .update_in(cx, |workspace, window, cx| {
6430 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6431 workspace.serialize_workspace_internal(window, cx).detach();
6432
6433 // Ensure that we mark the window as edited if we did load dirty items
6434 workspace.update_window_edited(window, cx);
6435 })
6436 .ok();
6437
6438 Ok(opened_items)
6439 })
6440 }
6441
6442 pub fn key_context(&self, cx: &App) -> KeyContext {
6443 let mut context = KeyContext::new_with_defaults();
6444 context.add("Workspace");
6445 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6446 if let Some(status) = self
6447 .debugger_provider
6448 .as_ref()
6449 .and_then(|provider| provider.active_thread_state(cx))
6450 {
6451 match status {
6452 ThreadStatus::Running | ThreadStatus::Stepping => {
6453 context.add("debugger_running");
6454 }
6455 ThreadStatus::Stopped => context.add("debugger_stopped"),
6456 ThreadStatus::Exited | ThreadStatus::Ended => {}
6457 }
6458 }
6459
6460 if self.left_dock.read(cx).is_open() {
6461 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6462 context.set("left_dock", active_panel.panel_key());
6463 }
6464 }
6465
6466 if self.right_dock.read(cx).is_open() {
6467 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6468 context.set("right_dock", active_panel.panel_key());
6469 }
6470 }
6471
6472 if self.bottom_dock.read(cx).is_open() {
6473 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6474 context.set("bottom_dock", active_panel.panel_key());
6475 }
6476 }
6477
6478 context
6479 }
6480
6481 /// Multiworkspace uses this to add workspace action handling to itself
6482 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6483 self.add_workspace_actions_listeners(div, window, cx)
6484 .on_action(cx.listener(
6485 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6486 for action in &action_sequence.0 {
6487 window.dispatch_action(action.boxed_clone(), cx);
6488 }
6489 },
6490 ))
6491 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6492 .on_action(cx.listener(Self::close_all_items_and_panes))
6493 .on_action(cx.listener(Self::close_item_in_all_panes))
6494 .on_action(cx.listener(Self::save_all))
6495 .on_action(cx.listener(Self::send_keystrokes))
6496 .on_action(cx.listener(Self::add_folder_to_project))
6497 .on_action(cx.listener(Self::follow_next_collaborator))
6498 .on_action(cx.listener(Self::activate_pane_at_index))
6499 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6500 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6501 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6502 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6503 let pane = workspace.active_pane().clone();
6504 workspace.unfollow_in_pane(&pane, window, cx);
6505 }))
6506 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6507 workspace
6508 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6509 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6510 }))
6511 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6512 workspace
6513 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6514 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6515 }))
6516 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6517 workspace
6518 .save_active_item(SaveIntent::SaveAs, window, cx)
6519 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6520 }))
6521 .on_action(
6522 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6523 workspace.activate_previous_pane(window, cx)
6524 }),
6525 )
6526 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6527 workspace.activate_next_pane(window, cx)
6528 }))
6529 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6530 workspace.activate_last_pane(window, cx)
6531 }))
6532 .on_action(
6533 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6534 workspace.activate_next_window(cx)
6535 }),
6536 )
6537 .on_action(
6538 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6539 workspace.activate_previous_window(cx)
6540 }),
6541 )
6542 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6543 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6544 }))
6545 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6546 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6547 }))
6548 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6549 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6550 }))
6551 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6552 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6553 }))
6554 .on_action(cx.listener(
6555 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6556 workspace.move_item_to_pane_in_direction(action, window, cx)
6557 },
6558 ))
6559 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6560 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6561 }))
6562 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6563 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6564 }))
6565 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6566 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6567 }))
6568 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6569 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6570 }))
6571 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6572 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6573 SplitDirection::Down,
6574 SplitDirection::Up,
6575 SplitDirection::Right,
6576 SplitDirection::Left,
6577 ];
6578 for dir in DIRECTION_PRIORITY {
6579 if workspace.find_pane_in_direction(dir, cx).is_some() {
6580 workspace.swap_pane_in_direction(dir, cx);
6581 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6582 break;
6583 }
6584 }
6585 }))
6586 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6587 workspace.move_pane_to_border(SplitDirection::Left, cx)
6588 }))
6589 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6590 workspace.move_pane_to_border(SplitDirection::Right, cx)
6591 }))
6592 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6593 workspace.move_pane_to_border(SplitDirection::Up, cx)
6594 }))
6595 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6596 workspace.move_pane_to_border(SplitDirection::Down, cx)
6597 }))
6598 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6599 this.toggle_dock(DockPosition::Left, window, cx);
6600 }))
6601 .on_action(cx.listener(
6602 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6603 workspace.toggle_dock(DockPosition::Right, window, cx);
6604 },
6605 ))
6606 .on_action(cx.listener(
6607 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6608 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6609 },
6610 ))
6611 .on_action(cx.listener(
6612 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6613 if !workspace.close_active_dock(window, cx) {
6614 cx.propagate();
6615 }
6616 },
6617 ))
6618 .on_action(
6619 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6620 workspace.close_all_docks(window, cx);
6621 }),
6622 )
6623 .on_action(cx.listener(Self::toggle_all_docks))
6624 .on_action(cx.listener(
6625 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6626 workspace.clear_all_notifications(cx);
6627 },
6628 ))
6629 .on_action(cx.listener(
6630 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6631 workspace.clear_navigation_history(window, cx);
6632 },
6633 ))
6634 .on_action(cx.listener(
6635 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6636 if let Some((notification_id, _)) = workspace.notifications.pop() {
6637 workspace.suppress_notification(¬ification_id, cx);
6638 }
6639 },
6640 ))
6641 .on_action(cx.listener(
6642 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6643 workspace.show_worktree_trust_security_modal(true, window, cx);
6644 },
6645 ))
6646 .on_action(
6647 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6648 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6649 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6650 trusted_worktrees.clear_trusted_paths()
6651 });
6652 let clear_task = persistence::DB.clear_trusted_worktrees();
6653 cx.spawn(async move |_, cx| {
6654 if clear_task.await.log_err().is_some() {
6655 cx.update(|cx| reload(cx));
6656 }
6657 })
6658 .detach();
6659 }
6660 }),
6661 )
6662 .on_action(cx.listener(
6663 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
6664 workspace.reopen_closed_item(window, cx).detach();
6665 },
6666 ))
6667 .on_action(cx.listener(
6668 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
6669 for dock in workspace.all_docks() {
6670 if dock.focus_handle(cx).contains_focused(window, cx) {
6671 let Some(panel) = dock.read(cx).active_panel() else {
6672 return;
6673 };
6674
6675 // Set to `None`, then the size will fall back to the default.
6676 panel.clone().set_size(None, window, cx);
6677
6678 return;
6679 }
6680 }
6681 },
6682 ))
6683 .on_action(cx.listener(
6684 |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
6685 for dock in workspace.all_docks() {
6686 if let Some(panel) = dock.read(cx).visible_panel() {
6687 // Set to `None`, then the size will fall back to the default.
6688 panel.clone().set_size(None, window, cx);
6689 }
6690 }
6691 },
6692 ))
6693 .on_action(cx.listener(
6694 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
6695 adjust_active_dock_size_by_px(
6696 px_with_ui_font_fallback(act.px, cx),
6697 workspace,
6698 window,
6699 cx,
6700 );
6701 },
6702 ))
6703 .on_action(cx.listener(
6704 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
6705 adjust_active_dock_size_by_px(
6706 px_with_ui_font_fallback(act.px, cx) * -1.,
6707 workspace,
6708 window,
6709 cx,
6710 );
6711 },
6712 ))
6713 .on_action(cx.listener(
6714 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
6715 adjust_open_docks_size_by_px(
6716 px_with_ui_font_fallback(act.px, cx),
6717 workspace,
6718 window,
6719 cx,
6720 );
6721 },
6722 ))
6723 .on_action(cx.listener(
6724 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
6725 adjust_open_docks_size_by_px(
6726 px_with_ui_font_fallback(act.px, cx) * -1.,
6727 workspace,
6728 window,
6729 cx,
6730 );
6731 },
6732 ))
6733 .on_action(cx.listener(Workspace::toggle_centered_layout))
6734 .on_action(cx.listener(
6735 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
6736 if let Some(active_dock) = workspace.active_dock(window, cx) {
6737 let dock = active_dock.read(cx);
6738 if let Some(active_panel) = dock.active_panel() {
6739 if active_panel.pane(cx).is_none() {
6740 let mut recent_pane: Option<Entity<Pane>> = None;
6741 let mut recent_timestamp = 0;
6742 for pane_handle in workspace.panes() {
6743 let pane = pane_handle.read(cx);
6744 for entry in pane.activation_history() {
6745 if entry.timestamp > recent_timestamp {
6746 recent_timestamp = entry.timestamp;
6747 recent_pane = Some(pane_handle.clone());
6748 }
6749 }
6750 }
6751
6752 if let Some(pane) = recent_pane {
6753 pane.update(cx, |pane, cx| {
6754 let current_index = pane.active_item_index();
6755 let items_len = pane.items_len();
6756 if items_len > 0 {
6757 let next_index = if current_index + 1 < items_len {
6758 current_index + 1
6759 } else {
6760 0
6761 };
6762 pane.activate_item(
6763 next_index, false, false, window, cx,
6764 );
6765 }
6766 });
6767 return;
6768 }
6769 }
6770 }
6771 }
6772 cx.propagate();
6773 },
6774 ))
6775 .on_action(cx.listener(
6776 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
6777 if let Some(active_dock) = workspace.active_dock(window, cx) {
6778 let dock = active_dock.read(cx);
6779 if let Some(active_panel) = dock.active_panel() {
6780 if active_panel.pane(cx).is_none() {
6781 let mut recent_pane: Option<Entity<Pane>> = None;
6782 let mut recent_timestamp = 0;
6783 for pane_handle in workspace.panes() {
6784 let pane = pane_handle.read(cx);
6785 for entry in pane.activation_history() {
6786 if entry.timestamp > recent_timestamp {
6787 recent_timestamp = entry.timestamp;
6788 recent_pane = Some(pane_handle.clone());
6789 }
6790 }
6791 }
6792
6793 if let Some(pane) = recent_pane {
6794 pane.update(cx, |pane, cx| {
6795 let current_index = pane.active_item_index();
6796 let items_len = pane.items_len();
6797 if items_len > 0 {
6798 let prev_index = if current_index > 0 {
6799 current_index - 1
6800 } else {
6801 items_len.saturating_sub(1)
6802 };
6803 pane.activate_item(
6804 prev_index, false, false, window, cx,
6805 );
6806 }
6807 });
6808 return;
6809 }
6810 }
6811 }
6812 }
6813 cx.propagate();
6814 },
6815 ))
6816 .on_action(cx.listener(
6817 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
6818 if let Some(active_dock) = workspace.active_dock(window, cx) {
6819 let dock = active_dock.read(cx);
6820 if let Some(active_panel) = dock.active_panel() {
6821 if active_panel.pane(cx).is_none() {
6822 let active_pane = workspace.active_pane().clone();
6823 active_pane.update(cx, |pane, cx| {
6824 pane.close_active_item(action, window, cx)
6825 .detach_and_log_err(cx);
6826 });
6827 return;
6828 }
6829 }
6830 }
6831 cx.propagate();
6832 },
6833 ))
6834 .on_action(
6835 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
6836 let pane = workspace.active_pane().clone();
6837 if let Some(item) = pane.read(cx).active_item() {
6838 item.toggle_read_only(window, cx);
6839 }
6840 }),
6841 )
6842 .on_action(cx.listener(Workspace::cancel))
6843 }
6844
6845 #[cfg(any(test, feature = "test-support"))]
6846 pub fn set_random_database_id(&mut self) {
6847 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
6848 }
6849
6850 #[cfg(any(test, feature = "test-support"))]
6851 pub(crate) fn test_new(
6852 project: Entity<Project>,
6853 window: &mut Window,
6854 cx: &mut Context<Self>,
6855 ) -> Self {
6856 use node_runtime::NodeRuntime;
6857 use session::Session;
6858
6859 let client = project.read(cx).client();
6860 let user_store = project.read(cx).user_store();
6861 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
6862 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
6863 window.activate_window();
6864 let app_state = Arc::new(AppState {
6865 languages: project.read(cx).languages().clone(),
6866 workspace_store,
6867 client,
6868 user_store,
6869 fs: project.read(cx).fs().clone(),
6870 build_window_options: |_, _| Default::default(),
6871 node_runtime: NodeRuntime::unavailable(),
6872 session,
6873 });
6874 let workspace = Self::new(Default::default(), project, app_state, window, cx);
6875 workspace
6876 .active_pane
6877 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6878 workspace
6879 }
6880
6881 pub fn register_action<A: Action>(
6882 &mut self,
6883 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
6884 ) -> &mut Self {
6885 let callback = Arc::new(callback);
6886
6887 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
6888 let callback = callback.clone();
6889 div.on_action(cx.listener(move |workspace, event, window, cx| {
6890 (callback)(workspace, event, window, cx)
6891 }))
6892 }));
6893 self
6894 }
6895 pub fn register_action_renderer(
6896 &mut self,
6897 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
6898 ) -> &mut Self {
6899 self.workspace_actions.push(Box::new(callback));
6900 self
6901 }
6902
6903 fn add_workspace_actions_listeners(
6904 &self,
6905 mut div: Div,
6906 window: &mut Window,
6907 cx: &mut Context<Self>,
6908 ) -> Div {
6909 for action in self.workspace_actions.iter() {
6910 div = (action)(div, self, window, cx)
6911 }
6912 div
6913 }
6914
6915 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
6916 self.modal_layer.read(cx).has_active_modal()
6917 }
6918
6919 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
6920 self.modal_layer.read(cx).active_modal()
6921 }
6922
6923 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
6924 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
6925 /// If no modal is active, the new modal will be shown.
6926 ///
6927 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
6928 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
6929 /// will not be shown.
6930 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
6931 where
6932 B: FnOnce(&mut Window, &mut Context<V>) -> V,
6933 {
6934 self.modal_layer.update(cx, |modal_layer, cx| {
6935 modal_layer.toggle_modal(window, cx, build)
6936 })
6937 }
6938
6939 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
6940 self.modal_layer
6941 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
6942 }
6943
6944 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
6945 self.toast_layer
6946 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
6947 }
6948
6949 pub fn toggle_centered_layout(
6950 &mut self,
6951 _: &ToggleCenteredLayout,
6952 _: &mut Window,
6953 cx: &mut Context<Self>,
6954 ) {
6955 self.centered_layout = !self.centered_layout;
6956 if let Some(database_id) = self.database_id() {
6957 cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
6958 .detach_and_log_err(cx);
6959 }
6960 cx.notify();
6961 }
6962
6963 fn adjust_padding(padding: Option<f32>) -> f32 {
6964 padding
6965 .unwrap_or(CenteredPaddingSettings::default().0)
6966 .clamp(
6967 CenteredPaddingSettings::MIN_PADDING,
6968 CenteredPaddingSettings::MAX_PADDING,
6969 )
6970 }
6971
6972 fn render_dock(
6973 &self,
6974 position: DockPosition,
6975 dock: &Entity<Dock>,
6976 window: &mut Window,
6977 cx: &mut Context<Self>,
6978 ) -> impl Iterator<Item = AnyElement> {
6979 let mut results = [None, None];
6980
6981 if self.zoomed_position == Some(position) {
6982 return results.into_iter().flatten();
6983 }
6984
6985 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
6986 let pane = panel.pane(cx)?;
6987 let follower_states = &self.follower_states;
6988 leader_border_for_pane(follower_states, &pane, window, cx)
6989 });
6990
6991 let fixed_content = {
6992 let dispatch_context = Dock::dispatch_context();
6993 if let Some(panel) = dock
6994 .read(cx)
6995 .visible_panel()
6996 .filter(|panel| panel.has_panel_content(window, cx))
6997 {
6998 let size = panel.size(window, cx);
6999
7000 let panel_content = panel
7001 .to_any()
7002 .cached(StyleRefinement::default().v_flex().size_full());
7003
7004 div()
7005 .key_context(dispatch_context)
7006 .track_focus(&self.focus_handle(cx))
7007 .flex()
7008 .bg(cx.theme().colors().panel_background)
7009 .border_color(cx.theme().colors().border)
7010 .overflow_hidden()
7011 .map(|this| match position.axis() {
7012 Axis::Horizontal => this
7013 .h_full()
7014 .flex_row()
7015 .child(div().w(size).h_full().child(panel_content)),
7016 Axis::Vertical => this
7017 .w_full()
7018 .flex_col()
7019 .child(div().h(size).w_full().child(panel_content)),
7020 })
7021 .map(|this| match position {
7022 DockPosition::Left => this.border_r_1(),
7023 DockPosition::Right => this.border_l_1(),
7024 DockPosition::Bottom => this.border_t_1(),
7025 })
7026 .when(dock.read(cx).resizable(cx), |this| {
7027 this.child(dock::create_resize_handle(position, DockPart::Fixed, cx))
7028 })
7029 } else {
7030 div()
7031 .key_context(dispatch_context)
7032 .track_focus(&self.focus_handle(cx))
7033 }
7034 };
7035
7036 results[0] = Some(
7037 div()
7038 .flex()
7039 .flex_none()
7040 .overflow_hidden()
7041 .child(fixed_content)
7042 .children(leader_border)
7043 .into_any_element(),
7044 );
7045
7046 results[1] = dock
7047 .read(cx)
7048 .visible_panel()
7049 .cloned()
7050 .and_then(|panel| panel.flex_content(window, cx))
7051 .map(|flex_content| {
7052 div()
7053 .h_full()
7054 .flex_1()
7055 .min_w(px(10.))
7056 .flex_grow()
7057 .when(position == DockPosition::Right, |this| {
7058 this.child(dock::create_resize_handle(position, DockPart::Flexible, cx))
7059 })
7060 .child(flex_content)
7061 .when(position == DockPosition::Left, |this| {
7062 this.child(dock::create_resize_handle(position, DockPart::Flexible, cx))
7063 })
7064 .into_any_element()
7065 });
7066
7067 if position == DockPosition::Right {
7068 results.swap(0, 1);
7069 }
7070
7071 results.into_iter().flatten()
7072 }
7073
7074 fn render_center(
7075 &mut self,
7076 paddings: (Option<Div>, Option<Div>),
7077 window: &mut Window,
7078 cx: &mut App,
7079 ) -> AnyElement {
7080 h_flex()
7081 .flex_1()
7082 .child(
7083 h_flex()
7084 .size_full()
7085 .flex_1()
7086 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7087 .child(self.center.render(
7088 self.zoomed.as_ref(),
7089 &PaneRenderContext {
7090 follower_states: &self.follower_states,
7091 active_call: self.active_call(),
7092 active_pane: &self.active_pane,
7093 app_state: &self.app_state,
7094 project: &self.project,
7095 workspace: &self.weak_self,
7096 },
7097 window,
7098 cx,
7099 ))
7100 .when_some(paddings.1, |this, p| this.child(p.border_l_1()))
7101 .into_any_element(),
7102 )
7103 .into_any_element()
7104 }
7105
7106 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7107 window
7108 .root::<MultiWorkspace>()
7109 .flatten()
7110 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7111 }
7112
7113 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7114 self.zoomed.as_ref()
7115 }
7116
7117 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7118 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7119 return;
7120 };
7121 let windows = cx.windows();
7122 let next_window =
7123 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7124 || {
7125 windows
7126 .iter()
7127 .cycle()
7128 .skip_while(|window| window.window_id() != current_window_id)
7129 .nth(1)
7130 },
7131 );
7132
7133 if let Some(window) = next_window {
7134 window
7135 .update(cx, |_, window, _| window.activate_window())
7136 .ok();
7137 }
7138 }
7139
7140 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7141 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7142 return;
7143 };
7144 let windows = cx.windows();
7145 let prev_window =
7146 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7147 || {
7148 windows
7149 .iter()
7150 .rev()
7151 .cycle()
7152 .skip_while(|window| window.window_id() != current_window_id)
7153 .nth(1)
7154 },
7155 );
7156
7157 if let Some(window) = prev_window {
7158 window
7159 .update(cx, |_, window, _| window.activate_window())
7160 .ok();
7161 }
7162 }
7163
7164 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7165 if cx.stop_active_drag(window) {
7166 } else if let Some((notification_id, _)) = self.notifications.pop() {
7167 dismiss_app_notification(¬ification_id, cx);
7168 } else {
7169 cx.propagate();
7170 }
7171 }
7172
7173 fn adjust_dock_size_by_px(
7174 &mut self,
7175 panel_size: Pixels,
7176 dock_pos: DockPosition,
7177 px: Pixels,
7178 window: &mut Window,
7179 cx: &mut Context<Self>,
7180 ) {
7181 match dock_pos {
7182 DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
7183 DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
7184 DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
7185 }
7186 }
7187
7188 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7189 let workspace_width = self.bounds.size.width;
7190 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7191
7192 self.right_dock.read_with(cx, |right_dock, cx| {
7193 let right_dock_size = right_dock
7194 .active_panel_size(window, cx)
7195 .unwrap_or(Pixels::ZERO);
7196 if right_dock_size + size > workspace_width {
7197 size = workspace_width - right_dock_size
7198 }
7199 });
7200
7201 self.left_dock.update(cx, |left_dock, cx| {
7202 if WorkspaceSettings::get_global(cx)
7203 .resize_all_panels_in_dock
7204 .contains(&DockPosition::Left)
7205 {
7206 left_dock.resize_all_panels(Some(size), window, cx);
7207 } else {
7208 left_dock.resize_active_panel(Some(size), window, cx);
7209 }
7210 });
7211 }
7212
7213 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7214 let workspace_width = self.bounds.size.width;
7215 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7216 self.left_dock.read_with(cx, |left_dock, cx| {
7217 let left_dock_size = left_dock
7218 .active_panel_size(window, cx)
7219 .unwrap_or(Pixels::ZERO);
7220 if left_dock_size + size > workspace_width {
7221 size = workspace_width - left_dock_size
7222 }
7223 });
7224 self.right_dock.update(cx, |right_dock, cx| {
7225 if WorkspaceSettings::get_global(cx)
7226 .resize_all_panels_in_dock
7227 .contains(&DockPosition::Right)
7228 {
7229 right_dock.resize_all_panels(Some(size), window, cx);
7230 } else {
7231 right_dock.resize_active_panel(Some(size), window, cx);
7232 }
7233 });
7234 }
7235
7236 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7237 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7238 self.bottom_dock.update(cx, |bottom_dock, cx| {
7239 if WorkspaceSettings::get_global(cx)
7240 .resize_all_panels_in_dock
7241 .contains(&DockPosition::Bottom)
7242 {
7243 bottom_dock.resize_all_panels(Some(size), window, cx);
7244 } else {
7245 bottom_dock.resize_active_panel(Some(size), window, cx);
7246 }
7247 });
7248 }
7249
7250 fn toggle_edit_predictions_all_files(
7251 &mut self,
7252 _: &ToggleEditPrediction,
7253 _window: &mut Window,
7254 cx: &mut Context<Self>,
7255 ) {
7256 let fs = self.project().read(cx).fs().clone();
7257 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7258 update_settings_file(fs, cx, move |file, _| {
7259 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7260 });
7261 }
7262
7263 pub fn show_worktree_trust_security_modal(
7264 &mut self,
7265 toggle: bool,
7266 window: &mut Window,
7267 cx: &mut Context<Self>,
7268 ) {
7269 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7270 if toggle {
7271 security_modal.update(cx, |security_modal, cx| {
7272 security_modal.dismiss(cx);
7273 })
7274 } else {
7275 security_modal.update(cx, |security_modal, cx| {
7276 security_modal.refresh_restricted_paths(cx);
7277 });
7278 }
7279 } else {
7280 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7281 .map(|trusted_worktrees| {
7282 trusted_worktrees
7283 .read(cx)
7284 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7285 })
7286 .unwrap_or(false);
7287 if has_restricted_worktrees {
7288 let project = self.project().read(cx);
7289 let remote_host = project
7290 .remote_connection_options(cx)
7291 .map(RemoteHostLocation::from);
7292 let worktree_store = project.worktree_store().downgrade();
7293 self.toggle_modal(window, cx, |_, cx| {
7294 SecurityModal::new(worktree_store, remote_host, cx)
7295 });
7296 }
7297 }
7298 }
7299}
7300
7301fn render_resize_handle() -> impl IntoElement {
7302 // FIXME: actually render the handle and wire it up.
7303 div().debug_bg_magenta()
7304}
7305
7306pub trait AnyActiveCall {
7307 fn entity(&self) -> AnyEntity;
7308 fn is_in_room(&self, _: &App) -> bool;
7309 fn room_id(&self, _: &App) -> Option<u64>;
7310 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7311 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7312 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7313 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7314 fn is_sharing_project(&self, _: &App) -> bool;
7315 fn has_remote_participants(&self, _: &App) -> bool;
7316 fn local_participant_is_guest(&self, _: &App) -> bool;
7317 fn client(&self, _: &App) -> Arc<Client>;
7318 fn share_on_join(&self, _: &App) -> bool;
7319 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7320 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7321 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7322 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7323 fn join_project(
7324 &self,
7325 _: u64,
7326 _: Arc<LanguageRegistry>,
7327 _: Arc<dyn Fs>,
7328 _: &mut App,
7329 ) -> Task<Result<Entity<Project>>>;
7330 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7331 fn subscribe(
7332 &self,
7333 _: &mut Window,
7334 _: &mut Context<Workspace>,
7335 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7336 ) -> Subscription;
7337 fn create_shared_screen(
7338 &self,
7339 _: PeerId,
7340 _: &Entity<Pane>,
7341 _: &mut Window,
7342 _: &mut App,
7343 ) -> Option<Entity<SharedScreen>>;
7344}
7345
7346#[derive(Clone)]
7347pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7348impl Global for GlobalAnyActiveCall {}
7349
7350impl GlobalAnyActiveCall {
7351 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7352 cx.try_global()
7353 }
7354
7355 pub(crate) fn global(cx: &App) -> &Self {
7356 cx.global()
7357 }
7358}
7359/// Workspace-local view of a remote participant's location.
7360#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7361pub enum ParticipantLocation {
7362 SharedProject { project_id: u64 },
7363 UnsharedProject,
7364 External,
7365}
7366
7367impl ParticipantLocation {
7368 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7369 match location
7370 .and_then(|l| l.variant)
7371 .context("participant location was not provided")?
7372 {
7373 proto::participant_location::Variant::SharedProject(project) => {
7374 Ok(Self::SharedProject {
7375 project_id: project.id,
7376 })
7377 }
7378 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7379 proto::participant_location::Variant::External(_) => Ok(Self::External),
7380 }
7381 }
7382}
7383/// Workspace-local view of a remote collaborator's state.
7384/// This is the subset of `call::RemoteParticipant` that workspace needs.
7385#[derive(Clone)]
7386pub struct RemoteCollaborator {
7387 pub user: Arc<User>,
7388 pub peer_id: PeerId,
7389 pub location: ParticipantLocation,
7390 pub participant_index: ParticipantIndex,
7391}
7392
7393pub enum ActiveCallEvent {
7394 ParticipantLocationChanged { participant_id: PeerId },
7395 RemoteVideoTracksChanged { participant_id: PeerId },
7396}
7397
7398fn leader_border_for_pane(
7399 follower_states: &HashMap<CollaboratorId, FollowerState>,
7400 pane: &Entity<Pane>,
7401 _: &Window,
7402 cx: &App,
7403) -> Option<Div> {
7404 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7405 if state.pane() == pane {
7406 Some((*leader_id, state))
7407 } else {
7408 None
7409 }
7410 })?;
7411
7412 let mut leader_color = match leader_id {
7413 CollaboratorId::PeerId(leader_peer_id) => {
7414 let leader = GlobalAnyActiveCall::try_global(cx)?
7415 .0
7416 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7417
7418 cx.theme()
7419 .players()
7420 .color_for_participant(leader.participant_index.0)
7421 .cursor
7422 }
7423 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7424 };
7425 leader_color.fade_out(0.3);
7426 Some(
7427 div()
7428 .absolute()
7429 .size_full()
7430 .left_0()
7431 .top_0()
7432 .border_2()
7433 .border_color(leader_color),
7434 )
7435}
7436
7437fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7438 ZED_WINDOW_POSITION
7439 .zip(*ZED_WINDOW_SIZE)
7440 .map(|(position, size)| Bounds {
7441 origin: position,
7442 size,
7443 })
7444}
7445
7446fn open_items(
7447 serialized_workspace: Option<SerializedWorkspace>,
7448 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7449 window: &mut Window,
7450 cx: &mut Context<Workspace>,
7451) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7452 let restored_items = serialized_workspace.map(|serialized_workspace| {
7453 Workspace::load_workspace(
7454 serialized_workspace,
7455 project_paths_to_open
7456 .iter()
7457 .map(|(_, project_path)| project_path)
7458 .cloned()
7459 .collect(),
7460 window,
7461 cx,
7462 )
7463 });
7464
7465 cx.spawn_in(window, async move |workspace, cx| {
7466 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7467
7468 if let Some(restored_items) = restored_items {
7469 let restored_items = restored_items.await?;
7470
7471 let restored_project_paths = restored_items
7472 .iter()
7473 .filter_map(|item| {
7474 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7475 .ok()
7476 .flatten()
7477 })
7478 .collect::<HashSet<_>>();
7479
7480 for restored_item in restored_items {
7481 opened_items.push(restored_item.map(Ok));
7482 }
7483
7484 project_paths_to_open
7485 .iter_mut()
7486 .for_each(|(_, project_path)| {
7487 if let Some(project_path_to_open) = project_path
7488 && restored_project_paths.contains(project_path_to_open)
7489 {
7490 *project_path = None;
7491 }
7492 });
7493 } else {
7494 for _ in 0..project_paths_to_open.len() {
7495 opened_items.push(None);
7496 }
7497 }
7498 assert!(opened_items.len() == project_paths_to_open.len());
7499
7500 let tasks =
7501 project_paths_to_open
7502 .into_iter()
7503 .enumerate()
7504 .map(|(ix, (abs_path, project_path))| {
7505 let workspace = workspace.clone();
7506 cx.spawn(async move |cx| {
7507 let file_project_path = project_path?;
7508 let abs_path_task = workspace.update(cx, |workspace, cx| {
7509 workspace.project().update(cx, |project, cx| {
7510 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7511 })
7512 });
7513
7514 // We only want to open file paths here. If one of the items
7515 // here is a directory, it was already opened further above
7516 // with a `find_or_create_worktree`.
7517 if let Ok(task) = abs_path_task
7518 && task.await.is_none_or(|p| p.is_file())
7519 {
7520 return Some((
7521 ix,
7522 workspace
7523 .update_in(cx, |workspace, window, cx| {
7524 workspace.open_path(
7525 file_project_path,
7526 None,
7527 true,
7528 window,
7529 cx,
7530 )
7531 })
7532 .log_err()?
7533 .await,
7534 ));
7535 }
7536 None
7537 })
7538 });
7539
7540 let tasks = tasks.collect::<Vec<_>>();
7541
7542 let tasks = futures::future::join_all(tasks);
7543 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7544 opened_items[ix] = Some(path_open_result);
7545 }
7546
7547 Ok(opened_items)
7548 })
7549}
7550
7551enum ActivateInDirectionTarget {
7552 Pane(Entity<Pane>),
7553 Dock(Entity<Dock>),
7554}
7555
7556fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7557 window
7558 .update(cx, |multi_workspace, _, cx| {
7559 let workspace = multi_workspace.workspace().clone();
7560 workspace.update(cx, |workspace, cx| {
7561 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7562 struct DatabaseFailedNotification;
7563
7564 workspace.show_notification(
7565 NotificationId::unique::<DatabaseFailedNotification>(),
7566 cx,
7567 |cx| {
7568 cx.new(|cx| {
7569 MessageNotification::new("Failed to load the database file.", cx)
7570 .primary_message("File an Issue")
7571 .primary_icon(IconName::Plus)
7572 .primary_on_click(|window, cx| {
7573 window.dispatch_action(Box::new(FileBugReport), cx)
7574 })
7575 })
7576 },
7577 );
7578 }
7579 });
7580 })
7581 .log_err();
7582}
7583
7584fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7585 if val == 0 {
7586 ThemeSettings::get_global(cx).ui_font_size(cx)
7587 } else {
7588 px(val as f32)
7589 }
7590}
7591
7592fn adjust_active_dock_size_by_px(
7593 px: Pixels,
7594 workspace: &mut Workspace,
7595 window: &mut Window,
7596 cx: &mut Context<Workspace>,
7597) {
7598 let Some(active_dock) = workspace
7599 .all_docks()
7600 .into_iter()
7601 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7602 else {
7603 return;
7604 };
7605 let dock = active_dock.read(cx);
7606 let Some(panel_size) = dock.active_panel_size(window, cx) else {
7607 return;
7608 };
7609 let dock_pos = dock.position();
7610 workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
7611}
7612
7613fn adjust_open_docks_size_by_px(
7614 px: Pixels,
7615 workspace: &mut Workspace,
7616 window: &mut Window,
7617 cx: &mut Context<Workspace>,
7618) {
7619 let docks = workspace
7620 .all_docks()
7621 .into_iter()
7622 .filter_map(|dock| {
7623 if dock.read(cx).is_open() {
7624 let dock = dock.read(cx);
7625 let panel_size = dock.active_panel_size(window, cx)?;
7626 let dock_pos = dock.position();
7627 Some((panel_size, dock_pos, px))
7628 } else {
7629 None
7630 }
7631 })
7632 .collect::<Vec<_>>();
7633
7634 docks
7635 .into_iter()
7636 .for_each(|(panel_size, dock_pos, offset)| {
7637 workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
7638 });
7639}
7640
7641impl Focusable for Workspace {
7642 fn focus_handle(&self, cx: &App) -> FocusHandle {
7643 self.active_pane.focus_handle(cx)
7644 }
7645}
7646
7647#[derive(Clone)]
7648struct DraggedDock {
7649 position: DockPosition,
7650 part: DockPart,
7651}
7652
7653impl Render for DraggedDock {
7654 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7655 gpui::Empty
7656 }
7657}
7658
7659impl Render for Workspace {
7660 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7661 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7662 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7663 log::info!("Rendered first frame");
7664 }
7665
7666 let centered_layout = self.centered_layout
7667 && self.center.panes().len() == 1
7668 && self.active_item(cx).is_some();
7669 let render_padding = |size| {
7670 (size > 0.0).then(|| {
7671 div()
7672 .h_full()
7673 .w(relative(size))
7674 .bg(cx.theme().colors().editor_background)
7675 .border_color(cx.theme().colors().pane_group_border)
7676 })
7677 };
7678 let paddings = if centered_layout {
7679 let settings = WorkspaceSettings::get_global(cx).centered_layout;
7680 (
7681 render_padding(Self::adjust_padding(
7682 settings.left_padding.map(|padding| padding.0),
7683 )),
7684 render_padding(Self::adjust_padding(
7685 settings.right_padding.map(|padding| padding.0),
7686 )),
7687 )
7688 } else {
7689 (None, None)
7690 };
7691 let ui_font = theme::setup_ui_font(window, cx);
7692
7693 let theme = cx.theme().clone();
7694 let colors = theme.colors();
7695 let notification_entities = self
7696 .notifications
7697 .iter()
7698 .map(|(_, notification)| notification.entity_id())
7699 .collect::<Vec<_>>();
7700 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
7701
7702 let mut center_area = Some(self.render_center(paddings, window, cx));
7703
7704 div()
7705 .relative()
7706 .size_full()
7707 .flex()
7708 .flex_col()
7709 .font(ui_font)
7710 .gap_0()
7711 .justify_start()
7712 .items_start()
7713 .text_color(colors.text)
7714 .overflow_hidden()
7715 .children(self.titlebar_item.clone())
7716 .on_modifiers_changed(move |_, _, cx| {
7717 for &id in ¬ification_entities {
7718 cx.notify(id);
7719 }
7720 })
7721 .child(
7722 div()
7723 .size_full()
7724 .relative()
7725 .flex_1()
7726 .flex()
7727 .flex_col()
7728 .child(
7729 div()
7730 .id("workspace")
7731 .bg(colors.background)
7732 .relative()
7733 .flex_1()
7734 .w_full()
7735 .flex()
7736 .flex_col()
7737 .overflow_hidden()
7738 .border_t_1()
7739 .border_b_1()
7740 .border_color(colors.border)
7741 .child({
7742 let this = cx.entity();
7743 canvas(
7744 move |bounds, window, cx| {
7745 this.update(cx, |this, cx| {
7746 let bounds_changed = this.bounds != bounds;
7747 this.bounds = bounds;
7748
7749 if bounds_changed {
7750 this.left_dock.update(cx, |dock, cx| {
7751 dock.clamp_panel_size(
7752 bounds.size.width,
7753 window,
7754 cx,
7755 )
7756 });
7757
7758 this.right_dock.update(cx, |dock, cx| {
7759 dock.clamp_panel_size(
7760 bounds.size.width,
7761 window,
7762 cx,
7763 )
7764 });
7765
7766 this.bottom_dock.update(cx, |dock, cx| {
7767 dock.clamp_panel_size(
7768 bounds.size.height,
7769 window,
7770 cx,
7771 )
7772 });
7773 }
7774 })
7775 },
7776 |_, _, _, _| {},
7777 )
7778 .absolute()
7779 .size_full()
7780 })
7781 .when(self.zoomed.is_none(), |this| {
7782 this.on_drag_move(cx.listener(
7783 move |workspace, e: &DragMoveEvent<DraggedDock>, window, cx| {
7784 let drag = e.drag(cx);
7785 match drag.part {
7786 DockPart::Fixed => {
7787 if workspace.previous_dock_drag_coordinates
7788 != Some(e.event.position)
7789 {
7790 workspace.previous_dock_drag_coordinates =
7791 Some(e.event.position);
7792
7793 match e.drag(cx).position {
7794 DockPosition::Left => {
7795 workspace.resize_left_dock(
7796 e.event.position.x
7797 - workspace.bounds.left(),
7798 window,
7799 cx,
7800 );
7801 }
7802 DockPosition::Right => {
7803 workspace.resize_right_dock(
7804 workspace.bounds.right()
7805 - e.event.position.x,
7806 window,
7807 cx,
7808 );
7809 }
7810 DockPosition::Bottom => {
7811 workspace.resize_bottom_dock(
7812 workspace.bounds.bottom()
7813 - e.event.position.y,
7814 window,
7815 cx,
7816 );
7817 }
7818 };
7819 workspace.serialize_workspace(window, cx);
7820 }
7821 }
7822 DockPart::Flexible => {
7823 match drag.position {
7824 DockPosition::Left => {
7825 let fixed_width = workspace
7826 .left_dock
7827 .read(cx)
7828 .active_panel()
7829 .map_or(px(0.0), |p| {
7830 p.size(window, cx)
7831 });
7832 let start_x =
7833 workspace.bounds.left() + fixed_width;
7834 let new_width =
7835 e.event.position.x - start_x;
7836
7837 dbg!(&e.event.position);
7838 dbg!(&workspace.bounds);
7839 dbg!(&fixed_width);
7840 dbg!(&start_x);
7841 dbg!(new_width);
7842 //
7843 }
7844 DockPosition::Right => {
7845 //
7846 }
7847 DockPosition::Bottom => unreachable!(
7848 "bottom dock cannot have flex content"
7849 ),
7850 }
7851 }
7852 }
7853 },
7854 ))
7855 })
7856 .child({
7857 match bottom_dock_layout {
7858 BottomDockLayout::Full => div()
7859 .flex()
7860 .flex_col()
7861 .h_full()
7862 .child(
7863 div()
7864 .flex()
7865 .flex_row()
7866 .flex_1()
7867 .overflow_hidden()
7868 .children(self.render_dock(
7869 DockPosition::Left,
7870 &self.left_dock,
7871 window,
7872 cx,
7873 ))
7874 .child(
7875 div()
7876 .flex()
7877 .flex_col()
7878 .flex_1()
7879 .overflow_hidden()
7880 .children(center_area.take()),
7881 )
7882 .children(self.render_dock(
7883 DockPosition::Right,
7884 &self.right_dock,
7885 window,
7886 cx,
7887 )),
7888 )
7889 .child(div().w_full().children(self.render_dock(
7890 DockPosition::Bottom,
7891 &self.bottom_dock,
7892 window,
7893 cx,
7894 ))),
7895
7896 BottomDockLayout::LeftAligned => div()
7897 .flex()
7898 .flex_row()
7899 .h_full()
7900 .child(
7901 div()
7902 .flex()
7903 .flex_col()
7904 .flex_1()
7905 .h_full()
7906 .child(
7907 div()
7908 .flex()
7909 .flex_row()
7910 .flex_1()
7911 .children(self.render_dock(
7912 DockPosition::Left,
7913 &self.left_dock,
7914 window,
7915 cx,
7916 ))
7917 .child(
7918 div()
7919 .flex()
7920 .flex_col()
7921 .flex_1()
7922 .overflow_hidden()
7923 .children(center_area.take()),
7924 ),
7925 )
7926 .child(div().w_full().children(self.render_dock(
7927 DockPosition::Bottom,
7928 &self.bottom_dock,
7929 window,
7930 cx,
7931 ))),
7932 )
7933 .children(self.render_dock(
7934 DockPosition::Right,
7935 &self.right_dock,
7936 window,
7937 cx,
7938 )),
7939
7940 BottomDockLayout::RightAligned => div()
7941 .flex()
7942 .flex_row()
7943 .h_full()
7944 .children(self.render_dock(
7945 DockPosition::Left,
7946 &self.left_dock,
7947 window,
7948 cx,
7949 ))
7950 .child(
7951 div()
7952 .flex()
7953 .flex_col()
7954 .flex_1()
7955 .h_full()
7956 .child(
7957 div()
7958 .flex()
7959 .flex_row()
7960 .flex_1()
7961 .child(
7962 div()
7963 .flex()
7964 .flex_col()
7965 .flex_1()
7966 .overflow_hidden()
7967 .children(center_area.take()),
7968 )
7969 .children(self.render_dock(
7970 DockPosition::Right,
7971 &self.right_dock,
7972 window,
7973 cx,
7974 )),
7975 )
7976 .child(div().w_full().children(self.render_dock(
7977 DockPosition::Bottom,
7978 &self.bottom_dock,
7979 window,
7980 cx,
7981 ))),
7982 ),
7983
7984 BottomDockLayout::Contained => div()
7985 .flex()
7986 .flex_row()
7987 .h_full()
7988 .children(self.render_dock(
7989 DockPosition::Left,
7990 &self.left_dock,
7991 window,
7992 cx,
7993 ))
7994 .child(
7995 div()
7996 .flex()
7997 .flex_col()
7998 .flex_1()
7999 .overflow_hidden()
8000 .children(center_area.take())
8001 .children(self.render_dock(
8002 DockPosition::Bottom,
8003 &self.bottom_dock,
8004 window,
8005 cx,
8006 )),
8007 )
8008 .children(self.render_dock(
8009 DockPosition::Right,
8010 &self.right_dock,
8011 window,
8012 cx,
8013 )),
8014 }
8015 })
8016 .children(self.zoomed.as_ref().and_then(|view| {
8017 let zoomed_view = view.upgrade()?;
8018 let div = div()
8019 .occlude()
8020 .absolute()
8021 .overflow_hidden()
8022 .border_color(colors.border)
8023 .bg(colors.background)
8024 .child(zoomed_view)
8025 .inset_0()
8026 .shadow_lg();
8027
8028 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8029 return Some(div);
8030 }
8031
8032 Some(match self.zoomed_position {
8033 Some(DockPosition::Left) => div.right_2().border_r_1(),
8034 Some(DockPosition::Right) => div.left_2().border_l_1(),
8035 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8036 None => div.top_2().bottom_2().left_2().right_2().border_1(),
8037 })
8038 }))
8039 .children(self.render_notifications(window, cx)),
8040 )
8041 .when(self.status_bar_visible(cx), |parent| {
8042 parent.child(self.status_bar.clone())
8043 })
8044 .child(self.toast_layer.clone()),
8045 )
8046 }
8047}
8048
8049impl WorkspaceStore {
8050 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8051 Self {
8052 workspaces: Default::default(),
8053 _subscriptions: vec![
8054 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8055 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8056 ],
8057 client,
8058 }
8059 }
8060
8061 pub fn update_followers(
8062 &self,
8063 project_id: Option<u64>,
8064 update: proto::update_followers::Variant,
8065 cx: &App,
8066 ) -> Option<()> {
8067 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8068 let room_id = active_call.0.room_id(cx)?;
8069 self.client
8070 .send(proto::UpdateFollowers {
8071 room_id,
8072 project_id,
8073 variant: Some(update),
8074 })
8075 .log_err()
8076 }
8077
8078 pub async fn handle_follow(
8079 this: Entity<Self>,
8080 envelope: TypedEnvelope<proto::Follow>,
8081 mut cx: AsyncApp,
8082 ) -> Result<proto::FollowResponse> {
8083 this.update(&mut cx, |this, cx| {
8084 let follower = Follower {
8085 project_id: envelope.payload.project_id,
8086 peer_id: envelope.original_sender_id()?,
8087 };
8088
8089 let mut response = proto::FollowResponse::default();
8090
8091 this.workspaces.retain(|(window_handle, weak_workspace)| {
8092 let Some(workspace) = weak_workspace.upgrade() else {
8093 return false;
8094 };
8095 window_handle
8096 .update(cx, |_, window, cx| {
8097 workspace.update(cx, |workspace, cx| {
8098 let handler_response =
8099 workspace.handle_follow(follower.project_id, window, cx);
8100 if let Some(active_view) = handler_response.active_view
8101 && workspace.project.read(cx).remote_id() == follower.project_id
8102 {
8103 response.active_view = Some(active_view)
8104 }
8105 });
8106 })
8107 .is_ok()
8108 });
8109
8110 Ok(response)
8111 })
8112 }
8113
8114 async fn handle_update_followers(
8115 this: Entity<Self>,
8116 envelope: TypedEnvelope<proto::UpdateFollowers>,
8117 mut cx: AsyncApp,
8118 ) -> Result<()> {
8119 let leader_id = envelope.original_sender_id()?;
8120 let update = envelope.payload;
8121
8122 this.update(&mut cx, |this, cx| {
8123 this.workspaces.retain(|(window_handle, weak_workspace)| {
8124 let Some(workspace) = weak_workspace.upgrade() else {
8125 return false;
8126 };
8127 window_handle
8128 .update(cx, |_, window, cx| {
8129 workspace.update(cx, |workspace, cx| {
8130 let project_id = workspace.project.read(cx).remote_id();
8131 if update.project_id != project_id && update.project_id.is_some() {
8132 return;
8133 }
8134 workspace.handle_update_followers(
8135 leader_id,
8136 update.clone(),
8137 window,
8138 cx,
8139 );
8140 });
8141 })
8142 .is_ok()
8143 });
8144 Ok(())
8145 })
8146 }
8147
8148 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8149 self.workspaces.iter().map(|(_, weak)| weak)
8150 }
8151
8152 pub fn workspaces_with_windows(
8153 &self,
8154 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8155 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8156 }
8157}
8158
8159impl ViewId {
8160 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8161 Ok(Self {
8162 creator: message
8163 .creator
8164 .map(CollaboratorId::PeerId)
8165 .context("creator is missing")?,
8166 id: message.id,
8167 })
8168 }
8169
8170 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8171 if let CollaboratorId::PeerId(peer_id) = self.creator {
8172 Some(proto::ViewId {
8173 creator: Some(peer_id),
8174 id: self.id,
8175 })
8176 } else {
8177 None
8178 }
8179 }
8180}
8181
8182impl FollowerState {
8183 fn pane(&self) -> &Entity<Pane> {
8184 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8185 }
8186}
8187
8188pub trait WorkspaceHandle {
8189 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8190}
8191
8192impl WorkspaceHandle for Entity<Workspace> {
8193 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8194 self.read(cx)
8195 .worktrees(cx)
8196 .flat_map(|worktree| {
8197 let worktree_id = worktree.read(cx).id();
8198 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8199 worktree_id,
8200 path: f.path.clone(),
8201 })
8202 })
8203 .collect::<Vec<_>>()
8204 }
8205}
8206
8207pub async fn last_opened_workspace_location(
8208 fs: &dyn fs::Fs,
8209) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8210 DB.last_workspace(fs)
8211 .await
8212 .log_err()
8213 .flatten()
8214 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8215}
8216
8217pub async fn last_session_workspace_locations(
8218 last_session_id: &str,
8219 last_session_window_stack: Option<Vec<WindowId>>,
8220 fs: &dyn fs::Fs,
8221) -> Option<Vec<SessionWorkspace>> {
8222 DB.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8223 .await
8224 .log_err()
8225}
8226
8227pub struct MultiWorkspaceRestoreResult {
8228 pub window_handle: WindowHandle<MultiWorkspace>,
8229 pub errors: Vec<anyhow::Error>,
8230}
8231
8232pub async fn restore_multiworkspace(
8233 multi_workspace: SerializedMultiWorkspace,
8234 app_state: Arc<AppState>,
8235 cx: &mut AsyncApp,
8236) -> anyhow::Result<MultiWorkspaceRestoreResult> {
8237 let SerializedMultiWorkspace {
8238 workspaces,
8239 state,
8240 id: window_id,
8241 } = multi_workspace;
8242 let mut group_iter = workspaces.into_iter();
8243 let first = group_iter
8244 .next()
8245 .context("window group must not be empty")?;
8246
8247 let window_handle = if first.paths.is_empty() {
8248 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
8249 .await?
8250 } else {
8251 let (window, _items) = cx
8252 .update(|cx| {
8253 Workspace::new_local(
8254 first.paths.paths().to_vec(),
8255 app_state.clone(),
8256 None,
8257 None,
8258 None,
8259 true,
8260 cx,
8261 )
8262 })
8263 .await?;
8264 window
8265 };
8266
8267 let mut errors = Vec::new();
8268
8269 for session_workspace in group_iter {
8270 let error = if session_workspace.paths.is_empty() {
8271 cx.update(|cx| {
8272 open_workspace_by_id(
8273 session_workspace.workspace_id,
8274 app_state.clone(),
8275 Some(window_handle),
8276 cx,
8277 )
8278 })
8279 .await
8280 .err()
8281 } else {
8282 cx.update(|cx| {
8283 Workspace::new_local(
8284 session_workspace.paths.paths().to_vec(),
8285 app_state.clone(),
8286 Some(window_handle),
8287 None,
8288 None,
8289 true,
8290 cx,
8291 )
8292 })
8293 .await
8294 .err()
8295 };
8296
8297 if let Some(error) = error {
8298 errors.push(error);
8299 }
8300 }
8301
8302 if let Some(target_id) = state.active_workspace_id {
8303 window_handle
8304 .update(cx, |multi_workspace, window, cx| {
8305 multi_workspace.set_database_id(window_id);
8306 let target_index = multi_workspace
8307 .workspaces()
8308 .iter()
8309 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8310 if let Some(index) = target_index {
8311 multi_workspace.activate_index(index, window, cx);
8312 } else if !multi_workspace.workspaces().is_empty() {
8313 multi_workspace.activate_index(0, window, cx);
8314 }
8315 })
8316 .ok();
8317 } else {
8318 window_handle
8319 .update(cx, |multi_workspace, window, cx| {
8320 if !multi_workspace.workspaces().is_empty() {
8321 multi_workspace.activate_index(0, window, cx);
8322 }
8323 })
8324 .ok();
8325 }
8326
8327 window_handle
8328 .update(cx, |_, window, _cx| {
8329 window.activate_window();
8330 })
8331 .ok();
8332
8333 Ok(MultiWorkspaceRestoreResult {
8334 window_handle,
8335 errors,
8336 })
8337}
8338
8339actions!(
8340 collab,
8341 [
8342 /// Opens the channel notes for the current call.
8343 ///
8344 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8345 /// channel in the collab panel.
8346 ///
8347 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8348 /// can be copied via "Copy link to section" in the context menu of the channel notes
8349 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8350 OpenChannelNotes,
8351 /// Mutes your microphone.
8352 Mute,
8353 /// Deafens yourself (mute both microphone and speakers).
8354 Deafen,
8355 /// Leaves the current call.
8356 LeaveCall,
8357 /// Shares the current project with collaborators.
8358 ShareProject,
8359 /// Shares your screen with collaborators.
8360 ScreenShare,
8361 /// Copies the current room name and session id for debugging purposes.
8362 CopyRoomId,
8363 ]
8364);
8365actions!(
8366 zed,
8367 [
8368 /// Opens the Zed log file.
8369 OpenLog,
8370 /// Reveals the Zed log file in the system file manager.
8371 RevealLogInFileManager
8372 ]
8373);
8374
8375async fn join_channel_internal(
8376 channel_id: ChannelId,
8377 app_state: &Arc<AppState>,
8378 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8379 requesting_workspace: Option<WeakEntity<Workspace>>,
8380 active_call: &dyn AnyActiveCall,
8381 cx: &mut AsyncApp,
8382) -> Result<bool> {
8383 let (should_prompt, already_in_channel) = cx.update(|cx| {
8384 if !active_call.is_in_room(cx) {
8385 return (false, false);
8386 }
8387
8388 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8389 let should_prompt = active_call.is_sharing_project(cx)
8390 && active_call.has_remote_participants(cx)
8391 && !already_in_channel;
8392 (should_prompt, already_in_channel)
8393 });
8394
8395 if already_in_channel {
8396 let task = cx.update(|cx| {
8397 if let Some((project, host)) = active_call.most_active_project(cx) {
8398 Some(join_in_room_project(project, host, app_state.clone(), cx))
8399 } else {
8400 None
8401 }
8402 });
8403 if let Some(task) = task {
8404 task.await?;
8405 }
8406 return anyhow::Ok(true);
8407 }
8408
8409 if should_prompt {
8410 if let Some(multi_workspace) = requesting_window {
8411 let answer = multi_workspace
8412 .update(cx, |_, window, cx| {
8413 window.prompt(
8414 PromptLevel::Warning,
8415 "Do you want to switch channels?",
8416 Some("Leaving this call will unshare your current project."),
8417 &["Yes, Join Channel", "Cancel"],
8418 cx,
8419 )
8420 })?
8421 .await;
8422
8423 if answer == Ok(1) {
8424 return Ok(false);
8425 }
8426 } else {
8427 return Ok(false);
8428 }
8429 }
8430
8431 let client = cx.update(|cx| active_call.client(cx));
8432
8433 let mut client_status = client.status();
8434
8435 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8436 'outer: loop {
8437 let Some(status) = client_status.recv().await else {
8438 anyhow::bail!("error connecting");
8439 };
8440
8441 match status {
8442 Status::Connecting
8443 | Status::Authenticating
8444 | Status::Authenticated
8445 | Status::Reconnecting
8446 | Status::Reauthenticating
8447 | Status::Reauthenticated => continue,
8448 Status::Connected { .. } => break 'outer,
8449 Status::SignedOut | Status::AuthenticationError => {
8450 return Err(ErrorCode::SignedOut.into());
8451 }
8452 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8453 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8454 return Err(ErrorCode::Disconnected.into());
8455 }
8456 }
8457 }
8458
8459 let joined = cx
8460 .update(|cx| active_call.join_channel(channel_id, cx))
8461 .await?;
8462
8463 if !joined {
8464 return anyhow::Ok(true);
8465 }
8466
8467 cx.update(|cx| active_call.room_update_completed(cx)).await;
8468
8469 let task = cx.update(|cx| {
8470 if let Some((project, host)) = active_call.most_active_project(cx) {
8471 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8472 }
8473
8474 // If you are the first to join a channel, see if you should share your project.
8475 if !active_call.has_remote_participants(cx)
8476 && !active_call.local_participant_is_guest(cx)
8477 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8478 {
8479 let project = workspace.update(cx, |workspace, cx| {
8480 let project = workspace.project.read(cx);
8481
8482 if !active_call.share_on_join(cx) {
8483 return None;
8484 }
8485
8486 if (project.is_local() || project.is_via_remote_server())
8487 && project.visible_worktrees(cx).any(|tree| {
8488 tree.read(cx)
8489 .root_entry()
8490 .is_some_and(|entry| entry.is_dir())
8491 })
8492 {
8493 Some(workspace.project.clone())
8494 } else {
8495 None
8496 }
8497 });
8498 if let Some(project) = project {
8499 let share_task = active_call.share_project(project, cx);
8500 return Some(cx.spawn(async move |_cx| -> Result<()> {
8501 share_task.await?;
8502 Ok(())
8503 }));
8504 }
8505 }
8506
8507 None
8508 });
8509 if let Some(task) = task {
8510 task.await?;
8511 return anyhow::Ok(true);
8512 }
8513 anyhow::Ok(false)
8514}
8515
8516pub fn join_channel(
8517 channel_id: ChannelId,
8518 app_state: Arc<AppState>,
8519 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8520 requesting_workspace: Option<WeakEntity<Workspace>>,
8521 cx: &mut App,
8522) -> Task<Result<()>> {
8523 let active_call = GlobalAnyActiveCall::global(cx).clone();
8524 cx.spawn(async move |cx| {
8525 let result = join_channel_internal(
8526 channel_id,
8527 &app_state,
8528 requesting_window,
8529 requesting_workspace,
8530 &*active_call.0,
8531 cx,
8532 )
8533 .await;
8534
8535 // join channel succeeded, and opened a window
8536 if matches!(result, Ok(true)) {
8537 return anyhow::Ok(());
8538 }
8539
8540 // find an existing workspace to focus and show call controls
8541 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8542 if active_window.is_none() {
8543 // no open workspaces, make one to show the error in (blergh)
8544 let (window_handle, _) = cx
8545 .update(|cx| {
8546 Workspace::new_local(
8547 vec![],
8548 app_state.clone(),
8549 requesting_window,
8550 None,
8551 None,
8552 true,
8553 cx,
8554 )
8555 })
8556 .await?;
8557
8558 window_handle
8559 .update(cx, |_, window, _cx| {
8560 window.activate_window();
8561 })
8562 .ok();
8563
8564 if result.is_ok() {
8565 cx.update(|cx| {
8566 cx.dispatch_action(&OpenChannelNotes);
8567 });
8568 }
8569
8570 active_window = Some(window_handle);
8571 }
8572
8573 if let Err(err) = result {
8574 log::error!("failed to join channel: {}", err);
8575 if let Some(active_window) = active_window {
8576 active_window
8577 .update(cx, |_, window, cx| {
8578 let detail: SharedString = match err.error_code() {
8579 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8580 ErrorCode::UpgradeRequired => concat!(
8581 "Your are running an unsupported version of Zed. ",
8582 "Please update to continue."
8583 )
8584 .into(),
8585 ErrorCode::NoSuchChannel => concat!(
8586 "No matching channel was found. ",
8587 "Please check the link and try again."
8588 )
8589 .into(),
8590 ErrorCode::Forbidden => concat!(
8591 "This channel is private, and you do not have access. ",
8592 "Please ask someone to add you and try again."
8593 )
8594 .into(),
8595 ErrorCode::Disconnected => {
8596 "Please check your internet connection and try again.".into()
8597 }
8598 _ => format!("{}\n\nPlease try again.", err).into(),
8599 };
8600 window.prompt(
8601 PromptLevel::Critical,
8602 "Failed to join channel",
8603 Some(&detail),
8604 &["Ok"],
8605 cx,
8606 )
8607 })?
8608 .await
8609 .ok();
8610 }
8611 }
8612
8613 // return ok, we showed the error to the user.
8614 anyhow::Ok(())
8615 })
8616}
8617
8618pub async fn get_any_active_multi_workspace(
8619 app_state: Arc<AppState>,
8620 mut cx: AsyncApp,
8621) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8622 // find an existing workspace to focus and show call controls
8623 let active_window = activate_any_workspace_window(&mut cx);
8624 if active_window.is_none() {
8625 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
8626 .await?;
8627 }
8628 activate_any_workspace_window(&mut cx).context("could not open zed")
8629}
8630
8631fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
8632 cx.update(|cx| {
8633 if let Some(workspace_window) = cx
8634 .active_window()
8635 .and_then(|window| window.downcast::<MultiWorkspace>())
8636 {
8637 return Some(workspace_window);
8638 }
8639
8640 for window in cx.windows() {
8641 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
8642 workspace_window
8643 .update(cx, |_, window, _| window.activate_window())
8644 .ok();
8645 return Some(workspace_window);
8646 }
8647 }
8648 None
8649 })
8650}
8651
8652pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
8653 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
8654}
8655
8656pub fn workspace_windows_for_location(
8657 serialized_location: &SerializedWorkspaceLocation,
8658 cx: &App,
8659) -> Vec<WindowHandle<MultiWorkspace>> {
8660 cx.windows()
8661 .into_iter()
8662 .filter_map(|window| window.downcast::<MultiWorkspace>())
8663 .filter(|multi_workspace| {
8664 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
8665 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
8666 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
8667 }
8668 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
8669 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
8670 a.distro_name == b.distro_name
8671 }
8672 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
8673 a.container_id == b.container_id
8674 }
8675 #[cfg(any(test, feature = "test-support"))]
8676 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
8677 a.id == b.id
8678 }
8679 _ => false,
8680 };
8681
8682 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
8683 multi_workspace.workspaces().iter().any(|workspace| {
8684 match workspace.read(cx).workspace_location(cx) {
8685 WorkspaceLocation::Location(location, _) => {
8686 match (&location, serialized_location) {
8687 (
8688 SerializedWorkspaceLocation::Local,
8689 SerializedWorkspaceLocation::Local,
8690 ) => true,
8691 (
8692 SerializedWorkspaceLocation::Remote(a),
8693 SerializedWorkspaceLocation::Remote(b),
8694 ) => same_host(a, b),
8695 _ => false,
8696 }
8697 }
8698 _ => false,
8699 }
8700 })
8701 })
8702 })
8703 .collect()
8704}
8705
8706pub async fn find_existing_workspace(
8707 abs_paths: &[PathBuf],
8708 open_options: &OpenOptions,
8709 location: &SerializedWorkspaceLocation,
8710 cx: &mut AsyncApp,
8711) -> (
8712 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
8713 OpenVisible,
8714) {
8715 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
8716 let mut open_visible = OpenVisible::All;
8717 let mut best_match = None;
8718
8719 if open_options.open_new_workspace != Some(true) {
8720 cx.update(|cx| {
8721 for window in workspace_windows_for_location(location, cx) {
8722 if let Ok(multi_workspace) = window.read(cx) {
8723 for workspace in multi_workspace.workspaces() {
8724 let project = workspace.read(cx).project.read(cx);
8725 let m = project.visibility_for_paths(
8726 abs_paths,
8727 open_options.open_new_workspace == None,
8728 cx,
8729 );
8730 if m > best_match {
8731 existing = Some((window, workspace.clone()));
8732 best_match = m;
8733 } else if best_match.is_none()
8734 && open_options.open_new_workspace == Some(false)
8735 {
8736 existing = Some((window, workspace.clone()))
8737 }
8738 }
8739 }
8740 }
8741 });
8742
8743 let all_paths_are_files = existing
8744 .as_ref()
8745 .and_then(|(_, target_workspace)| {
8746 cx.update(|cx| {
8747 let workspace = target_workspace.read(cx);
8748 let project = workspace.project.read(cx);
8749 let path_style = workspace.path_style(cx);
8750 Some(!abs_paths.iter().any(|path| {
8751 let path = util::paths::SanitizedPath::new(path);
8752 project.worktrees(cx).any(|worktree| {
8753 let worktree = worktree.read(cx);
8754 let abs_path = worktree.abs_path();
8755 path_style
8756 .strip_prefix(path.as_ref(), abs_path.as_ref())
8757 .and_then(|rel| worktree.entry_for_path(&rel))
8758 .is_some_and(|e| e.is_dir())
8759 })
8760 }))
8761 })
8762 })
8763 .unwrap_or(false);
8764
8765 if open_options.open_new_workspace.is_none()
8766 && existing.is_some()
8767 && open_options.wait
8768 && all_paths_are_files
8769 {
8770 cx.update(|cx| {
8771 let windows = workspace_windows_for_location(location, cx);
8772 let window = cx
8773 .active_window()
8774 .and_then(|window| window.downcast::<MultiWorkspace>())
8775 .filter(|window| windows.contains(window))
8776 .or_else(|| windows.into_iter().next());
8777 if let Some(window) = window {
8778 if let Ok(multi_workspace) = window.read(cx) {
8779 let active_workspace = multi_workspace.workspace().clone();
8780 existing = Some((window, active_workspace));
8781 open_visible = OpenVisible::None;
8782 }
8783 }
8784 });
8785 }
8786 }
8787 (existing, open_visible)
8788}
8789
8790#[derive(Default, Clone)]
8791pub struct OpenOptions {
8792 pub visible: Option<OpenVisible>,
8793 pub focus: Option<bool>,
8794 pub open_new_workspace: Option<bool>,
8795 pub wait: bool,
8796 pub replace_window: Option<WindowHandle<MultiWorkspace>>,
8797 pub env: Option<HashMap<String, String>>,
8798}
8799
8800/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
8801pub fn open_workspace_by_id(
8802 workspace_id: WorkspaceId,
8803 app_state: Arc<AppState>,
8804 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8805 cx: &mut App,
8806) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
8807 let project_handle = Project::local(
8808 app_state.client.clone(),
8809 app_state.node_runtime.clone(),
8810 app_state.user_store.clone(),
8811 app_state.languages.clone(),
8812 app_state.fs.clone(),
8813 None,
8814 project::LocalProjectFlags {
8815 init_worktree_trust: true,
8816 ..project::LocalProjectFlags::default()
8817 },
8818 cx,
8819 );
8820
8821 cx.spawn(async move |cx| {
8822 let serialized_workspace = persistence::DB
8823 .workspace_for_id(workspace_id)
8824 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
8825
8826 let centered_layout = serialized_workspace.centered_layout;
8827
8828 let (window, workspace) = if let Some(window) = requesting_window {
8829 let workspace = window.update(cx, |multi_workspace, window, cx| {
8830 let workspace = cx.new(|cx| {
8831 let mut workspace = Workspace::new(
8832 Some(workspace_id),
8833 project_handle.clone(),
8834 app_state.clone(),
8835 window,
8836 cx,
8837 );
8838 workspace.centered_layout = centered_layout;
8839 workspace
8840 });
8841 multi_workspace.add_workspace(workspace.clone(), cx);
8842 workspace
8843 })?;
8844 (window, workspace)
8845 } else {
8846 let window_bounds_override = window_bounds_env_override();
8847
8848 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
8849 (Some(WindowBounds::Windowed(bounds)), None)
8850 } else if let Some(display) = serialized_workspace.display
8851 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
8852 {
8853 (Some(bounds.0), Some(display))
8854 } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
8855 (Some(bounds), Some(display))
8856 } else {
8857 (None, None)
8858 };
8859
8860 let options = cx.update(|cx| {
8861 let mut options = (app_state.build_window_options)(display, cx);
8862 options.window_bounds = window_bounds;
8863 options
8864 });
8865
8866 let window = cx.open_window(options, {
8867 let app_state = app_state.clone();
8868 let project_handle = project_handle.clone();
8869 move |window, cx| {
8870 let workspace = cx.new(|cx| {
8871 let mut workspace = Workspace::new(
8872 Some(workspace_id),
8873 project_handle,
8874 app_state,
8875 window,
8876 cx,
8877 );
8878 workspace.centered_layout = centered_layout;
8879 workspace
8880 });
8881 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
8882 }
8883 })?;
8884
8885 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
8886 multi_workspace.workspace().clone()
8887 })?;
8888
8889 (window, workspace)
8890 };
8891
8892 notify_if_database_failed(window, cx);
8893
8894 // Restore items from the serialized workspace
8895 window
8896 .update(cx, |_, window, cx| {
8897 workspace.update(cx, |_workspace, cx| {
8898 open_items(Some(serialized_workspace), vec![], window, cx)
8899 })
8900 })?
8901 .await?;
8902
8903 window.update(cx, |_, window, cx| {
8904 workspace.update(cx, |workspace, cx| {
8905 workspace.serialize_workspace(window, cx);
8906 });
8907 })?;
8908
8909 Ok(window)
8910 })
8911}
8912
8913#[allow(clippy::type_complexity)]
8914pub fn open_paths(
8915 abs_paths: &[PathBuf],
8916 app_state: Arc<AppState>,
8917 open_options: OpenOptions,
8918 cx: &mut App,
8919) -> Task<
8920 anyhow::Result<(
8921 WindowHandle<MultiWorkspace>,
8922 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
8923 )>,
8924> {
8925 let abs_paths = abs_paths.to_vec();
8926 #[cfg(target_os = "windows")]
8927 let wsl_path = abs_paths
8928 .iter()
8929 .find_map(|p| util::paths::WslPath::from_path(p));
8930
8931 cx.spawn(async move |cx| {
8932 let (mut existing, mut open_visible) = find_existing_workspace(
8933 &abs_paths,
8934 &open_options,
8935 &SerializedWorkspaceLocation::Local,
8936 cx,
8937 )
8938 .await;
8939
8940 // Fallback: if no workspace contains the paths and all paths are files,
8941 // prefer an existing local workspace window (active window first).
8942 if open_options.open_new_workspace.is_none() && existing.is_none() {
8943 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
8944 let all_metadatas = futures::future::join_all(all_paths)
8945 .await
8946 .into_iter()
8947 .filter_map(|result| result.ok().flatten())
8948 .collect::<Vec<_>>();
8949
8950 if all_metadatas.iter().all(|file| !file.is_dir) {
8951 cx.update(|cx| {
8952 let windows = workspace_windows_for_location(
8953 &SerializedWorkspaceLocation::Local,
8954 cx,
8955 );
8956 let window = cx
8957 .active_window()
8958 .and_then(|window| window.downcast::<MultiWorkspace>())
8959 .filter(|window| windows.contains(window))
8960 .or_else(|| windows.into_iter().next());
8961 if let Some(window) = window {
8962 if let Ok(multi_workspace) = window.read(cx) {
8963 let active_workspace = multi_workspace.workspace().clone();
8964 existing = Some((window, active_workspace));
8965 open_visible = OpenVisible::None;
8966 }
8967 }
8968 });
8969 }
8970 }
8971
8972 let result = if let Some((existing, target_workspace)) = existing {
8973 let open_task = existing
8974 .update(cx, |multi_workspace, window, cx| {
8975 window.activate_window();
8976 multi_workspace.activate(target_workspace.clone(), cx);
8977 target_workspace.update(cx, |workspace, cx| {
8978 workspace.open_paths(
8979 abs_paths,
8980 OpenOptions {
8981 visible: Some(open_visible),
8982 ..Default::default()
8983 },
8984 None,
8985 window,
8986 cx,
8987 )
8988 })
8989 })?
8990 .await;
8991
8992 _ = existing.update(cx, |multi_workspace, _, cx| {
8993 let workspace = multi_workspace.workspace().clone();
8994 workspace.update(cx, |workspace, cx| {
8995 for item in open_task.iter().flatten() {
8996 if let Err(e) = item {
8997 workspace.show_error(&e, cx);
8998 }
8999 }
9000 });
9001 });
9002
9003 Ok((existing, open_task))
9004 } else {
9005 let result = cx
9006 .update(move |cx| {
9007 Workspace::new_local(
9008 abs_paths,
9009 app_state.clone(),
9010 open_options.replace_window,
9011 open_options.env,
9012 None,
9013 true,
9014 cx,
9015 )
9016 })
9017 .await;
9018
9019 if let Ok((ref window_handle, _)) = result {
9020 window_handle
9021 .update(cx, |_, window, _cx| {
9022 window.activate_window();
9023 })
9024 .log_err();
9025 }
9026
9027 result
9028 };
9029
9030 #[cfg(target_os = "windows")]
9031 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9032 && let Ok((multi_workspace_window, _)) = &result
9033 {
9034 multi_workspace_window
9035 .update(cx, move |multi_workspace, _window, cx| {
9036 struct OpenInWsl;
9037 let workspace = multi_workspace.workspace().clone();
9038 workspace.update(cx, |workspace, cx| {
9039 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9040 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9041 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9042 cx.new(move |cx| {
9043 MessageNotification::new(msg, cx)
9044 .primary_message("Open in WSL")
9045 .primary_icon(IconName::FolderOpen)
9046 .primary_on_click(move |window, cx| {
9047 window.dispatch_action(Box::new(remote::OpenWslPath {
9048 distro: remote::WslConnectionOptions {
9049 distro_name: distro.clone(),
9050 user: None,
9051 },
9052 paths: vec![path.clone().into()],
9053 }), cx)
9054 })
9055 })
9056 });
9057 });
9058 })
9059 .unwrap();
9060 };
9061 result
9062 })
9063}
9064
9065pub fn open_new(
9066 open_options: OpenOptions,
9067 app_state: Arc<AppState>,
9068 cx: &mut App,
9069 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9070) -> Task<anyhow::Result<()>> {
9071 let task = Workspace::new_local(
9072 Vec::new(),
9073 app_state,
9074 open_options.replace_window,
9075 open_options.env,
9076 Some(Box::new(init)),
9077 true,
9078 cx,
9079 );
9080 cx.spawn(async move |cx| {
9081 let (window, _opened_paths) = task.await?;
9082 window
9083 .update(cx, |_, window, _cx| {
9084 window.activate_window();
9085 })
9086 .ok();
9087 Ok(())
9088 })
9089}
9090
9091pub fn create_and_open_local_file(
9092 path: &'static Path,
9093 window: &mut Window,
9094 cx: &mut Context<Workspace>,
9095 default_content: impl 'static + Send + FnOnce() -> Rope,
9096) -> Task<Result<Box<dyn ItemHandle>>> {
9097 cx.spawn_in(window, async move |workspace, cx| {
9098 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9099 if !fs.is_file(path).await {
9100 fs.create_file(path, Default::default()).await?;
9101 fs.save(path, &default_content(), Default::default())
9102 .await?;
9103 }
9104
9105 workspace
9106 .update_in(cx, |workspace, window, cx| {
9107 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9108 let path = workspace
9109 .project
9110 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9111 cx.spawn_in(window, async move |workspace, cx| {
9112 let path = path.await?;
9113 let mut items = workspace
9114 .update_in(cx, |workspace, window, cx| {
9115 workspace.open_paths(
9116 vec![path.to_path_buf()],
9117 OpenOptions {
9118 visible: Some(OpenVisible::None),
9119 ..Default::default()
9120 },
9121 None,
9122 window,
9123 cx,
9124 )
9125 })?
9126 .await;
9127 let item = items.pop().flatten();
9128 item.with_context(|| format!("path {path:?} is not a file"))?
9129 })
9130 })
9131 })?
9132 .await?
9133 .await
9134 })
9135}
9136
9137pub fn open_remote_project_with_new_connection(
9138 window: WindowHandle<MultiWorkspace>,
9139 remote_connection: Arc<dyn RemoteConnection>,
9140 cancel_rx: oneshot::Receiver<()>,
9141 delegate: Arc<dyn RemoteClientDelegate>,
9142 app_state: Arc<AppState>,
9143 paths: Vec<PathBuf>,
9144 cx: &mut App,
9145) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9146 cx.spawn(async move |cx| {
9147 let (workspace_id, serialized_workspace) =
9148 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9149 .await?;
9150
9151 let session = match cx
9152 .update(|cx| {
9153 remote::RemoteClient::new(
9154 ConnectionIdentifier::Workspace(workspace_id.0),
9155 remote_connection,
9156 cancel_rx,
9157 delegate,
9158 cx,
9159 )
9160 })
9161 .await?
9162 {
9163 Some(result) => result,
9164 None => return Ok(Vec::new()),
9165 };
9166
9167 let project = cx.update(|cx| {
9168 project::Project::remote(
9169 session,
9170 app_state.client.clone(),
9171 app_state.node_runtime.clone(),
9172 app_state.user_store.clone(),
9173 app_state.languages.clone(),
9174 app_state.fs.clone(),
9175 true,
9176 cx,
9177 )
9178 });
9179
9180 open_remote_project_inner(
9181 project,
9182 paths,
9183 workspace_id,
9184 serialized_workspace,
9185 app_state,
9186 window,
9187 cx,
9188 )
9189 .await
9190 })
9191}
9192
9193pub fn open_remote_project_with_existing_connection(
9194 connection_options: RemoteConnectionOptions,
9195 project: Entity<Project>,
9196 paths: Vec<PathBuf>,
9197 app_state: Arc<AppState>,
9198 window: WindowHandle<MultiWorkspace>,
9199 cx: &mut AsyncApp,
9200) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9201 cx.spawn(async move |cx| {
9202 let (workspace_id, serialized_workspace) =
9203 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9204
9205 open_remote_project_inner(
9206 project,
9207 paths,
9208 workspace_id,
9209 serialized_workspace,
9210 app_state,
9211 window,
9212 cx,
9213 )
9214 .await
9215 })
9216}
9217
9218async fn open_remote_project_inner(
9219 project: Entity<Project>,
9220 paths: Vec<PathBuf>,
9221 workspace_id: WorkspaceId,
9222 serialized_workspace: Option<SerializedWorkspace>,
9223 app_state: Arc<AppState>,
9224 window: WindowHandle<MultiWorkspace>,
9225 cx: &mut AsyncApp,
9226) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9227 let toolchains = DB.toolchains(workspace_id).await?;
9228 for (toolchain, worktree_path, path) in toolchains {
9229 project
9230 .update(cx, |this, cx| {
9231 let Some(worktree_id) =
9232 this.find_worktree(&worktree_path, cx)
9233 .and_then(|(worktree, rel_path)| {
9234 if rel_path.is_empty() {
9235 Some(worktree.read(cx).id())
9236 } else {
9237 None
9238 }
9239 })
9240 else {
9241 return Task::ready(None);
9242 };
9243
9244 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9245 })
9246 .await;
9247 }
9248 let mut project_paths_to_open = vec![];
9249 let mut project_path_errors = vec![];
9250
9251 for path in paths {
9252 let result = cx
9253 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9254 .await;
9255 match result {
9256 Ok((_, project_path)) => {
9257 project_paths_to_open.push((path.clone(), Some(project_path)));
9258 }
9259 Err(error) => {
9260 project_path_errors.push(error);
9261 }
9262 };
9263 }
9264
9265 if project_paths_to_open.is_empty() {
9266 return Err(project_path_errors.pop().context("no paths given")?);
9267 }
9268
9269 let workspace = window.update(cx, |multi_workspace, window, cx| {
9270 telemetry::event!("SSH Project Opened");
9271
9272 let new_workspace = cx.new(|cx| {
9273 let mut workspace =
9274 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9275 workspace.update_history(cx);
9276
9277 if let Some(ref serialized) = serialized_workspace {
9278 workspace.centered_layout = serialized.centered_layout;
9279 }
9280
9281 workspace
9282 });
9283
9284 multi_workspace.activate(new_workspace.clone(), cx);
9285 new_workspace
9286 })?;
9287
9288 let items = window
9289 .update(cx, |_, window, cx| {
9290 window.activate_window();
9291 workspace.update(cx, |_workspace, cx| {
9292 open_items(serialized_workspace, project_paths_to_open, window, cx)
9293 })
9294 })?
9295 .await?;
9296
9297 workspace.update(cx, |workspace, cx| {
9298 for error in project_path_errors {
9299 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9300 if let Some(path) = error.error_tag("path") {
9301 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9302 }
9303 } else {
9304 workspace.show_error(&error, cx)
9305 }
9306 }
9307 });
9308
9309 Ok(items.into_iter().map(|item| item?.ok()).collect())
9310}
9311
9312fn deserialize_remote_project(
9313 connection_options: RemoteConnectionOptions,
9314 paths: Vec<PathBuf>,
9315 cx: &AsyncApp,
9316) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9317 cx.background_spawn(async move {
9318 let remote_connection_id = persistence::DB
9319 .get_or_create_remote_connection(connection_options)
9320 .await?;
9321
9322 let serialized_workspace =
9323 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
9324
9325 let workspace_id = if let Some(workspace_id) =
9326 serialized_workspace.as_ref().map(|workspace| workspace.id)
9327 {
9328 workspace_id
9329 } else {
9330 persistence::DB.next_id().await?
9331 };
9332
9333 Ok((workspace_id, serialized_workspace))
9334 })
9335}
9336
9337pub fn join_in_room_project(
9338 project_id: u64,
9339 follow_user_id: u64,
9340 app_state: Arc<AppState>,
9341 cx: &mut App,
9342) -> Task<Result<()>> {
9343 let windows = cx.windows();
9344 cx.spawn(async move |cx| {
9345 let existing_window_and_workspace: Option<(
9346 WindowHandle<MultiWorkspace>,
9347 Entity<Workspace>,
9348 )> = windows.into_iter().find_map(|window_handle| {
9349 window_handle
9350 .downcast::<MultiWorkspace>()
9351 .and_then(|window_handle| {
9352 window_handle
9353 .update(cx, |multi_workspace, _window, cx| {
9354 for workspace in multi_workspace.workspaces() {
9355 if workspace.read(cx).project().read(cx).remote_id()
9356 == Some(project_id)
9357 {
9358 return Some((window_handle, workspace.clone()));
9359 }
9360 }
9361 None
9362 })
9363 .unwrap_or(None)
9364 })
9365 });
9366
9367 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9368 existing_window_and_workspace
9369 {
9370 existing_window
9371 .update(cx, |multi_workspace, _, cx| {
9372 multi_workspace.activate(target_workspace, cx);
9373 })
9374 .ok();
9375 existing_window
9376 } else {
9377 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9378 let project = cx
9379 .update(|cx| {
9380 active_call.0.join_project(
9381 project_id,
9382 app_state.languages.clone(),
9383 app_state.fs.clone(),
9384 cx,
9385 )
9386 })
9387 .await?;
9388
9389 let window_bounds_override = window_bounds_env_override();
9390 cx.update(|cx| {
9391 let mut options = (app_state.build_window_options)(None, cx);
9392 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9393 cx.open_window(options, |window, cx| {
9394 let workspace = cx.new(|cx| {
9395 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9396 });
9397 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9398 })
9399 })?
9400 };
9401
9402 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9403 cx.activate(true);
9404 window.activate_window();
9405
9406 // We set the active workspace above, so this is the correct workspace.
9407 let workspace = multi_workspace.workspace().clone();
9408 workspace.update(cx, |workspace, cx| {
9409 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9410 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9411 .or_else(|| {
9412 // If we couldn't follow the given user, follow the host instead.
9413 let collaborator = workspace
9414 .project()
9415 .read(cx)
9416 .collaborators()
9417 .values()
9418 .find(|collaborator| collaborator.is_host)?;
9419 Some(collaborator.peer_id)
9420 });
9421
9422 if let Some(follow_peer_id) = follow_peer_id {
9423 workspace.follow(follow_peer_id, window, cx);
9424 }
9425 });
9426 })?;
9427
9428 anyhow::Ok(())
9429 })
9430}
9431
9432pub fn reload(cx: &mut App) {
9433 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9434 let mut workspace_windows = cx
9435 .windows()
9436 .into_iter()
9437 .filter_map(|window| window.downcast::<MultiWorkspace>())
9438 .collect::<Vec<_>>();
9439
9440 // If multiple windows have unsaved changes, and need a save prompt,
9441 // prompt in the active window before switching to a different window.
9442 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9443
9444 let mut prompt = None;
9445 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9446 prompt = window
9447 .update(cx, |_, window, cx| {
9448 window.prompt(
9449 PromptLevel::Info,
9450 "Are you sure you want to restart?",
9451 None,
9452 &["Restart", "Cancel"],
9453 cx,
9454 )
9455 })
9456 .ok();
9457 }
9458
9459 cx.spawn(async move |cx| {
9460 if let Some(prompt) = prompt {
9461 let answer = prompt.await?;
9462 if answer != 0 {
9463 return anyhow::Ok(());
9464 }
9465 }
9466
9467 // If the user cancels any save prompt, then keep the app open.
9468 for window in workspace_windows {
9469 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9470 let workspace = multi_workspace.workspace().clone();
9471 workspace.update(cx, |workspace, cx| {
9472 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9473 })
9474 }) && !should_close.await?
9475 {
9476 return anyhow::Ok(());
9477 }
9478 }
9479 cx.update(|cx| cx.restart());
9480 anyhow::Ok(())
9481 })
9482 .detach_and_log_err(cx);
9483}
9484
9485fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9486 let mut parts = value.split(',');
9487 let x: usize = parts.next()?.parse().ok()?;
9488 let y: usize = parts.next()?.parse().ok()?;
9489 Some(point(px(x as f32), px(y as f32)))
9490}
9491
9492fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9493 let mut parts = value.split(',');
9494 let width: usize = parts.next()?.parse().ok()?;
9495 let height: usize = parts.next()?.parse().ok()?;
9496 Some(size(px(width as f32), px(height as f32)))
9497}
9498
9499/// Add client-side decorations (rounded corners, shadows, resize handling) when
9500/// appropriate.
9501///
9502/// The `border_radius_tiling` parameter allows overriding which corners get
9503/// rounded, independently of the actual window tiling state. This is used
9504/// specifically for the workspace switcher sidebar: when the sidebar is open,
9505/// we want square corners on the left (so the sidebar appears flush with the
9506/// window edge) but we still need the shadow padding for proper visual
9507/// appearance. Unlike actual window tiling, this only affects border radius -
9508/// not padding or shadows.
9509pub fn client_side_decorations(
9510 element: impl IntoElement,
9511 window: &mut Window,
9512 cx: &mut App,
9513 border_radius_tiling: Tiling,
9514) -> Stateful<Div> {
9515 const BORDER_SIZE: Pixels = px(1.0);
9516 let decorations = window.window_decorations();
9517 let tiling = match decorations {
9518 Decorations::Server => Tiling::default(),
9519 Decorations::Client { tiling } => tiling,
9520 };
9521
9522 match decorations {
9523 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9524 Decorations::Server => window.set_client_inset(px(0.0)),
9525 }
9526
9527 struct GlobalResizeEdge(ResizeEdge);
9528 impl Global for GlobalResizeEdge {}
9529
9530 div()
9531 .id("window-backdrop")
9532 .bg(transparent_black())
9533 .map(|div| match decorations {
9534 Decorations::Server => div,
9535 Decorations::Client { .. } => div
9536 .when(
9537 !(tiling.top
9538 || tiling.right
9539 || border_radius_tiling.top
9540 || border_radius_tiling.right),
9541 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9542 )
9543 .when(
9544 !(tiling.top
9545 || tiling.left
9546 || border_radius_tiling.top
9547 || border_radius_tiling.left),
9548 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9549 )
9550 .when(
9551 !(tiling.bottom
9552 || tiling.right
9553 || border_radius_tiling.bottom
9554 || border_radius_tiling.right),
9555 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9556 )
9557 .when(
9558 !(tiling.bottom
9559 || tiling.left
9560 || border_radius_tiling.bottom
9561 || border_radius_tiling.left),
9562 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9563 )
9564 .when(!tiling.top, |div| {
9565 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9566 })
9567 .when(!tiling.bottom, |div| {
9568 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9569 })
9570 .when(!tiling.left, |div| {
9571 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9572 })
9573 .when(!tiling.right, |div| {
9574 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9575 })
9576 .on_mouse_move(move |e, window, cx| {
9577 let size = window.window_bounds().get_bounds().size;
9578 let pos = e.position;
9579
9580 let new_edge =
9581 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9582
9583 let edge = cx.try_global::<GlobalResizeEdge>();
9584 if new_edge != edge.map(|edge| edge.0) {
9585 window
9586 .window_handle()
9587 .update(cx, |workspace, _, cx| {
9588 cx.notify(workspace.entity_id());
9589 })
9590 .ok();
9591 }
9592 })
9593 .on_mouse_down(MouseButton::Left, move |e, window, _| {
9594 let size = window.window_bounds().get_bounds().size;
9595 let pos = e.position;
9596
9597 let edge = match resize_edge(
9598 pos,
9599 theme::CLIENT_SIDE_DECORATION_SHADOW,
9600 size,
9601 tiling,
9602 ) {
9603 Some(value) => value,
9604 None => return,
9605 };
9606
9607 window.start_window_resize(edge);
9608 }),
9609 })
9610 .size_full()
9611 .child(
9612 div()
9613 .cursor(CursorStyle::Arrow)
9614 .map(|div| match decorations {
9615 Decorations::Server => div,
9616 Decorations::Client { .. } => div
9617 .border_color(cx.theme().colors().border)
9618 .when(
9619 !(tiling.top
9620 || tiling.right
9621 || border_radius_tiling.top
9622 || border_radius_tiling.right),
9623 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9624 )
9625 .when(
9626 !(tiling.top
9627 || tiling.left
9628 || border_radius_tiling.top
9629 || border_radius_tiling.left),
9630 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9631 )
9632 .when(
9633 !(tiling.bottom
9634 || tiling.right
9635 || border_radius_tiling.bottom
9636 || border_radius_tiling.right),
9637 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9638 )
9639 .when(
9640 !(tiling.bottom
9641 || tiling.left
9642 || border_radius_tiling.bottom
9643 || border_radius_tiling.left),
9644 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9645 )
9646 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
9647 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
9648 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
9649 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
9650 .when(!tiling.is_tiled(), |div| {
9651 div.shadow(vec![gpui::BoxShadow {
9652 color: Hsla {
9653 h: 0.,
9654 s: 0.,
9655 l: 0.,
9656 a: 0.4,
9657 },
9658 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
9659 spread_radius: px(0.),
9660 offset: point(px(0.0), px(0.0)),
9661 }])
9662 }),
9663 })
9664 .on_mouse_move(|_e, _, cx| {
9665 cx.stop_propagation();
9666 })
9667 .size_full()
9668 .child(element),
9669 )
9670 .map(|div| match decorations {
9671 Decorations::Server => div,
9672 Decorations::Client { tiling, .. } => div.child(
9673 canvas(
9674 |_bounds, window, _| {
9675 window.insert_hitbox(
9676 Bounds::new(
9677 point(px(0.0), px(0.0)),
9678 window.window_bounds().get_bounds().size,
9679 ),
9680 HitboxBehavior::Normal,
9681 )
9682 },
9683 move |_bounds, hitbox, window, cx| {
9684 let mouse = window.mouse_position();
9685 let size = window.window_bounds().get_bounds().size;
9686 let Some(edge) =
9687 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
9688 else {
9689 return;
9690 };
9691 cx.set_global(GlobalResizeEdge(edge));
9692 window.set_cursor_style(
9693 match edge {
9694 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
9695 ResizeEdge::Left | ResizeEdge::Right => {
9696 CursorStyle::ResizeLeftRight
9697 }
9698 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
9699 CursorStyle::ResizeUpLeftDownRight
9700 }
9701 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
9702 CursorStyle::ResizeUpRightDownLeft
9703 }
9704 },
9705 &hitbox,
9706 );
9707 },
9708 )
9709 .size_full()
9710 .absolute(),
9711 ),
9712 })
9713}
9714
9715fn resize_edge(
9716 pos: Point<Pixels>,
9717 shadow_size: Pixels,
9718 window_size: Size<Pixels>,
9719 tiling: Tiling,
9720) -> Option<ResizeEdge> {
9721 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
9722 if bounds.contains(&pos) {
9723 return None;
9724 }
9725
9726 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
9727 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
9728 if !tiling.top && top_left_bounds.contains(&pos) {
9729 return Some(ResizeEdge::TopLeft);
9730 }
9731
9732 let top_right_bounds = Bounds::new(
9733 Point::new(window_size.width - corner_size.width, px(0.)),
9734 corner_size,
9735 );
9736 if !tiling.top && top_right_bounds.contains(&pos) {
9737 return Some(ResizeEdge::TopRight);
9738 }
9739
9740 let bottom_left_bounds = Bounds::new(
9741 Point::new(px(0.), window_size.height - corner_size.height),
9742 corner_size,
9743 );
9744 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
9745 return Some(ResizeEdge::BottomLeft);
9746 }
9747
9748 let bottom_right_bounds = Bounds::new(
9749 Point::new(
9750 window_size.width - corner_size.width,
9751 window_size.height - corner_size.height,
9752 ),
9753 corner_size,
9754 );
9755 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
9756 return Some(ResizeEdge::BottomRight);
9757 }
9758
9759 if !tiling.top && pos.y < shadow_size {
9760 Some(ResizeEdge::Top)
9761 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
9762 Some(ResizeEdge::Bottom)
9763 } else if !tiling.left && pos.x < shadow_size {
9764 Some(ResizeEdge::Left)
9765 } else if !tiling.right && pos.x > window_size.width - shadow_size {
9766 Some(ResizeEdge::Right)
9767 } else {
9768 None
9769 }
9770}
9771
9772fn join_pane_into_active(
9773 active_pane: &Entity<Pane>,
9774 pane: &Entity<Pane>,
9775 window: &mut Window,
9776 cx: &mut App,
9777) {
9778 if pane == active_pane {
9779 } else if pane.read(cx).items_len() == 0 {
9780 pane.update(cx, |_, cx| {
9781 cx.emit(pane::Event::Remove {
9782 focus_on_pane: None,
9783 });
9784 })
9785 } else {
9786 move_all_items(pane, active_pane, window, cx);
9787 }
9788}
9789
9790fn move_all_items(
9791 from_pane: &Entity<Pane>,
9792 to_pane: &Entity<Pane>,
9793 window: &mut Window,
9794 cx: &mut App,
9795) {
9796 let destination_is_different = from_pane != to_pane;
9797 let mut moved_items = 0;
9798 for (item_ix, item_handle) in from_pane
9799 .read(cx)
9800 .items()
9801 .enumerate()
9802 .map(|(ix, item)| (ix, item.clone()))
9803 .collect::<Vec<_>>()
9804 {
9805 let ix = item_ix - moved_items;
9806 if destination_is_different {
9807 // Close item from previous pane
9808 from_pane.update(cx, |source, cx| {
9809 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
9810 });
9811 moved_items += 1;
9812 }
9813
9814 // This automatically removes duplicate items in the pane
9815 to_pane.update(cx, |destination, cx| {
9816 destination.add_item(item_handle, true, true, None, window, cx);
9817 window.focus(&destination.focus_handle(cx), cx)
9818 });
9819 }
9820}
9821
9822pub fn move_item(
9823 source: &Entity<Pane>,
9824 destination: &Entity<Pane>,
9825 item_id_to_move: EntityId,
9826 destination_index: usize,
9827 activate: bool,
9828 window: &mut Window,
9829 cx: &mut App,
9830) {
9831 let Some((item_ix, item_handle)) = source
9832 .read(cx)
9833 .items()
9834 .enumerate()
9835 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
9836 .map(|(ix, item)| (ix, item.clone()))
9837 else {
9838 // Tab was closed during drag
9839 return;
9840 };
9841
9842 if source != destination {
9843 // Close item from previous pane
9844 source.update(cx, |source, cx| {
9845 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
9846 });
9847 }
9848
9849 // This automatically removes duplicate items in the pane
9850 destination.update(cx, |destination, cx| {
9851 destination.add_item_inner(
9852 item_handle,
9853 activate,
9854 activate,
9855 activate,
9856 Some(destination_index),
9857 window,
9858 cx,
9859 );
9860 if activate {
9861 window.focus(&destination.focus_handle(cx), cx)
9862 }
9863 });
9864}
9865
9866pub fn move_active_item(
9867 source: &Entity<Pane>,
9868 destination: &Entity<Pane>,
9869 focus_destination: bool,
9870 close_if_empty: bool,
9871 window: &mut Window,
9872 cx: &mut App,
9873) {
9874 if source == destination {
9875 return;
9876 }
9877 let Some(active_item) = source.read(cx).active_item() else {
9878 return;
9879 };
9880 source.update(cx, |source_pane, cx| {
9881 let item_id = active_item.item_id();
9882 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
9883 destination.update(cx, |target_pane, cx| {
9884 target_pane.add_item(
9885 active_item,
9886 focus_destination,
9887 focus_destination,
9888 Some(target_pane.items_len()),
9889 window,
9890 cx,
9891 );
9892 });
9893 });
9894}
9895
9896pub fn clone_active_item(
9897 workspace_id: Option<WorkspaceId>,
9898 source: &Entity<Pane>,
9899 destination: &Entity<Pane>,
9900 focus_destination: bool,
9901 window: &mut Window,
9902 cx: &mut App,
9903) {
9904 if source == destination {
9905 return;
9906 }
9907 let Some(active_item) = source.read(cx).active_item() else {
9908 return;
9909 };
9910 if !active_item.can_split(cx) {
9911 return;
9912 }
9913 let destination = destination.downgrade();
9914 let task = active_item.clone_on_split(workspace_id, window, cx);
9915 window
9916 .spawn(cx, async move |cx| {
9917 let Some(clone) = task.await else {
9918 return;
9919 };
9920 destination
9921 .update_in(cx, |target_pane, window, cx| {
9922 target_pane.add_item(
9923 clone,
9924 focus_destination,
9925 focus_destination,
9926 Some(target_pane.items_len()),
9927 window,
9928 cx,
9929 );
9930 })
9931 .log_err();
9932 })
9933 .detach();
9934}
9935
9936#[derive(Debug)]
9937pub struct WorkspacePosition {
9938 pub window_bounds: Option<WindowBounds>,
9939 pub display: Option<Uuid>,
9940 pub centered_layout: bool,
9941}
9942
9943pub fn remote_workspace_position_from_db(
9944 connection_options: RemoteConnectionOptions,
9945 paths_to_open: &[PathBuf],
9946 cx: &App,
9947) -> Task<Result<WorkspacePosition>> {
9948 let paths = paths_to_open.to_vec();
9949
9950 cx.background_spawn(async move {
9951 let remote_connection_id = persistence::DB
9952 .get_or_create_remote_connection(connection_options)
9953 .await
9954 .context("fetching serialized ssh project")?;
9955 let serialized_workspace =
9956 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
9957
9958 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
9959 (Some(WindowBounds::Windowed(bounds)), None)
9960 } else {
9961 let restorable_bounds = serialized_workspace
9962 .as_ref()
9963 .and_then(|workspace| {
9964 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
9965 })
9966 .or_else(|| persistence::read_default_window_bounds());
9967
9968 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
9969 (Some(serialized_bounds), Some(serialized_display))
9970 } else {
9971 (None, None)
9972 }
9973 };
9974
9975 let centered_layout = serialized_workspace
9976 .as_ref()
9977 .map(|w| w.centered_layout)
9978 .unwrap_or(false);
9979
9980 Ok(WorkspacePosition {
9981 window_bounds,
9982 display,
9983 centered_layout,
9984 })
9985 })
9986}
9987
9988pub fn with_active_or_new_workspace(
9989 cx: &mut App,
9990 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
9991) {
9992 match cx
9993 .active_window()
9994 .and_then(|w| w.downcast::<MultiWorkspace>())
9995 {
9996 Some(multi_workspace) => {
9997 cx.defer(move |cx| {
9998 multi_workspace
9999 .update(cx, |multi_workspace, window, cx| {
10000 let workspace = multi_workspace.workspace().clone();
10001 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10002 })
10003 .log_err();
10004 });
10005 }
10006 None => {
10007 let app_state = AppState::global(cx);
10008 if let Some(app_state) = app_state.upgrade() {
10009 open_new(
10010 OpenOptions::default(),
10011 app_state,
10012 cx,
10013 move |workspace, window, cx| f(workspace, window, cx),
10014 )
10015 .detach_and_log_err(cx);
10016 }
10017 }
10018 }
10019}
10020
10021#[cfg(test)]
10022mod tests {
10023 use std::{cell::RefCell, rc::Rc};
10024
10025 use super::*;
10026 use crate::{
10027 dock::{PanelEvent, test::TestPanel},
10028 item::{
10029 ItemBufferKind, ItemEvent,
10030 test::{TestItem, TestProjectItem},
10031 },
10032 };
10033 use fs::FakeFs;
10034 use gpui::{
10035 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10036 UpdateGlobal, VisualTestContext, px,
10037 };
10038 use project::{Project, ProjectEntryId};
10039 use serde_json::json;
10040 use settings::SettingsStore;
10041 use util::rel_path::rel_path;
10042
10043 #[gpui::test]
10044 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10045 init_test(cx);
10046
10047 let fs = FakeFs::new(cx.executor());
10048 let project = Project::test(fs, [], cx).await;
10049 let (workspace, cx) =
10050 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10051
10052 // Adding an item with no ambiguity renders the tab without detail.
10053 let item1 = cx.new(|cx| {
10054 let mut item = TestItem::new(cx);
10055 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10056 item
10057 });
10058 workspace.update_in(cx, |workspace, window, cx| {
10059 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10060 });
10061 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10062
10063 // Adding an item that creates ambiguity increases the level of detail on
10064 // both tabs.
10065 let item2 = cx.new_window_entity(|_window, cx| {
10066 let mut item = TestItem::new(cx);
10067 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10068 item
10069 });
10070 workspace.update_in(cx, |workspace, window, cx| {
10071 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10072 });
10073 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10074 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10075
10076 // Adding an item that creates ambiguity increases the level of detail only
10077 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10078 // we stop at the highest detail available.
10079 let item3 = cx.new(|cx| {
10080 let mut item = TestItem::new(cx);
10081 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10082 item
10083 });
10084 workspace.update_in(cx, |workspace, window, cx| {
10085 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10086 });
10087 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10088 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10089 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10090 }
10091
10092 #[gpui::test]
10093 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10094 init_test(cx);
10095
10096 let fs = FakeFs::new(cx.executor());
10097 fs.insert_tree(
10098 "/root1",
10099 json!({
10100 "one.txt": "",
10101 "two.txt": "",
10102 }),
10103 )
10104 .await;
10105 fs.insert_tree(
10106 "/root2",
10107 json!({
10108 "three.txt": "",
10109 }),
10110 )
10111 .await;
10112
10113 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10114 let (workspace, cx) =
10115 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10116 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10117 let worktree_id = project.update(cx, |project, cx| {
10118 project.worktrees(cx).next().unwrap().read(cx).id()
10119 });
10120
10121 let item1 = cx.new(|cx| {
10122 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10123 });
10124 let item2 = cx.new(|cx| {
10125 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10126 });
10127
10128 // Add an item to an empty pane
10129 workspace.update_in(cx, |workspace, window, cx| {
10130 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10131 });
10132 project.update(cx, |project, cx| {
10133 assert_eq!(
10134 project.active_entry(),
10135 project
10136 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10137 .map(|e| e.id)
10138 );
10139 });
10140 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10141
10142 // Add a second item to a non-empty pane
10143 workspace.update_in(cx, |workspace, window, cx| {
10144 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10145 });
10146 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10147 project.update(cx, |project, cx| {
10148 assert_eq!(
10149 project.active_entry(),
10150 project
10151 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10152 .map(|e| e.id)
10153 );
10154 });
10155
10156 // Close the active item
10157 pane.update_in(cx, |pane, window, cx| {
10158 pane.close_active_item(&Default::default(), window, cx)
10159 })
10160 .await
10161 .unwrap();
10162 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10163 project.update(cx, |project, cx| {
10164 assert_eq!(
10165 project.active_entry(),
10166 project
10167 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10168 .map(|e| e.id)
10169 );
10170 });
10171
10172 // Add a project folder
10173 project
10174 .update(cx, |project, cx| {
10175 project.find_or_create_worktree("root2", true, cx)
10176 })
10177 .await
10178 .unwrap();
10179 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10180
10181 // Remove a project folder
10182 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10183 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10184 }
10185
10186 #[gpui::test]
10187 async fn test_close_window(cx: &mut TestAppContext) {
10188 init_test(cx);
10189
10190 let fs = FakeFs::new(cx.executor());
10191 fs.insert_tree("/root", json!({ "one": "" })).await;
10192
10193 let project = Project::test(fs, ["root".as_ref()], cx).await;
10194 let (workspace, cx) =
10195 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10196
10197 // When there are no dirty items, there's nothing to do.
10198 let item1 = cx.new(TestItem::new);
10199 workspace.update_in(cx, |w, window, cx| {
10200 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10201 });
10202 let task = workspace.update_in(cx, |w, window, cx| {
10203 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10204 });
10205 assert!(task.await.unwrap());
10206
10207 // When there are dirty untitled items, prompt to save each one. If the user
10208 // cancels any prompt, then abort.
10209 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10210 let item3 = cx.new(|cx| {
10211 TestItem::new(cx)
10212 .with_dirty(true)
10213 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10214 });
10215 workspace.update_in(cx, |w, window, cx| {
10216 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10217 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10218 });
10219 let task = workspace.update_in(cx, |w, window, cx| {
10220 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10221 });
10222 cx.executor().run_until_parked();
10223 cx.simulate_prompt_answer("Cancel"); // cancel save all
10224 cx.executor().run_until_parked();
10225 assert!(!cx.has_pending_prompt());
10226 assert!(!task.await.unwrap());
10227 }
10228
10229 #[gpui::test]
10230 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10231 init_test(cx);
10232
10233 let fs = FakeFs::new(cx.executor());
10234 fs.insert_tree("/root", json!({ "one": "" })).await;
10235
10236 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10237 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10238 let multi_workspace_handle =
10239 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10240 cx.run_until_parked();
10241
10242 let workspace_a = multi_workspace_handle
10243 .read_with(cx, |mw, _| mw.workspace().clone())
10244 .unwrap();
10245
10246 let workspace_b = multi_workspace_handle
10247 .update(cx, |mw, window, cx| {
10248 mw.test_add_workspace(project_b, window, cx)
10249 })
10250 .unwrap();
10251
10252 // Activate workspace A
10253 multi_workspace_handle
10254 .update(cx, |mw, window, cx| {
10255 mw.activate_index(0, window, cx);
10256 })
10257 .unwrap();
10258
10259 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10260
10261 // Workspace A has a clean item
10262 let item_a = cx.new(TestItem::new);
10263 workspace_a.update_in(cx, |w, window, cx| {
10264 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10265 });
10266
10267 // Workspace B has a dirty item
10268 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10269 workspace_b.update_in(cx, |w, window, cx| {
10270 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10271 });
10272
10273 // Verify workspace A is active
10274 multi_workspace_handle
10275 .read_with(cx, |mw, _| {
10276 assert_eq!(mw.active_workspace_index(), 0);
10277 })
10278 .unwrap();
10279
10280 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10281 multi_workspace_handle
10282 .update(cx, |mw, window, cx| {
10283 mw.close_window(&CloseWindow, window, cx);
10284 })
10285 .unwrap();
10286 cx.run_until_parked();
10287
10288 // Workspace B should now be active since it has dirty items that need attention
10289 multi_workspace_handle
10290 .read_with(cx, |mw, _| {
10291 assert_eq!(
10292 mw.active_workspace_index(),
10293 1,
10294 "workspace B should be activated when it prompts"
10295 );
10296 })
10297 .unwrap();
10298
10299 // User cancels the save prompt from workspace B
10300 cx.simulate_prompt_answer("Cancel");
10301 cx.run_until_parked();
10302
10303 // Window should still exist because workspace B's close was cancelled
10304 assert!(
10305 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10306 "window should still exist after cancelling one workspace's close"
10307 );
10308 }
10309
10310 #[gpui::test]
10311 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10312 init_test(cx);
10313
10314 // Register TestItem as a serializable item
10315 cx.update(|cx| {
10316 register_serializable_item::<TestItem>(cx);
10317 });
10318
10319 let fs = FakeFs::new(cx.executor());
10320 fs.insert_tree("/root", json!({ "one": "" })).await;
10321
10322 let project = Project::test(fs, ["root".as_ref()], cx).await;
10323 let (workspace, cx) =
10324 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10325
10326 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10327 let item1 = cx.new(|cx| {
10328 TestItem::new(cx)
10329 .with_dirty(true)
10330 .with_serialize(|| Some(Task::ready(Ok(()))))
10331 });
10332 let item2 = cx.new(|cx| {
10333 TestItem::new(cx)
10334 .with_dirty(true)
10335 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10336 .with_serialize(|| Some(Task::ready(Ok(()))))
10337 });
10338 workspace.update_in(cx, |w, window, cx| {
10339 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10340 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10341 });
10342 let task = workspace.update_in(cx, |w, window, cx| {
10343 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10344 });
10345 assert!(task.await.unwrap());
10346 }
10347
10348 #[gpui::test]
10349 async fn test_close_pane_items(cx: &mut TestAppContext) {
10350 init_test(cx);
10351
10352 let fs = FakeFs::new(cx.executor());
10353
10354 let project = Project::test(fs, None, cx).await;
10355 let (workspace, cx) =
10356 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10357
10358 let item1 = cx.new(|cx| {
10359 TestItem::new(cx)
10360 .with_dirty(true)
10361 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10362 });
10363 let item2 = cx.new(|cx| {
10364 TestItem::new(cx)
10365 .with_dirty(true)
10366 .with_conflict(true)
10367 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10368 });
10369 let item3 = cx.new(|cx| {
10370 TestItem::new(cx)
10371 .with_dirty(true)
10372 .with_conflict(true)
10373 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10374 });
10375 let item4 = cx.new(|cx| {
10376 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10377 let project_item = TestProjectItem::new_untitled(cx);
10378 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10379 project_item
10380 }])
10381 });
10382 let pane = workspace.update_in(cx, |workspace, window, cx| {
10383 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10384 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10385 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10386 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10387 workspace.active_pane().clone()
10388 });
10389
10390 let close_items = pane.update_in(cx, |pane, window, cx| {
10391 pane.activate_item(1, true, true, window, cx);
10392 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10393 let item1_id = item1.item_id();
10394 let item3_id = item3.item_id();
10395 let item4_id = item4.item_id();
10396 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10397 [item1_id, item3_id, item4_id].contains(&id)
10398 })
10399 });
10400 cx.executor().run_until_parked();
10401
10402 assert!(cx.has_pending_prompt());
10403 cx.simulate_prompt_answer("Save all");
10404
10405 cx.executor().run_until_parked();
10406
10407 // Item 1 is saved. There's a prompt to save item 3.
10408 pane.update(cx, |pane, cx| {
10409 assert_eq!(item1.read(cx).save_count, 1);
10410 assert_eq!(item1.read(cx).save_as_count, 0);
10411 assert_eq!(item1.read(cx).reload_count, 0);
10412 assert_eq!(pane.items_len(), 3);
10413 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10414 });
10415 assert!(cx.has_pending_prompt());
10416
10417 // Cancel saving item 3.
10418 cx.simulate_prompt_answer("Discard");
10419 cx.executor().run_until_parked();
10420
10421 // Item 3 is reloaded. There's a prompt to save item 4.
10422 pane.update(cx, |pane, cx| {
10423 assert_eq!(item3.read(cx).save_count, 0);
10424 assert_eq!(item3.read(cx).save_as_count, 0);
10425 assert_eq!(item3.read(cx).reload_count, 1);
10426 assert_eq!(pane.items_len(), 2);
10427 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10428 });
10429
10430 // There's a prompt for a path for item 4.
10431 cx.simulate_new_path_selection(|_| Some(Default::default()));
10432 close_items.await.unwrap();
10433
10434 // The requested items are closed.
10435 pane.update(cx, |pane, cx| {
10436 assert_eq!(item4.read(cx).save_count, 0);
10437 assert_eq!(item4.read(cx).save_as_count, 1);
10438 assert_eq!(item4.read(cx).reload_count, 0);
10439 assert_eq!(pane.items_len(), 1);
10440 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10441 });
10442 }
10443
10444 #[gpui::test]
10445 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10446 init_test(cx);
10447
10448 let fs = FakeFs::new(cx.executor());
10449 let project = Project::test(fs, [], cx).await;
10450 let (workspace, cx) =
10451 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10452
10453 // Create several workspace items with single project entries, and two
10454 // workspace items with multiple project entries.
10455 let single_entry_items = (0..=4)
10456 .map(|project_entry_id| {
10457 cx.new(|cx| {
10458 TestItem::new(cx)
10459 .with_dirty(true)
10460 .with_project_items(&[dirty_project_item(
10461 project_entry_id,
10462 &format!("{project_entry_id}.txt"),
10463 cx,
10464 )])
10465 })
10466 })
10467 .collect::<Vec<_>>();
10468 let item_2_3 = cx.new(|cx| {
10469 TestItem::new(cx)
10470 .with_dirty(true)
10471 .with_buffer_kind(ItemBufferKind::Multibuffer)
10472 .with_project_items(&[
10473 single_entry_items[2].read(cx).project_items[0].clone(),
10474 single_entry_items[3].read(cx).project_items[0].clone(),
10475 ])
10476 });
10477 let item_3_4 = cx.new(|cx| {
10478 TestItem::new(cx)
10479 .with_dirty(true)
10480 .with_buffer_kind(ItemBufferKind::Multibuffer)
10481 .with_project_items(&[
10482 single_entry_items[3].read(cx).project_items[0].clone(),
10483 single_entry_items[4].read(cx).project_items[0].clone(),
10484 ])
10485 });
10486
10487 // Create two panes that contain the following project entries:
10488 // left pane:
10489 // multi-entry items: (2, 3)
10490 // single-entry items: 0, 2, 3, 4
10491 // right pane:
10492 // single-entry items: 4, 1
10493 // multi-entry items: (3, 4)
10494 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10495 let left_pane = workspace.active_pane().clone();
10496 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10497 workspace.add_item_to_active_pane(
10498 single_entry_items[0].boxed_clone(),
10499 None,
10500 true,
10501 window,
10502 cx,
10503 );
10504 workspace.add_item_to_active_pane(
10505 single_entry_items[2].boxed_clone(),
10506 None,
10507 true,
10508 window,
10509 cx,
10510 );
10511 workspace.add_item_to_active_pane(
10512 single_entry_items[3].boxed_clone(),
10513 None,
10514 true,
10515 window,
10516 cx,
10517 );
10518 workspace.add_item_to_active_pane(
10519 single_entry_items[4].boxed_clone(),
10520 None,
10521 true,
10522 window,
10523 cx,
10524 );
10525
10526 let right_pane =
10527 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10528
10529 let boxed_clone = single_entry_items[1].boxed_clone();
10530 let right_pane = window.spawn(cx, async move |cx| {
10531 right_pane.await.inspect(|right_pane| {
10532 right_pane
10533 .update_in(cx, |pane, window, cx| {
10534 pane.add_item(boxed_clone, true, true, None, window, cx);
10535 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10536 })
10537 .unwrap();
10538 })
10539 });
10540
10541 (left_pane, right_pane)
10542 });
10543 let right_pane = right_pane.await.unwrap();
10544 cx.focus(&right_pane);
10545
10546 let close = right_pane.update_in(cx, |pane, window, cx| {
10547 pane.close_all_items(&CloseAllItems::default(), window, cx)
10548 .unwrap()
10549 });
10550 cx.executor().run_until_parked();
10551
10552 let msg = cx.pending_prompt().unwrap().0;
10553 assert!(msg.contains("1.txt"));
10554 assert!(!msg.contains("2.txt"));
10555 assert!(!msg.contains("3.txt"));
10556 assert!(!msg.contains("4.txt"));
10557
10558 // With best-effort close, cancelling item 1 keeps it open but items 4
10559 // and (3,4) still close since their entries exist in left pane.
10560 cx.simulate_prompt_answer("Cancel");
10561 close.await;
10562
10563 right_pane.read_with(cx, |pane, _| {
10564 assert_eq!(pane.items_len(), 1);
10565 });
10566
10567 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10568 left_pane
10569 .update_in(cx, |left_pane, window, cx| {
10570 left_pane.close_item_by_id(
10571 single_entry_items[3].entity_id(),
10572 SaveIntent::Skip,
10573 window,
10574 cx,
10575 )
10576 })
10577 .await
10578 .unwrap();
10579
10580 let close = left_pane.update_in(cx, |pane, window, cx| {
10581 pane.close_all_items(&CloseAllItems::default(), window, cx)
10582 .unwrap()
10583 });
10584 cx.executor().run_until_parked();
10585
10586 let details = cx.pending_prompt().unwrap().1;
10587 assert!(details.contains("0.txt"));
10588 assert!(details.contains("3.txt"));
10589 assert!(details.contains("4.txt"));
10590 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10591 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10592 // assert!(!details.contains("2.txt"));
10593
10594 cx.simulate_prompt_answer("Save all");
10595 cx.executor().run_until_parked();
10596 close.await;
10597
10598 left_pane.read_with(cx, |pane, _| {
10599 assert_eq!(pane.items_len(), 0);
10600 });
10601 }
10602
10603 #[gpui::test]
10604 async fn test_autosave(cx: &mut gpui::TestAppContext) {
10605 init_test(cx);
10606
10607 let fs = FakeFs::new(cx.executor());
10608 let project = Project::test(fs, [], cx).await;
10609 let (workspace, cx) =
10610 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10611 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10612
10613 let item = cx.new(|cx| {
10614 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10615 });
10616 let item_id = item.entity_id();
10617 workspace.update_in(cx, |workspace, window, cx| {
10618 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10619 });
10620
10621 // Autosave on window change.
10622 item.update(cx, |item, cx| {
10623 SettingsStore::update_global(cx, |settings, cx| {
10624 settings.update_user_settings(cx, |settings| {
10625 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10626 })
10627 });
10628 item.is_dirty = true;
10629 });
10630
10631 // Deactivating the window saves the file.
10632 cx.deactivate_window();
10633 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10634
10635 // Re-activating the window doesn't save the file.
10636 cx.update(|window, _| window.activate_window());
10637 cx.executor().run_until_parked();
10638 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10639
10640 // Autosave on focus change.
10641 item.update_in(cx, |item, window, cx| {
10642 cx.focus_self(window);
10643 SettingsStore::update_global(cx, |settings, cx| {
10644 settings.update_user_settings(cx, |settings| {
10645 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10646 })
10647 });
10648 item.is_dirty = true;
10649 });
10650 // Blurring the item saves the file.
10651 item.update_in(cx, |_, window, _| window.blur());
10652 cx.executor().run_until_parked();
10653 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10654
10655 // Deactivating the window still saves the file.
10656 item.update_in(cx, |item, window, cx| {
10657 cx.focus_self(window);
10658 item.is_dirty = true;
10659 });
10660 cx.deactivate_window();
10661 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10662
10663 // Autosave after delay.
10664 item.update(cx, |item, cx| {
10665 SettingsStore::update_global(cx, |settings, cx| {
10666 settings.update_user_settings(cx, |settings| {
10667 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10668 milliseconds: 500.into(),
10669 });
10670 })
10671 });
10672 item.is_dirty = true;
10673 cx.emit(ItemEvent::Edit);
10674 });
10675
10676 // Delay hasn't fully expired, so the file is still dirty and unsaved.
10677 cx.executor().advance_clock(Duration::from_millis(250));
10678 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10679
10680 // After delay expires, the file is saved.
10681 cx.executor().advance_clock(Duration::from_millis(250));
10682 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10683
10684 // Autosave after delay, should save earlier than delay if tab is closed
10685 item.update(cx, |item, cx| {
10686 item.is_dirty = true;
10687 cx.emit(ItemEvent::Edit);
10688 });
10689 cx.executor().advance_clock(Duration::from_millis(250));
10690 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10691
10692 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10693 pane.update_in(cx, |pane, window, cx| {
10694 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10695 })
10696 .await
10697 .unwrap();
10698 assert!(!cx.has_pending_prompt());
10699 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10700
10701 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10702 workspace.update_in(cx, |workspace, window, cx| {
10703 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10704 });
10705 item.update_in(cx, |item, _window, cx| {
10706 item.is_dirty = true;
10707 for project_item in &mut item.project_items {
10708 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10709 }
10710 });
10711 cx.run_until_parked();
10712 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10713
10714 // Autosave on focus change, ensuring closing the tab counts as such.
10715 item.update(cx, |item, cx| {
10716 SettingsStore::update_global(cx, |settings, cx| {
10717 settings.update_user_settings(cx, |settings| {
10718 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10719 })
10720 });
10721 item.is_dirty = true;
10722 for project_item in &mut item.project_items {
10723 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10724 }
10725 });
10726
10727 pane.update_in(cx, |pane, window, cx| {
10728 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10729 })
10730 .await
10731 .unwrap();
10732 assert!(!cx.has_pending_prompt());
10733 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10734
10735 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10736 workspace.update_in(cx, |workspace, window, cx| {
10737 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10738 });
10739 item.update_in(cx, |item, window, cx| {
10740 item.project_items[0].update(cx, |item, _| {
10741 item.entry_id = None;
10742 });
10743 item.is_dirty = true;
10744 window.blur();
10745 });
10746 cx.run_until_parked();
10747 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10748
10749 // Ensure autosave is prevented for deleted files also when closing the buffer.
10750 let _close_items = pane.update_in(cx, |pane, window, cx| {
10751 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10752 });
10753 cx.run_until_parked();
10754 assert!(cx.has_pending_prompt());
10755 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10756 }
10757
10758 #[gpui::test]
10759 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
10760 init_test(cx);
10761
10762 let fs = FakeFs::new(cx.executor());
10763 let project = Project::test(fs, [], cx).await;
10764 let (workspace, cx) =
10765 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10766
10767 // Create a multibuffer-like item with two child focus handles,
10768 // simulating individual buffer editors within a multibuffer.
10769 let item = cx.new(|cx| {
10770 TestItem::new(cx)
10771 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10772 .with_child_focus_handles(2, cx)
10773 });
10774 workspace.update_in(cx, |workspace, window, cx| {
10775 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10776 });
10777
10778 // Set autosave to OnFocusChange and focus the first child handle,
10779 // simulating the user's cursor being inside one of the multibuffer's excerpts.
10780 item.update_in(cx, |item, window, cx| {
10781 SettingsStore::update_global(cx, |settings, cx| {
10782 settings.update_user_settings(cx, |settings| {
10783 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10784 })
10785 });
10786 item.is_dirty = true;
10787 window.focus(&item.child_focus_handles[0], cx);
10788 });
10789 cx.executor().run_until_parked();
10790 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
10791
10792 // Moving focus from one child to another within the same item should
10793 // NOT trigger autosave — focus is still within the item's focus hierarchy.
10794 item.update_in(cx, |item, window, cx| {
10795 window.focus(&item.child_focus_handles[1], cx);
10796 });
10797 cx.executor().run_until_parked();
10798 item.read_with(cx, |item, _| {
10799 assert_eq!(
10800 item.save_count, 0,
10801 "Switching focus between children within the same item should not autosave"
10802 );
10803 });
10804
10805 // Blurring the item saves the file. This is the core regression scenario:
10806 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
10807 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
10808 // the leaf is always a child focus handle, so `on_blur` never detected
10809 // focus leaving the item.
10810 item.update_in(cx, |_, window, _| window.blur());
10811 cx.executor().run_until_parked();
10812 item.read_with(cx, |item, _| {
10813 assert_eq!(
10814 item.save_count, 1,
10815 "Blurring should trigger autosave when focus was on a child of the item"
10816 );
10817 });
10818
10819 // Deactivating the window should also trigger autosave when a child of
10820 // the multibuffer item currently owns focus.
10821 item.update_in(cx, |item, window, cx| {
10822 item.is_dirty = true;
10823 window.focus(&item.child_focus_handles[0], cx);
10824 });
10825 cx.executor().run_until_parked();
10826 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10827
10828 cx.deactivate_window();
10829 item.read_with(cx, |item, _| {
10830 assert_eq!(
10831 item.save_count, 2,
10832 "Deactivating window should trigger autosave when focus was on a child"
10833 );
10834 });
10835 }
10836
10837 #[gpui::test]
10838 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10839 init_test(cx);
10840
10841 let fs = FakeFs::new(cx.executor());
10842
10843 let project = Project::test(fs, [], cx).await;
10844 let (workspace, cx) =
10845 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10846
10847 let item = cx.new(|cx| {
10848 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10849 });
10850 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10851 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10852 let toolbar_notify_count = Rc::new(RefCell::new(0));
10853
10854 workspace.update_in(cx, |workspace, window, cx| {
10855 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10856 let toolbar_notification_count = toolbar_notify_count.clone();
10857 cx.observe_in(&toolbar, window, move |_, _, _, _| {
10858 *toolbar_notification_count.borrow_mut() += 1
10859 })
10860 .detach();
10861 });
10862
10863 pane.read_with(cx, |pane, _| {
10864 assert!(!pane.can_navigate_backward());
10865 assert!(!pane.can_navigate_forward());
10866 });
10867
10868 item.update_in(cx, |item, _, cx| {
10869 item.set_state("one".to_string(), cx);
10870 });
10871
10872 // Toolbar must be notified to re-render the navigation buttons
10873 assert_eq!(*toolbar_notify_count.borrow(), 1);
10874
10875 pane.read_with(cx, |pane, _| {
10876 assert!(pane.can_navigate_backward());
10877 assert!(!pane.can_navigate_forward());
10878 });
10879
10880 workspace
10881 .update_in(cx, |workspace, window, cx| {
10882 workspace.go_back(pane.downgrade(), window, cx)
10883 })
10884 .await
10885 .unwrap();
10886
10887 assert_eq!(*toolbar_notify_count.borrow(), 2);
10888 pane.read_with(cx, |pane, _| {
10889 assert!(!pane.can_navigate_backward());
10890 assert!(pane.can_navigate_forward());
10891 });
10892 }
10893
10894 #[gpui::test]
10895 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
10896 init_test(cx);
10897 let fs = FakeFs::new(cx.executor());
10898 let project = Project::test(fs, [], cx).await;
10899 let (multi_workspace, cx) =
10900 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
10901 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
10902
10903 workspace.update_in(cx, |workspace, window, cx| {
10904 let first_item = cx.new(|cx| {
10905 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10906 });
10907 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
10908 workspace.split_pane(
10909 workspace.active_pane().clone(),
10910 SplitDirection::Right,
10911 window,
10912 cx,
10913 );
10914 workspace.split_pane(
10915 workspace.active_pane().clone(),
10916 SplitDirection::Right,
10917 window,
10918 cx,
10919 );
10920 });
10921
10922 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
10923 let panes = workspace.center.panes();
10924 assert!(panes.len() >= 2);
10925 (
10926 panes.first().expect("at least one pane").entity_id(),
10927 panes.last().expect("at least one pane").entity_id(),
10928 )
10929 });
10930
10931 workspace.update_in(cx, |workspace, window, cx| {
10932 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
10933 });
10934 workspace.update(cx, |workspace, _| {
10935 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
10936 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
10937 });
10938
10939 cx.dispatch_action(ActivateLastPane);
10940
10941 workspace.update(cx, |workspace, _| {
10942 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
10943 });
10944 }
10945
10946 #[gpui::test]
10947 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
10948 init_test(cx);
10949 let fs = FakeFs::new(cx.executor());
10950
10951 let project = Project::test(fs, [], cx).await;
10952 let (workspace, cx) =
10953 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10954
10955 let panel = workspace.update_in(cx, |workspace, window, cx| {
10956 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10957 workspace.add_panel(panel.clone(), window, cx);
10958
10959 workspace
10960 .right_dock()
10961 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10962
10963 panel
10964 });
10965
10966 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10967 pane.update_in(cx, |pane, window, cx| {
10968 let item = cx.new(TestItem::new);
10969 pane.add_item(Box::new(item), true, true, None, window, cx);
10970 });
10971
10972 // Transfer focus from center to panel
10973 workspace.update_in(cx, |workspace, window, cx| {
10974 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10975 });
10976
10977 workspace.update_in(cx, |workspace, window, cx| {
10978 assert!(workspace.right_dock().read(cx).is_open());
10979 assert!(!panel.is_zoomed(window, cx));
10980 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10981 });
10982
10983 // Transfer focus from panel to center
10984 workspace.update_in(cx, |workspace, window, cx| {
10985 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10986 });
10987
10988 workspace.update_in(cx, |workspace, window, cx| {
10989 assert!(workspace.right_dock().read(cx).is_open());
10990 assert!(!panel.is_zoomed(window, cx));
10991 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10992 });
10993
10994 // Close the dock
10995 workspace.update_in(cx, |workspace, window, cx| {
10996 workspace.toggle_dock(DockPosition::Right, window, cx);
10997 });
10998
10999 workspace.update_in(cx, |workspace, window, cx| {
11000 assert!(!workspace.right_dock().read(cx).is_open());
11001 assert!(!panel.is_zoomed(window, cx));
11002 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11003 });
11004
11005 // Open the dock
11006 workspace.update_in(cx, |workspace, window, cx| {
11007 workspace.toggle_dock(DockPosition::Right, window, cx);
11008 });
11009
11010 workspace.update_in(cx, |workspace, window, cx| {
11011 assert!(workspace.right_dock().read(cx).is_open());
11012 assert!(!panel.is_zoomed(window, cx));
11013 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11014 });
11015
11016 // Focus and zoom panel
11017 panel.update_in(cx, |panel, window, cx| {
11018 cx.focus_self(window);
11019 panel.set_zoomed(true, window, cx)
11020 });
11021
11022 workspace.update_in(cx, |workspace, window, cx| {
11023 assert!(workspace.right_dock().read(cx).is_open());
11024 assert!(panel.is_zoomed(window, cx));
11025 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11026 });
11027
11028 // Transfer focus to the center closes the dock
11029 workspace.update_in(cx, |workspace, window, cx| {
11030 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11031 });
11032
11033 workspace.update_in(cx, |workspace, window, cx| {
11034 assert!(!workspace.right_dock().read(cx).is_open());
11035 assert!(panel.is_zoomed(window, cx));
11036 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11037 });
11038
11039 // Transferring focus back to the panel keeps it zoomed
11040 workspace.update_in(cx, |workspace, window, cx| {
11041 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11042 });
11043
11044 workspace.update_in(cx, |workspace, window, cx| {
11045 assert!(workspace.right_dock().read(cx).is_open());
11046 assert!(panel.is_zoomed(window, cx));
11047 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11048 });
11049
11050 // Close the dock while it is zoomed
11051 workspace.update_in(cx, |workspace, window, cx| {
11052 workspace.toggle_dock(DockPosition::Right, window, cx)
11053 });
11054
11055 workspace.update_in(cx, |workspace, window, cx| {
11056 assert!(!workspace.right_dock().read(cx).is_open());
11057 assert!(panel.is_zoomed(window, cx));
11058 assert!(workspace.zoomed.is_none());
11059 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11060 });
11061
11062 // Opening the dock, when it's zoomed, retains focus
11063 workspace.update_in(cx, |workspace, window, cx| {
11064 workspace.toggle_dock(DockPosition::Right, window, cx)
11065 });
11066
11067 workspace.update_in(cx, |workspace, window, cx| {
11068 assert!(workspace.right_dock().read(cx).is_open());
11069 assert!(panel.is_zoomed(window, cx));
11070 assert!(workspace.zoomed.is_some());
11071 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11072 });
11073
11074 // Unzoom and close the panel, zoom the active pane.
11075 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11076 workspace.update_in(cx, |workspace, window, cx| {
11077 workspace.toggle_dock(DockPosition::Right, window, cx)
11078 });
11079 pane.update_in(cx, |pane, window, cx| {
11080 pane.toggle_zoom(&Default::default(), window, cx)
11081 });
11082
11083 // Opening a dock unzooms the pane.
11084 workspace.update_in(cx, |workspace, window, cx| {
11085 workspace.toggle_dock(DockPosition::Right, window, cx)
11086 });
11087 workspace.update_in(cx, |workspace, window, cx| {
11088 let pane = pane.read(cx);
11089 assert!(!pane.is_zoomed());
11090 assert!(!pane.focus_handle(cx).is_focused(window));
11091 assert!(workspace.right_dock().read(cx).is_open());
11092 assert!(workspace.zoomed.is_none());
11093 });
11094 }
11095
11096 #[gpui::test]
11097 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11098 init_test(cx);
11099 let fs = FakeFs::new(cx.executor());
11100
11101 let project = Project::test(fs, [], cx).await;
11102 let (workspace, cx) =
11103 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11104
11105 let panel = workspace.update_in(cx, |workspace, window, cx| {
11106 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11107 workspace.add_panel(panel.clone(), window, cx);
11108 panel
11109 });
11110
11111 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11112 pane.update_in(cx, |pane, window, cx| {
11113 let item = cx.new(TestItem::new);
11114 pane.add_item(Box::new(item), true, true, None, window, cx);
11115 });
11116
11117 // Enable close_panel_on_toggle
11118 cx.update_global(|store: &mut SettingsStore, cx| {
11119 store.update_user_settings(cx, |settings| {
11120 settings.workspace.close_panel_on_toggle = Some(true);
11121 });
11122 });
11123
11124 // Panel starts closed. Toggling should open and focus it.
11125 workspace.update_in(cx, |workspace, window, cx| {
11126 assert!(!workspace.right_dock().read(cx).is_open());
11127 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11128 });
11129
11130 workspace.update_in(cx, |workspace, window, cx| {
11131 assert!(
11132 workspace.right_dock().read(cx).is_open(),
11133 "Dock should be open after toggling from center"
11134 );
11135 assert!(
11136 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11137 "Panel should be focused after toggling from center"
11138 );
11139 });
11140
11141 // Panel is open and focused. Toggling should close the panel and
11142 // return focus to the center.
11143 workspace.update_in(cx, |workspace, window, cx| {
11144 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11145 });
11146
11147 workspace.update_in(cx, |workspace, window, cx| {
11148 assert!(
11149 !workspace.right_dock().read(cx).is_open(),
11150 "Dock should be closed after toggling from focused panel"
11151 );
11152 assert!(
11153 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11154 "Panel should not be focused after toggling from focused panel"
11155 );
11156 });
11157
11158 // Open the dock and focus something else so the panel is open but not
11159 // focused. Toggling should focus the panel (not close it).
11160 workspace.update_in(cx, |workspace, window, cx| {
11161 workspace
11162 .right_dock()
11163 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11164 window.focus(&pane.read(cx).focus_handle(cx), cx);
11165 });
11166
11167 workspace.update_in(cx, |workspace, window, cx| {
11168 assert!(workspace.right_dock().read(cx).is_open());
11169 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11170 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11171 });
11172
11173 workspace.update_in(cx, |workspace, window, cx| {
11174 assert!(
11175 workspace.right_dock().read(cx).is_open(),
11176 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11177 );
11178 assert!(
11179 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11180 "Panel should be focused after toggling an open-but-unfocused panel"
11181 );
11182 });
11183
11184 // Now disable the setting and verify the original behavior: toggling
11185 // from a focused panel moves focus to center but leaves the dock open.
11186 cx.update_global(|store: &mut SettingsStore, cx| {
11187 store.update_user_settings(cx, |settings| {
11188 settings.workspace.close_panel_on_toggle = Some(false);
11189 });
11190 });
11191
11192 workspace.update_in(cx, |workspace, window, cx| {
11193 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11194 });
11195
11196 workspace.update_in(cx, |workspace, window, cx| {
11197 assert!(
11198 workspace.right_dock().read(cx).is_open(),
11199 "Dock should remain open when setting is disabled"
11200 );
11201 assert!(
11202 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11203 "Panel should not be focused after toggling with setting disabled"
11204 );
11205 });
11206 }
11207
11208 #[gpui::test]
11209 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11210 init_test(cx);
11211 let fs = FakeFs::new(cx.executor());
11212
11213 let project = Project::test(fs, [], cx).await;
11214 let (workspace, cx) =
11215 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11216
11217 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11218 workspace.active_pane().clone()
11219 });
11220
11221 // Add an item to the pane so it can be zoomed
11222 workspace.update_in(cx, |workspace, window, cx| {
11223 let item = cx.new(TestItem::new);
11224 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11225 });
11226
11227 // Initially not zoomed
11228 workspace.update_in(cx, |workspace, _window, cx| {
11229 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11230 assert!(
11231 workspace.zoomed.is_none(),
11232 "Workspace should track no zoomed pane"
11233 );
11234 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11235 });
11236
11237 // Zoom In
11238 pane.update_in(cx, |pane, window, cx| {
11239 pane.zoom_in(&crate::ZoomIn, window, cx);
11240 });
11241
11242 workspace.update_in(cx, |workspace, window, cx| {
11243 assert!(
11244 pane.read(cx).is_zoomed(),
11245 "Pane should be zoomed after ZoomIn"
11246 );
11247 assert!(
11248 workspace.zoomed.is_some(),
11249 "Workspace should track the zoomed pane"
11250 );
11251 assert!(
11252 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11253 "ZoomIn should focus the pane"
11254 );
11255 });
11256
11257 // Zoom In again is a no-op
11258 pane.update_in(cx, |pane, window, cx| {
11259 pane.zoom_in(&crate::ZoomIn, window, cx);
11260 });
11261
11262 workspace.update_in(cx, |workspace, window, cx| {
11263 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11264 assert!(
11265 workspace.zoomed.is_some(),
11266 "Workspace still tracks zoomed pane"
11267 );
11268 assert!(
11269 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11270 "Pane remains focused after repeated ZoomIn"
11271 );
11272 });
11273
11274 // Zoom Out
11275 pane.update_in(cx, |pane, window, cx| {
11276 pane.zoom_out(&crate::ZoomOut, window, cx);
11277 });
11278
11279 workspace.update_in(cx, |workspace, _window, cx| {
11280 assert!(
11281 !pane.read(cx).is_zoomed(),
11282 "Pane should unzoom after ZoomOut"
11283 );
11284 assert!(
11285 workspace.zoomed.is_none(),
11286 "Workspace clears zoom tracking after ZoomOut"
11287 );
11288 });
11289
11290 // Zoom Out again is a no-op
11291 pane.update_in(cx, |pane, window, cx| {
11292 pane.zoom_out(&crate::ZoomOut, window, cx);
11293 });
11294
11295 workspace.update_in(cx, |workspace, _window, cx| {
11296 assert!(
11297 !pane.read(cx).is_zoomed(),
11298 "Second ZoomOut keeps pane unzoomed"
11299 );
11300 assert!(
11301 workspace.zoomed.is_none(),
11302 "Workspace remains without zoomed pane"
11303 );
11304 });
11305 }
11306
11307 #[gpui::test]
11308 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11309 init_test(cx);
11310 let fs = FakeFs::new(cx.executor());
11311
11312 let project = Project::test(fs, [], cx).await;
11313 let (workspace, cx) =
11314 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11315 workspace.update_in(cx, |workspace, window, cx| {
11316 // Open two docks
11317 let left_dock = workspace.dock_at_position(DockPosition::Left);
11318 let right_dock = workspace.dock_at_position(DockPosition::Right);
11319
11320 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11321 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11322
11323 assert!(left_dock.read(cx).is_open());
11324 assert!(right_dock.read(cx).is_open());
11325 });
11326
11327 workspace.update_in(cx, |workspace, window, cx| {
11328 // Toggle all docks - should close both
11329 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11330
11331 let left_dock = workspace.dock_at_position(DockPosition::Left);
11332 let right_dock = workspace.dock_at_position(DockPosition::Right);
11333 assert!(!left_dock.read(cx).is_open());
11334 assert!(!right_dock.read(cx).is_open());
11335 });
11336
11337 workspace.update_in(cx, |workspace, window, cx| {
11338 // Toggle again - should reopen both
11339 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11340
11341 let left_dock = workspace.dock_at_position(DockPosition::Left);
11342 let right_dock = workspace.dock_at_position(DockPosition::Right);
11343 assert!(left_dock.read(cx).is_open());
11344 assert!(right_dock.read(cx).is_open());
11345 });
11346 }
11347
11348 #[gpui::test]
11349 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11350 init_test(cx);
11351 let fs = FakeFs::new(cx.executor());
11352
11353 let project = Project::test(fs, [], cx).await;
11354 let (workspace, cx) =
11355 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11356 workspace.update_in(cx, |workspace, window, cx| {
11357 // Open two docks
11358 let left_dock = workspace.dock_at_position(DockPosition::Left);
11359 let right_dock = workspace.dock_at_position(DockPosition::Right);
11360
11361 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11362 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11363
11364 assert!(left_dock.read(cx).is_open());
11365 assert!(right_dock.read(cx).is_open());
11366 });
11367
11368 workspace.update_in(cx, |workspace, window, cx| {
11369 // Close them manually
11370 workspace.toggle_dock(DockPosition::Left, window, cx);
11371 workspace.toggle_dock(DockPosition::Right, window, cx);
11372
11373 let left_dock = workspace.dock_at_position(DockPosition::Left);
11374 let right_dock = workspace.dock_at_position(DockPosition::Right);
11375 assert!(!left_dock.read(cx).is_open());
11376 assert!(!right_dock.read(cx).is_open());
11377 });
11378
11379 workspace.update_in(cx, |workspace, window, cx| {
11380 // Toggle all docks - only last closed (right dock) should reopen
11381 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11382
11383 let left_dock = workspace.dock_at_position(DockPosition::Left);
11384 let right_dock = workspace.dock_at_position(DockPosition::Right);
11385 assert!(!left_dock.read(cx).is_open());
11386 assert!(right_dock.read(cx).is_open());
11387 });
11388 }
11389
11390 #[gpui::test]
11391 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11392 init_test(cx);
11393 let fs = FakeFs::new(cx.executor());
11394 let project = Project::test(fs, [], cx).await;
11395 let (multi_workspace, cx) =
11396 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11397 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11398
11399 // Open two docks (left and right) with one panel each
11400 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11401 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11402 workspace.add_panel(left_panel.clone(), window, cx);
11403
11404 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11405 workspace.add_panel(right_panel.clone(), window, cx);
11406
11407 workspace.toggle_dock(DockPosition::Left, window, cx);
11408 workspace.toggle_dock(DockPosition::Right, window, cx);
11409
11410 // Verify initial state
11411 assert!(
11412 workspace.left_dock().read(cx).is_open(),
11413 "Left dock should be open"
11414 );
11415 assert_eq!(
11416 workspace
11417 .left_dock()
11418 .read(cx)
11419 .visible_panel()
11420 .unwrap()
11421 .panel_id(),
11422 left_panel.panel_id(),
11423 "Left panel should be visible in left dock"
11424 );
11425 assert!(
11426 workspace.right_dock().read(cx).is_open(),
11427 "Right dock should be open"
11428 );
11429 assert_eq!(
11430 workspace
11431 .right_dock()
11432 .read(cx)
11433 .visible_panel()
11434 .unwrap()
11435 .panel_id(),
11436 right_panel.panel_id(),
11437 "Right panel should be visible in right dock"
11438 );
11439 assert!(
11440 !workspace.bottom_dock().read(cx).is_open(),
11441 "Bottom dock should be closed"
11442 );
11443
11444 (left_panel, right_panel)
11445 });
11446
11447 // Focus the left panel and move it to the next position (bottom dock)
11448 workspace.update_in(cx, |workspace, window, cx| {
11449 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11450 assert!(
11451 left_panel.read(cx).focus_handle(cx).is_focused(window),
11452 "Left panel should be focused"
11453 );
11454 });
11455
11456 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11457
11458 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11459 workspace.update(cx, |workspace, cx| {
11460 assert!(
11461 !workspace.left_dock().read(cx).is_open(),
11462 "Left dock should be closed"
11463 );
11464 assert!(
11465 workspace.bottom_dock().read(cx).is_open(),
11466 "Bottom dock should now be open"
11467 );
11468 assert_eq!(
11469 left_panel.read(cx).position,
11470 DockPosition::Bottom,
11471 "Left panel should now be in the bottom dock"
11472 );
11473 assert_eq!(
11474 workspace
11475 .bottom_dock()
11476 .read(cx)
11477 .visible_panel()
11478 .unwrap()
11479 .panel_id(),
11480 left_panel.panel_id(),
11481 "Left panel should be the visible panel in the bottom dock"
11482 );
11483 });
11484
11485 // Toggle all docks off
11486 workspace.update_in(cx, |workspace, window, cx| {
11487 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11488 assert!(
11489 !workspace.left_dock().read(cx).is_open(),
11490 "Left dock should be closed"
11491 );
11492 assert!(
11493 !workspace.right_dock().read(cx).is_open(),
11494 "Right dock should be closed"
11495 );
11496 assert!(
11497 !workspace.bottom_dock().read(cx).is_open(),
11498 "Bottom dock should be closed"
11499 );
11500 });
11501
11502 // Toggle all docks back on and verify positions are restored
11503 workspace.update_in(cx, |workspace, window, cx| {
11504 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11505 assert!(
11506 !workspace.left_dock().read(cx).is_open(),
11507 "Left dock should remain closed"
11508 );
11509 assert!(
11510 workspace.right_dock().read(cx).is_open(),
11511 "Right dock should remain open"
11512 );
11513 assert!(
11514 workspace.bottom_dock().read(cx).is_open(),
11515 "Bottom dock should remain open"
11516 );
11517 assert_eq!(
11518 left_panel.read(cx).position,
11519 DockPosition::Bottom,
11520 "Left panel should remain in the bottom dock"
11521 );
11522 assert_eq!(
11523 right_panel.read(cx).position,
11524 DockPosition::Right,
11525 "Right panel should remain in the right dock"
11526 );
11527 assert_eq!(
11528 workspace
11529 .bottom_dock()
11530 .read(cx)
11531 .visible_panel()
11532 .unwrap()
11533 .panel_id(),
11534 left_panel.panel_id(),
11535 "Left panel should be the visible panel in the right dock"
11536 );
11537 });
11538 }
11539
11540 #[gpui::test]
11541 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11542 init_test(cx);
11543
11544 let fs = FakeFs::new(cx.executor());
11545
11546 let project = Project::test(fs, None, cx).await;
11547 let (workspace, cx) =
11548 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11549
11550 // Let's arrange the panes like this:
11551 //
11552 // +-----------------------+
11553 // | top |
11554 // +------+--------+-------+
11555 // | left | center | right |
11556 // +------+--------+-------+
11557 // | bottom |
11558 // +-----------------------+
11559
11560 let top_item = cx.new(|cx| {
11561 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11562 });
11563 let bottom_item = cx.new(|cx| {
11564 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11565 });
11566 let left_item = cx.new(|cx| {
11567 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11568 });
11569 let right_item = cx.new(|cx| {
11570 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11571 });
11572 let center_item = cx.new(|cx| {
11573 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11574 });
11575
11576 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11577 let top_pane_id = workspace.active_pane().entity_id();
11578 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11579 workspace.split_pane(
11580 workspace.active_pane().clone(),
11581 SplitDirection::Down,
11582 window,
11583 cx,
11584 );
11585 top_pane_id
11586 });
11587 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11588 let bottom_pane_id = workspace.active_pane().entity_id();
11589 workspace.add_item_to_active_pane(
11590 Box::new(bottom_item.clone()),
11591 None,
11592 false,
11593 window,
11594 cx,
11595 );
11596 workspace.split_pane(
11597 workspace.active_pane().clone(),
11598 SplitDirection::Up,
11599 window,
11600 cx,
11601 );
11602 bottom_pane_id
11603 });
11604 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11605 let left_pane_id = workspace.active_pane().entity_id();
11606 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11607 workspace.split_pane(
11608 workspace.active_pane().clone(),
11609 SplitDirection::Right,
11610 window,
11611 cx,
11612 );
11613 left_pane_id
11614 });
11615 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11616 let right_pane_id = workspace.active_pane().entity_id();
11617 workspace.add_item_to_active_pane(
11618 Box::new(right_item.clone()),
11619 None,
11620 false,
11621 window,
11622 cx,
11623 );
11624 workspace.split_pane(
11625 workspace.active_pane().clone(),
11626 SplitDirection::Left,
11627 window,
11628 cx,
11629 );
11630 right_pane_id
11631 });
11632 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11633 let center_pane_id = workspace.active_pane().entity_id();
11634 workspace.add_item_to_active_pane(
11635 Box::new(center_item.clone()),
11636 None,
11637 false,
11638 window,
11639 cx,
11640 );
11641 center_pane_id
11642 });
11643 cx.executor().run_until_parked();
11644
11645 workspace.update_in(cx, |workspace, window, cx| {
11646 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11647
11648 // Join into next from center pane into right
11649 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11650 });
11651
11652 workspace.update_in(cx, |workspace, window, cx| {
11653 let active_pane = workspace.active_pane();
11654 assert_eq!(right_pane_id, active_pane.entity_id());
11655 assert_eq!(2, active_pane.read(cx).items_len());
11656 let item_ids_in_pane =
11657 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11658 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11659 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11660
11661 // Join into next from right pane into bottom
11662 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11663 });
11664
11665 workspace.update_in(cx, |workspace, window, cx| {
11666 let active_pane = workspace.active_pane();
11667 assert_eq!(bottom_pane_id, active_pane.entity_id());
11668 assert_eq!(3, active_pane.read(cx).items_len());
11669 let item_ids_in_pane =
11670 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11671 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11672 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11673 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11674
11675 // Join into next from bottom pane into left
11676 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11677 });
11678
11679 workspace.update_in(cx, |workspace, window, cx| {
11680 let active_pane = workspace.active_pane();
11681 assert_eq!(left_pane_id, active_pane.entity_id());
11682 assert_eq!(4, active_pane.read(cx).items_len());
11683 let item_ids_in_pane =
11684 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11685 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11686 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11687 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11688 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11689
11690 // Join into next from left pane into top
11691 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11692 });
11693
11694 workspace.update_in(cx, |workspace, window, cx| {
11695 let active_pane = workspace.active_pane();
11696 assert_eq!(top_pane_id, active_pane.entity_id());
11697 assert_eq!(5, active_pane.read(cx).items_len());
11698 let item_ids_in_pane =
11699 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11700 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11701 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11702 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11703 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11704 assert!(item_ids_in_pane.contains(&top_item.item_id()));
11705
11706 // Single pane left: no-op
11707 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11708 });
11709
11710 workspace.update(cx, |workspace, _cx| {
11711 let active_pane = workspace.active_pane();
11712 assert_eq!(top_pane_id, active_pane.entity_id());
11713 });
11714 }
11715
11716 fn add_an_item_to_active_pane(
11717 cx: &mut VisualTestContext,
11718 workspace: &Entity<Workspace>,
11719 item_id: u64,
11720 ) -> Entity<TestItem> {
11721 let item = cx.new(|cx| {
11722 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11723 item_id,
11724 "item{item_id}.txt",
11725 cx,
11726 )])
11727 });
11728 workspace.update_in(cx, |workspace, window, cx| {
11729 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11730 });
11731 item
11732 }
11733
11734 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11735 workspace.update_in(cx, |workspace, window, cx| {
11736 workspace.split_pane(
11737 workspace.active_pane().clone(),
11738 SplitDirection::Right,
11739 window,
11740 cx,
11741 )
11742 })
11743 }
11744
11745 #[gpui::test]
11746 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11747 init_test(cx);
11748 let fs = FakeFs::new(cx.executor());
11749 let project = Project::test(fs, None, cx).await;
11750 let (workspace, cx) =
11751 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11752
11753 add_an_item_to_active_pane(cx, &workspace, 1);
11754 split_pane(cx, &workspace);
11755 add_an_item_to_active_pane(cx, &workspace, 2);
11756 split_pane(cx, &workspace); // empty pane
11757 split_pane(cx, &workspace);
11758 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11759
11760 cx.executor().run_until_parked();
11761
11762 workspace.update(cx, |workspace, cx| {
11763 let num_panes = workspace.panes().len();
11764 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11765 let active_item = workspace
11766 .active_pane()
11767 .read(cx)
11768 .active_item()
11769 .expect("item is in focus");
11770
11771 assert_eq!(num_panes, 4);
11772 assert_eq!(num_items_in_current_pane, 1);
11773 assert_eq!(active_item.item_id(), last_item.item_id());
11774 });
11775
11776 workspace.update_in(cx, |workspace, window, cx| {
11777 workspace.join_all_panes(window, cx);
11778 });
11779
11780 workspace.update(cx, |workspace, cx| {
11781 let num_panes = workspace.panes().len();
11782 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11783 let active_item = workspace
11784 .active_pane()
11785 .read(cx)
11786 .active_item()
11787 .expect("item is in focus");
11788
11789 assert_eq!(num_panes, 1);
11790 assert_eq!(num_items_in_current_pane, 3);
11791 assert_eq!(active_item.item_id(), last_item.item_id());
11792 });
11793 }
11794 struct TestModal(FocusHandle);
11795
11796 impl TestModal {
11797 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11798 Self(cx.focus_handle())
11799 }
11800 }
11801
11802 impl EventEmitter<DismissEvent> for TestModal {}
11803
11804 impl Focusable for TestModal {
11805 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11806 self.0.clone()
11807 }
11808 }
11809
11810 impl ModalView for TestModal {}
11811
11812 impl Render for TestModal {
11813 fn render(
11814 &mut self,
11815 _window: &mut Window,
11816 _cx: &mut Context<TestModal>,
11817 ) -> impl IntoElement {
11818 div().track_focus(&self.0)
11819 }
11820 }
11821
11822 #[gpui::test]
11823 async fn test_panels(cx: &mut gpui::TestAppContext) {
11824 init_test(cx);
11825 let fs = FakeFs::new(cx.executor());
11826
11827 let project = Project::test(fs, [], cx).await;
11828 let (multi_workspace, cx) =
11829 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11830 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11831
11832 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11833 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11834 workspace.add_panel(panel_1.clone(), window, cx);
11835 workspace.toggle_dock(DockPosition::Left, window, cx);
11836 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11837 workspace.add_panel(panel_2.clone(), window, cx);
11838 workspace.toggle_dock(DockPosition::Right, window, cx);
11839
11840 let left_dock = workspace.left_dock();
11841 assert_eq!(
11842 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11843 panel_1.panel_id()
11844 );
11845 assert_eq!(
11846 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11847 panel_1.size(window, cx)
11848 );
11849
11850 left_dock.update(cx, |left_dock, cx| {
11851 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11852 });
11853 assert_eq!(
11854 workspace
11855 .right_dock()
11856 .read(cx)
11857 .visible_panel()
11858 .unwrap()
11859 .panel_id(),
11860 panel_2.panel_id(),
11861 );
11862
11863 (panel_1, panel_2)
11864 });
11865
11866 // Move panel_1 to the right
11867 panel_1.update_in(cx, |panel_1, window, cx| {
11868 panel_1.set_position(DockPosition::Right, window, cx)
11869 });
11870
11871 workspace.update_in(cx, |workspace, window, cx| {
11872 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11873 // Since it was the only panel on the left, the left dock should now be closed.
11874 assert!(!workspace.left_dock().read(cx).is_open());
11875 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11876 let right_dock = workspace.right_dock();
11877 assert_eq!(
11878 right_dock.read(cx).visible_panel().unwrap().panel_id(),
11879 panel_1.panel_id()
11880 );
11881 assert_eq!(
11882 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11883 px(1337.)
11884 );
11885
11886 // Now we move panel_2 to the left
11887 panel_2.set_position(DockPosition::Left, window, cx);
11888 });
11889
11890 workspace.update(cx, |workspace, cx| {
11891 // Since panel_2 was not visible on the right, we don't open the left dock.
11892 assert!(!workspace.left_dock().read(cx).is_open());
11893 // And the right dock is unaffected in its displaying of panel_1
11894 assert!(workspace.right_dock().read(cx).is_open());
11895 assert_eq!(
11896 workspace
11897 .right_dock()
11898 .read(cx)
11899 .visible_panel()
11900 .unwrap()
11901 .panel_id(),
11902 panel_1.panel_id(),
11903 );
11904 });
11905
11906 // Move panel_1 back to the left
11907 panel_1.update_in(cx, |panel_1, window, cx| {
11908 panel_1.set_position(DockPosition::Left, window, cx)
11909 });
11910
11911 workspace.update_in(cx, |workspace, window, cx| {
11912 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11913 let left_dock = workspace.left_dock();
11914 assert!(left_dock.read(cx).is_open());
11915 assert_eq!(
11916 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11917 panel_1.panel_id()
11918 );
11919 assert_eq!(
11920 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11921 px(1337.)
11922 );
11923 // And the right dock should be closed as it no longer has any panels.
11924 assert!(!workspace.right_dock().read(cx).is_open());
11925
11926 // Now we move panel_1 to the bottom
11927 panel_1.set_position(DockPosition::Bottom, window, cx);
11928 });
11929
11930 workspace.update_in(cx, |workspace, window, cx| {
11931 // Since panel_1 was visible on the left, we close the left dock.
11932 assert!(!workspace.left_dock().read(cx).is_open());
11933 // The bottom dock is sized based on the panel's default size,
11934 // since the panel orientation changed from vertical to horizontal.
11935 let bottom_dock = workspace.bottom_dock();
11936 assert_eq!(
11937 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
11938 panel_1.size(window, cx),
11939 );
11940 // Close bottom dock and move panel_1 back to the left.
11941 bottom_dock.update(cx, |bottom_dock, cx| {
11942 bottom_dock.set_open(false, window, cx)
11943 });
11944 panel_1.set_position(DockPosition::Left, window, cx);
11945 });
11946
11947 // Emit activated event on panel 1
11948 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
11949
11950 // Now the left dock is open and panel_1 is active and focused.
11951 workspace.update_in(cx, |workspace, window, cx| {
11952 let left_dock = workspace.left_dock();
11953 assert!(left_dock.read(cx).is_open());
11954 assert_eq!(
11955 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11956 panel_1.panel_id(),
11957 );
11958 assert!(panel_1.focus_handle(cx).is_focused(window));
11959 });
11960
11961 // Emit closed event on panel 2, which is not active
11962 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11963
11964 // Wo don't close the left dock, because panel_2 wasn't the active panel
11965 workspace.update(cx, |workspace, cx| {
11966 let left_dock = workspace.left_dock();
11967 assert!(left_dock.read(cx).is_open());
11968 assert_eq!(
11969 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11970 panel_1.panel_id(),
11971 );
11972 });
11973
11974 // Emitting a ZoomIn event shows the panel as zoomed.
11975 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
11976 workspace.read_with(cx, |workspace, _| {
11977 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11978 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
11979 });
11980
11981 // Move panel to another dock while it is zoomed
11982 panel_1.update_in(cx, |panel, window, cx| {
11983 panel.set_position(DockPosition::Right, window, cx)
11984 });
11985 workspace.read_with(cx, |workspace, _| {
11986 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11987
11988 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11989 });
11990
11991 // This is a helper for getting a:
11992 // - valid focus on an element,
11993 // - that isn't a part of the panes and panels system of the Workspace,
11994 // - and doesn't trigger the 'on_focus_lost' API.
11995 let focus_other_view = {
11996 let workspace = workspace.clone();
11997 move |cx: &mut VisualTestContext| {
11998 workspace.update_in(cx, |workspace, window, cx| {
11999 if workspace.active_modal::<TestModal>(cx).is_some() {
12000 workspace.toggle_modal(window, cx, TestModal::new);
12001 workspace.toggle_modal(window, cx, TestModal::new);
12002 } else {
12003 workspace.toggle_modal(window, cx, TestModal::new);
12004 }
12005 })
12006 }
12007 };
12008
12009 // If focus is transferred to another view that's not a panel or another pane, we still show
12010 // the panel as zoomed.
12011 focus_other_view(cx);
12012 workspace.read_with(cx, |workspace, _| {
12013 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12014 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12015 });
12016
12017 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12018 workspace.update_in(cx, |_workspace, window, cx| {
12019 cx.focus_self(window);
12020 });
12021 workspace.read_with(cx, |workspace, _| {
12022 assert_eq!(workspace.zoomed, None);
12023 assert_eq!(workspace.zoomed_position, None);
12024 });
12025
12026 // If focus is transferred again to another view that's not a panel or a pane, we won't
12027 // show the panel as zoomed because it wasn't zoomed before.
12028 focus_other_view(cx);
12029 workspace.read_with(cx, |workspace, _| {
12030 assert_eq!(workspace.zoomed, None);
12031 assert_eq!(workspace.zoomed_position, None);
12032 });
12033
12034 // When the panel is activated, it is zoomed again.
12035 cx.dispatch_action(ToggleRightDock);
12036 workspace.read_with(cx, |workspace, _| {
12037 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12038 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12039 });
12040
12041 // Emitting a ZoomOut event unzooms the panel.
12042 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12043 workspace.read_with(cx, |workspace, _| {
12044 assert_eq!(workspace.zoomed, None);
12045 assert_eq!(workspace.zoomed_position, None);
12046 });
12047
12048 // Emit closed event on panel 1, which is active
12049 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12050
12051 // Now the left dock is closed, because panel_1 was the active panel
12052 workspace.update(cx, |workspace, cx| {
12053 let right_dock = workspace.right_dock();
12054 assert!(!right_dock.read(cx).is_open());
12055 });
12056 }
12057
12058 #[gpui::test]
12059 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12060 init_test(cx);
12061
12062 let fs = FakeFs::new(cx.background_executor.clone());
12063 let project = Project::test(fs, [], cx).await;
12064 let (workspace, cx) =
12065 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12066 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12067
12068 let dirty_regular_buffer = cx.new(|cx| {
12069 TestItem::new(cx)
12070 .with_dirty(true)
12071 .with_label("1.txt")
12072 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12073 });
12074 let dirty_regular_buffer_2 = cx.new(|cx| {
12075 TestItem::new(cx)
12076 .with_dirty(true)
12077 .with_label("2.txt")
12078 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12079 });
12080 let dirty_multi_buffer_with_both = cx.new(|cx| {
12081 TestItem::new(cx)
12082 .with_dirty(true)
12083 .with_buffer_kind(ItemBufferKind::Multibuffer)
12084 .with_label("Fake Project Search")
12085 .with_project_items(&[
12086 dirty_regular_buffer.read(cx).project_items[0].clone(),
12087 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12088 ])
12089 });
12090 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12091 workspace.update_in(cx, |workspace, window, cx| {
12092 workspace.add_item(
12093 pane.clone(),
12094 Box::new(dirty_regular_buffer.clone()),
12095 None,
12096 false,
12097 false,
12098 window,
12099 cx,
12100 );
12101 workspace.add_item(
12102 pane.clone(),
12103 Box::new(dirty_regular_buffer_2.clone()),
12104 None,
12105 false,
12106 false,
12107 window,
12108 cx,
12109 );
12110 workspace.add_item(
12111 pane.clone(),
12112 Box::new(dirty_multi_buffer_with_both.clone()),
12113 None,
12114 false,
12115 false,
12116 window,
12117 cx,
12118 );
12119 });
12120
12121 pane.update_in(cx, |pane, window, cx| {
12122 pane.activate_item(2, true, true, window, cx);
12123 assert_eq!(
12124 pane.active_item().unwrap().item_id(),
12125 multi_buffer_with_both_files_id,
12126 "Should select the multi buffer in the pane"
12127 );
12128 });
12129 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12130 pane.close_other_items(
12131 &CloseOtherItems {
12132 save_intent: Some(SaveIntent::Save),
12133 close_pinned: true,
12134 },
12135 None,
12136 window,
12137 cx,
12138 )
12139 });
12140 cx.background_executor.run_until_parked();
12141 assert!(!cx.has_pending_prompt());
12142 close_all_but_multi_buffer_task
12143 .await
12144 .expect("Closing all buffers but the multi buffer failed");
12145 pane.update(cx, |pane, cx| {
12146 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12147 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12148 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12149 assert_eq!(pane.items_len(), 1);
12150 assert_eq!(
12151 pane.active_item().unwrap().item_id(),
12152 multi_buffer_with_both_files_id,
12153 "Should have only the multi buffer left in the pane"
12154 );
12155 assert!(
12156 dirty_multi_buffer_with_both.read(cx).is_dirty,
12157 "The multi buffer containing the unsaved buffer should still be dirty"
12158 );
12159 });
12160
12161 dirty_regular_buffer.update(cx, |buffer, cx| {
12162 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12163 });
12164
12165 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12166 pane.close_active_item(
12167 &CloseActiveItem {
12168 save_intent: Some(SaveIntent::Close),
12169 close_pinned: false,
12170 },
12171 window,
12172 cx,
12173 )
12174 });
12175 cx.background_executor.run_until_parked();
12176 assert!(
12177 cx.has_pending_prompt(),
12178 "Dirty multi buffer should prompt a save dialog"
12179 );
12180 cx.simulate_prompt_answer("Save");
12181 cx.background_executor.run_until_parked();
12182 close_multi_buffer_task
12183 .await
12184 .expect("Closing the multi buffer failed");
12185 pane.update(cx, |pane, cx| {
12186 assert_eq!(
12187 dirty_multi_buffer_with_both.read(cx).save_count,
12188 1,
12189 "Multi buffer item should get be saved"
12190 );
12191 // Test impl does not save inner items, so we do not assert them
12192 assert_eq!(
12193 pane.items_len(),
12194 0,
12195 "No more items should be left in the pane"
12196 );
12197 assert!(pane.active_item().is_none());
12198 });
12199 }
12200
12201 #[gpui::test]
12202 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
12203 cx: &mut TestAppContext,
12204 ) {
12205 init_test(cx);
12206
12207 let fs = FakeFs::new(cx.background_executor.clone());
12208 let project = Project::test(fs, [], cx).await;
12209 let (workspace, cx) =
12210 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12211 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12212
12213 let dirty_regular_buffer = cx.new(|cx| {
12214 TestItem::new(cx)
12215 .with_dirty(true)
12216 .with_label("1.txt")
12217 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12218 });
12219 let dirty_regular_buffer_2 = cx.new(|cx| {
12220 TestItem::new(cx)
12221 .with_dirty(true)
12222 .with_label("2.txt")
12223 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12224 });
12225 let clear_regular_buffer = cx.new(|cx| {
12226 TestItem::new(cx)
12227 .with_label("3.txt")
12228 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12229 });
12230
12231 let dirty_multi_buffer_with_both = cx.new(|cx| {
12232 TestItem::new(cx)
12233 .with_dirty(true)
12234 .with_buffer_kind(ItemBufferKind::Multibuffer)
12235 .with_label("Fake Project Search")
12236 .with_project_items(&[
12237 dirty_regular_buffer.read(cx).project_items[0].clone(),
12238 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12239 clear_regular_buffer.read(cx).project_items[0].clone(),
12240 ])
12241 });
12242 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12243 workspace.update_in(cx, |workspace, window, cx| {
12244 workspace.add_item(
12245 pane.clone(),
12246 Box::new(dirty_regular_buffer.clone()),
12247 None,
12248 false,
12249 false,
12250 window,
12251 cx,
12252 );
12253 workspace.add_item(
12254 pane.clone(),
12255 Box::new(dirty_multi_buffer_with_both.clone()),
12256 None,
12257 false,
12258 false,
12259 window,
12260 cx,
12261 );
12262 });
12263
12264 pane.update_in(cx, |pane, window, cx| {
12265 pane.activate_item(1, true, true, window, cx);
12266 assert_eq!(
12267 pane.active_item().unwrap().item_id(),
12268 multi_buffer_with_both_files_id,
12269 "Should select the multi buffer in the pane"
12270 );
12271 });
12272 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12273 pane.close_active_item(
12274 &CloseActiveItem {
12275 save_intent: None,
12276 close_pinned: false,
12277 },
12278 window,
12279 cx,
12280 )
12281 });
12282 cx.background_executor.run_until_parked();
12283 assert!(
12284 cx.has_pending_prompt(),
12285 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
12286 );
12287 }
12288
12289 /// Tests that when `close_on_file_delete` is enabled, files are automatically
12290 /// closed when they are deleted from disk.
12291 #[gpui::test]
12292 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
12293 init_test(cx);
12294
12295 // Enable the close_on_disk_deletion setting
12296 cx.update_global(|store: &mut SettingsStore, cx| {
12297 store.update_user_settings(cx, |settings| {
12298 settings.workspace.close_on_file_delete = Some(true);
12299 });
12300 });
12301
12302 let fs = FakeFs::new(cx.background_executor.clone());
12303 let project = Project::test(fs, [], cx).await;
12304 let (workspace, cx) =
12305 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12306 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12307
12308 // Create a test item that simulates a file
12309 let item = cx.new(|cx| {
12310 TestItem::new(cx)
12311 .with_label("test.txt")
12312 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12313 });
12314
12315 // Add item to workspace
12316 workspace.update_in(cx, |workspace, window, cx| {
12317 workspace.add_item(
12318 pane.clone(),
12319 Box::new(item.clone()),
12320 None,
12321 false,
12322 false,
12323 window,
12324 cx,
12325 );
12326 });
12327
12328 // Verify the item is in the pane
12329 pane.read_with(cx, |pane, _| {
12330 assert_eq!(pane.items().count(), 1);
12331 });
12332
12333 // Simulate file deletion by setting the item's deleted state
12334 item.update(cx, |item, _| {
12335 item.set_has_deleted_file(true);
12336 });
12337
12338 // Emit UpdateTab event to trigger the close behavior
12339 cx.run_until_parked();
12340 item.update(cx, |_, cx| {
12341 cx.emit(ItemEvent::UpdateTab);
12342 });
12343
12344 // Allow the close operation to complete
12345 cx.run_until_parked();
12346
12347 // Verify the item was automatically closed
12348 pane.read_with(cx, |pane, _| {
12349 assert_eq!(
12350 pane.items().count(),
12351 0,
12352 "Item should be automatically closed when file is deleted"
12353 );
12354 });
12355 }
12356
12357 /// Tests that when `close_on_file_delete` is disabled (default), files remain
12358 /// open with a strikethrough when they are deleted from disk.
12359 #[gpui::test]
12360 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12361 init_test(cx);
12362
12363 // Ensure close_on_disk_deletion is disabled (default)
12364 cx.update_global(|store: &mut SettingsStore, cx| {
12365 store.update_user_settings(cx, |settings| {
12366 settings.workspace.close_on_file_delete = Some(false);
12367 });
12368 });
12369
12370 let fs = FakeFs::new(cx.background_executor.clone());
12371 let project = Project::test(fs, [], cx).await;
12372 let (workspace, cx) =
12373 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12374 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12375
12376 // Create a test item that simulates a file
12377 let item = cx.new(|cx| {
12378 TestItem::new(cx)
12379 .with_label("test.txt")
12380 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12381 });
12382
12383 // Add item to workspace
12384 workspace.update_in(cx, |workspace, window, cx| {
12385 workspace.add_item(
12386 pane.clone(),
12387 Box::new(item.clone()),
12388 None,
12389 false,
12390 false,
12391 window,
12392 cx,
12393 );
12394 });
12395
12396 // Verify the item is in the pane
12397 pane.read_with(cx, |pane, _| {
12398 assert_eq!(pane.items().count(), 1);
12399 });
12400
12401 // Simulate file deletion
12402 item.update(cx, |item, _| {
12403 item.set_has_deleted_file(true);
12404 });
12405
12406 // Emit UpdateTab event
12407 cx.run_until_parked();
12408 item.update(cx, |_, cx| {
12409 cx.emit(ItemEvent::UpdateTab);
12410 });
12411
12412 // Allow any potential close operation to complete
12413 cx.run_until_parked();
12414
12415 // Verify the item remains open (with strikethrough)
12416 pane.read_with(cx, |pane, _| {
12417 assert_eq!(
12418 pane.items().count(),
12419 1,
12420 "Item should remain open when close_on_disk_deletion is disabled"
12421 );
12422 });
12423
12424 // Verify the item shows as deleted
12425 item.read_with(cx, |item, _| {
12426 assert!(
12427 item.has_deleted_file,
12428 "Item should be marked as having deleted file"
12429 );
12430 });
12431 }
12432
12433 /// Tests that dirty files are not automatically closed when deleted from disk,
12434 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12435 /// unsaved changes without being prompted.
12436 #[gpui::test]
12437 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12438 init_test(cx);
12439
12440 // Enable the close_on_file_delete setting
12441 cx.update_global(|store: &mut SettingsStore, cx| {
12442 store.update_user_settings(cx, |settings| {
12443 settings.workspace.close_on_file_delete = Some(true);
12444 });
12445 });
12446
12447 let fs = FakeFs::new(cx.background_executor.clone());
12448 let project = Project::test(fs, [], cx).await;
12449 let (workspace, cx) =
12450 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12451 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12452
12453 // Create a dirty test item
12454 let item = cx.new(|cx| {
12455 TestItem::new(cx)
12456 .with_dirty(true)
12457 .with_label("test.txt")
12458 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12459 });
12460
12461 // Add item to workspace
12462 workspace.update_in(cx, |workspace, window, cx| {
12463 workspace.add_item(
12464 pane.clone(),
12465 Box::new(item.clone()),
12466 None,
12467 false,
12468 false,
12469 window,
12470 cx,
12471 );
12472 });
12473
12474 // Simulate file deletion
12475 item.update(cx, |item, _| {
12476 item.set_has_deleted_file(true);
12477 });
12478
12479 // Emit UpdateTab event to trigger the close behavior
12480 cx.run_until_parked();
12481 item.update(cx, |_, cx| {
12482 cx.emit(ItemEvent::UpdateTab);
12483 });
12484
12485 // Allow any potential close operation to complete
12486 cx.run_until_parked();
12487
12488 // Verify the item remains open (dirty files are not auto-closed)
12489 pane.read_with(cx, |pane, _| {
12490 assert_eq!(
12491 pane.items().count(),
12492 1,
12493 "Dirty items should not be automatically closed even when file is deleted"
12494 );
12495 });
12496
12497 // Verify the item is marked as deleted and still dirty
12498 item.read_with(cx, |item, _| {
12499 assert!(
12500 item.has_deleted_file,
12501 "Item should be marked as having deleted file"
12502 );
12503 assert!(item.is_dirty, "Item should still be dirty");
12504 });
12505 }
12506
12507 /// Tests that navigation history is cleaned up when files are auto-closed
12508 /// due to deletion from disk.
12509 #[gpui::test]
12510 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12511 init_test(cx);
12512
12513 // Enable the close_on_file_delete setting
12514 cx.update_global(|store: &mut SettingsStore, cx| {
12515 store.update_user_settings(cx, |settings| {
12516 settings.workspace.close_on_file_delete = Some(true);
12517 });
12518 });
12519
12520 let fs = FakeFs::new(cx.background_executor.clone());
12521 let project = Project::test(fs, [], cx).await;
12522 let (workspace, cx) =
12523 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12524 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12525
12526 // Create test items
12527 let item1 = cx.new(|cx| {
12528 TestItem::new(cx)
12529 .with_label("test1.txt")
12530 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12531 });
12532 let item1_id = item1.item_id();
12533
12534 let item2 = cx.new(|cx| {
12535 TestItem::new(cx)
12536 .with_label("test2.txt")
12537 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12538 });
12539
12540 // Add items to workspace
12541 workspace.update_in(cx, |workspace, window, cx| {
12542 workspace.add_item(
12543 pane.clone(),
12544 Box::new(item1.clone()),
12545 None,
12546 false,
12547 false,
12548 window,
12549 cx,
12550 );
12551 workspace.add_item(
12552 pane.clone(),
12553 Box::new(item2.clone()),
12554 None,
12555 false,
12556 false,
12557 window,
12558 cx,
12559 );
12560 });
12561
12562 // Activate item1 to ensure it gets navigation entries
12563 pane.update_in(cx, |pane, window, cx| {
12564 pane.activate_item(0, true, true, window, cx);
12565 });
12566
12567 // Switch to item2 and back to create navigation history
12568 pane.update_in(cx, |pane, window, cx| {
12569 pane.activate_item(1, true, true, window, cx);
12570 });
12571 cx.run_until_parked();
12572
12573 pane.update_in(cx, |pane, window, cx| {
12574 pane.activate_item(0, true, true, window, cx);
12575 });
12576 cx.run_until_parked();
12577
12578 // Simulate file deletion for item1
12579 item1.update(cx, |item, _| {
12580 item.set_has_deleted_file(true);
12581 });
12582
12583 // Emit UpdateTab event to trigger the close behavior
12584 item1.update(cx, |_, cx| {
12585 cx.emit(ItemEvent::UpdateTab);
12586 });
12587 cx.run_until_parked();
12588
12589 // Verify item1 was closed
12590 pane.read_with(cx, |pane, _| {
12591 assert_eq!(
12592 pane.items().count(),
12593 1,
12594 "Should have 1 item remaining after auto-close"
12595 );
12596 });
12597
12598 // Check navigation history after close
12599 let has_item = pane.read_with(cx, |pane, cx| {
12600 let mut has_item = false;
12601 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12602 if entry.item.id() == item1_id {
12603 has_item = true;
12604 }
12605 });
12606 has_item
12607 });
12608
12609 assert!(
12610 !has_item,
12611 "Navigation history should not contain closed item entries"
12612 );
12613 }
12614
12615 #[gpui::test]
12616 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12617 cx: &mut TestAppContext,
12618 ) {
12619 init_test(cx);
12620
12621 let fs = FakeFs::new(cx.background_executor.clone());
12622 let project = Project::test(fs, [], cx).await;
12623 let (workspace, cx) =
12624 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12625 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12626
12627 let dirty_regular_buffer = cx.new(|cx| {
12628 TestItem::new(cx)
12629 .with_dirty(true)
12630 .with_label("1.txt")
12631 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12632 });
12633 let dirty_regular_buffer_2 = cx.new(|cx| {
12634 TestItem::new(cx)
12635 .with_dirty(true)
12636 .with_label("2.txt")
12637 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12638 });
12639 let clear_regular_buffer = cx.new(|cx| {
12640 TestItem::new(cx)
12641 .with_label("3.txt")
12642 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12643 });
12644
12645 let dirty_multi_buffer = cx.new(|cx| {
12646 TestItem::new(cx)
12647 .with_dirty(true)
12648 .with_buffer_kind(ItemBufferKind::Multibuffer)
12649 .with_label("Fake Project Search")
12650 .with_project_items(&[
12651 dirty_regular_buffer.read(cx).project_items[0].clone(),
12652 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12653 clear_regular_buffer.read(cx).project_items[0].clone(),
12654 ])
12655 });
12656 workspace.update_in(cx, |workspace, window, cx| {
12657 workspace.add_item(
12658 pane.clone(),
12659 Box::new(dirty_regular_buffer.clone()),
12660 None,
12661 false,
12662 false,
12663 window,
12664 cx,
12665 );
12666 workspace.add_item(
12667 pane.clone(),
12668 Box::new(dirty_regular_buffer_2.clone()),
12669 None,
12670 false,
12671 false,
12672 window,
12673 cx,
12674 );
12675 workspace.add_item(
12676 pane.clone(),
12677 Box::new(dirty_multi_buffer.clone()),
12678 None,
12679 false,
12680 false,
12681 window,
12682 cx,
12683 );
12684 });
12685
12686 pane.update_in(cx, |pane, window, cx| {
12687 pane.activate_item(2, true, true, window, cx);
12688 assert_eq!(
12689 pane.active_item().unwrap().item_id(),
12690 dirty_multi_buffer.item_id(),
12691 "Should select the multi buffer in the pane"
12692 );
12693 });
12694 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12695 pane.close_active_item(
12696 &CloseActiveItem {
12697 save_intent: None,
12698 close_pinned: false,
12699 },
12700 window,
12701 cx,
12702 )
12703 });
12704 cx.background_executor.run_until_parked();
12705 assert!(
12706 !cx.has_pending_prompt(),
12707 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12708 );
12709 close_multi_buffer_task
12710 .await
12711 .expect("Closing multi buffer failed");
12712 pane.update(cx, |pane, cx| {
12713 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12714 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12715 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12716 assert_eq!(
12717 pane.items()
12718 .map(|item| item.item_id())
12719 .sorted()
12720 .collect::<Vec<_>>(),
12721 vec![
12722 dirty_regular_buffer.item_id(),
12723 dirty_regular_buffer_2.item_id(),
12724 ],
12725 "Should have no multi buffer left in the pane"
12726 );
12727 assert!(dirty_regular_buffer.read(cx).is_dirty);
12728 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12729 });
12730 }
12731
12732 #[gpui::test]
12733 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12734 init_test(cx);
12735 let fs = FakeFs::new(cx.executor());
12736 let project = Project::test(fs, [], cx).await;
12737 let (multi_workspace, cx) =
12738 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12739 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12740
12741 // Add a new panel to the right dock, opening the dock and setting the
12742 // focus to the new panel.
12743 let panel = workspace.update_in(cx, |workspace, window, cx| {
12744 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12745 workspace.add_panel(panel.clone(), window, cx);
12746
12747 workspace
12748 .right_dock()
12749 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12750
12751 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12752
12753 panel
12754 });
12755
12756 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12757 // panel to the next valid position which, in this case, is the left
12758 // dock.
12759 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12760 workspace.update(cx, |workspace, cx| {
12761 assert!(workspace.left_dock().read(cx).is_open());
12762 assert_eq!(panel.read(cx).position, DockPosition::Left);
12763 });
12764
12765 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12766 // panel to the next valid position which, in this case, is the bottom
12767 // dock.
12768 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12769 workspace.update(cx, |workspace, cx| {
12770 assert!(workspace.bottom_dock().read(cx).is_open());
12771 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12772 });
12773
12774 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12775 // around moving the panel to its initial position, the right dock.
12776 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12777 workspace.update(cx, |workspace, cx| {
12778 assert!(workspace.right_dock().read(cx).is_open());
12779 assert_eq!(panel.read(cx).position, DockPosition::Right);
12780 });
12781
12782 // Remove focus from the panel, ensuring that, if the panel is not
12783 // focused, the `MoveFocusedPanelToNextPosition` action does not update
12784 // the panel's position, so the panel is still in the right dock.
12785 workspace.update_in(cx, |workspace, window, cx| {
12786 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12787 });
12788
12789 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12790 workspace.update(cx, |workspace, cx| {
12791 assert!(workspace.right_dock().read(cx).is_open());
12792 assert_eq!(panel.read(cx).position, DockPosition::Right);
12793 });
12794 }
12795
12796 #[gpui::test]
12797 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12798 init_test(cx);
12799
12800 let fs = FakeFs::new(cx.executor());
12801 let project = Project::test(fs, [], cx).await;
12802 let (workspace, cx) =
12803 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12804
12805 let item_1 = cx.new(|cx| {
12806 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12807 });
12808 workspace.update_in(cx, |workspace, window, cx| {
12809 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12810 workspace.move_item_to_pane_in_direction(
12811 &MoveItemToPaneInDirection {
12812 direction: SplitDirection::Right,
12813 focus: true,
12814 clone: false,
12815 },
12816 window,
12817 cx,
12818 );
12819 workspace.move_item_to_pane_at_index(
12820 &MoveItemToPane {
12821 destination: 3,
12822 focus: true,
12823 clone: false,
12824 },
12825 window,
12826 cx,
12827 );
12828
12829 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12830 assert_eq!(
12831 pane_items_paths(&workspace.active_pane, cx),
12832 vec!["first.txt".to_string()],
12833 "Single item was not moved anywhere"
12834 );
12835 });
12836
12837 let item_2 = cx.new(|cx| {
12838 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12839 });
12840 workspace.update_in(cx, |workspace, window, cx| {
12841 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12842 assert_eq!(
12843 pane_items_paths(&workspace.panes[0], cx),
12844 vec!["first.txt".to_string(), "second.txt".to_string()],
12845 );
12846 workspace.move_item_to_pane_in_direction(
12847 &MoveItemToPaneInDirection {
12848 direction: SplitDirection::Right,
12849 focus: true,
12850 clone: false,
12851 },
12852 window,
12853 cx,
12854 );
12855
12856 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12857 assert_eq!(
12858 pane_items_paths(&workspace.panes[0], cx),
12859 vec!["first.txt".to_string()],
12860 "After moving, one item should be left in the original pane"
12861 );
12862 assert_eq!(
12863 pane_items_paths(&workspace.panes[1], cx),
12864 vec!["second.txt".to_string()],
12865 "New item should have been moved to the new pane"
12866 );
12867 });
12868
12869 let item_3 = cx.new(|cx| {
12870 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12871 });
12872 workspace.update_in(cx, |workspace, window, cx| {
12873 let original_pane = workspace.panes[0].clone();
12874 workspace.set_active_pane(&original_pane, window, cx);
12875 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12876 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12877 assert_eq!(
12878 pane_items_paths(&workspace.active_pane, cx),
12879 vec!["first.txt".to_string(), "third.txt".to_string()],
12880 "New pane should be ready to move one item out"
12881 );
12882
12883 workspace.move_item_to_pane_at_index(
12884 &MoveItemToPane {
12885 destination: 3,
12886 focus: true,
12887 clone: false,
12888 },
12889 window,
12890 cx,
12891 );
12892 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12893 assert_eq!(
12894 pane_items_paths(&workspace.active_pane, cx),
12895 vec!["first.txt".to_string()],
12896 "After moving, one item should be left in the original pane"
12897 );
12898 assert_eq!(
12899 pane_items_paths(&workspace.panes[1], cx),
12900 vec!["second.txt".to_string()],
12901 "Previously created pane should be unchanged"
12902 );
12903 assert_eq!(
12904 pane_items_paths(&workspace.panes[2], cx),
12905 vec!["third.txt".to_string()],
12906 "New item should have been moved to the new pane"
12907 );
12908 });
12909 }
12910
12911 #[gpui::test]
12912 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12913 init_test(cx);
12914
12915 let fs = FakeFs::new(cx.executor());
12916 let project = Project::test(fs, [], cx).await;
12917 let (workspace, cx) =
12918 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12919
12920 let item_1 = cx.new(|cx| {
12921 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12922 });
12923 workspace.update_in(cx, |workspace, window, cx| {
12924 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12925 workspace.move_item_to_pane_in_direction(
12926 &MoveItemToPaneInDirection {
12927 direction: SplitDirection::Right,
12928 focus: true,
12929 clone: true,
12930 },
12931 window,
12932 cx,
12933 );
12934 });
12935 cx.run_until_parked();
12936 workspace.update_in(cx, |workspace, window, cx| {
12937 workspace.move_item_to_pane_at_index(
12938 &MoveItemToPane {
12939 destination: 3,
12940 focus: true,
12941 clone: true,
12942 },
12943 window,
12944 cx,
12945 );
12946 });
12947 cx.run_until_parked();
12948
12949 workspace.update(cx, |workspace, cx| {
12950 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
12951 for pane in workspace.panes() {
12952 assert_eq!(
12953 pane_items_paths(pane, cx),
12954 vec!["first.txt".to_string()],
12955 "Single item exists in all panes"
12956 );
12957 }
12958 });
12959
12960 // verify that the active pane has been updated after waiting for the
12961 // pane focus event to fire and resolve
12962 workspace.read_with(cx, |workspace, _app| {
12963 assert_eq!(
12964 workspace.active_pane(),
12965 &workspace.panes[2],
12966 "The third pane should be the active one: {:?}",
12967 workspace.panes
12968 );
12969 })
12970 }
12971
12972 #[gpui::test]
12973 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
12974 init_test(cx);
12975
12976 let fs = FakeFs::new(cx.executor());
12977 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
12978
12979 let project = Project::test(fs, ["root".as_ref()], cx).await;
12980 let (workspace, cx) =
12981 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12982
12983 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12984 // Add item to pane A with project path
12985 let item_a = cx.new(|cx| {
12986 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12987 });
12988 workspace.update_in(cx, |workspace, window, cx| {
12989 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
12990 });
12991
12992 // Split to create pane B
12993 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
12994 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
12995 });
12996
12997 // Add item with SAME project path to pane B, and pin it
12998 let item_b = cx.new(|cx| {
12999 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13000 });
13001 pane_b.update_in(cx, |pane, window, cx| {
13002 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13003 pane.set_pinned_count(1);
13004 });
13005
13006 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13007 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13008
13009 // close_pinned: false should only close the unpinned copy
13010 workspace.update_in(cx, |workspace, window, cx| {
13011 workspace.close_item_in_all_panes(
13012 &CloseItemInAllPanes {
13013 save_intent: Some(SaveIntent::Close),
13014 close_pinned: false,
13015 },
13016 window,
13017 cx,
13018 )
13019 });
13020 cx.executor().run_until_parked();
13021
13022 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13023 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13024 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13025 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13026
13027 // Split again, seeing as closing the previous item also closed its
13028 // pane, so only pane remains, which does not allow us to properly test
13029 // that both items close when `close_pinned: true`.
13030 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13031 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13032 });
13033
13034 // Add an item with the same project path to pane C so that
13035 // close_item_in_all_panes can determine what to close across all panes
13036 // (it reads the active item from the active pane, and split_pane
13037 // creates an empty pane).
13038 let item_c = cx.new(|cx| {
13039 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13040 });
13041 pane_c.update_in(cx, |pane, window, cx| {
13042 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13043 });
13044
13045 // close_pinned: true should close the pinned copy too
13046 workspace.update_in(cx, |workspace, window, cx| {
13047 let panes_count = workspace.panes().len();
13048 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13049
13050 workspace.close_item_in_all_panes(
13051 &CloseItemInAllPanes {
13052 save_intent: Some(SaveIntent::Close),
13053 close_pinned: true,
13054 },
13055 window,
13056 cx,
13057 )
13058 });
13059 cx.executor().run_until_parked();
13060
13061 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13062 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13063 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13064 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13065 }
13066
13067 mod register_project_item_tests {
13068
13069 use super::*;
13070
13071 // View
13072 struct TestPngItemView {
13073 focus_handle: FocusHandle,
13074 }
13075 // Model
13076 struct TestPngItem {}
13077
13078 impl project::ProjectItem for TestPngItem {
13079 fn try_open(
13080 _project: &Entity<Project>,
13081 path: &ProjectPath,
13082 cx: &mut App,
13083 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13084 if path.path.extension().unwrap() == "png" {
13085 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13086 } else {
13087 None
13088 }
13089 }
13090
13091 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13092 None
13093 }
13094
13095 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13096 None
13097 }
13098
13099 fn is_dirty(&self) -> bool {
13100 false
13101 }
13102 }
13103
13104 impl Item for TestPngItemView {
13105 type Event = ();
13106 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13107 "".into()
13108 }
13109 }
13110 impl EventEmitter<()> for TestPngItemView {}
13111 impl Focusable for TestPngItemView {
13112 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13113 self.focus_handle.clone()
13114 }
13115 }
13116
13117 impl Render for TestPngItemView {
13118 fn render(
13119 &mut self,
13120 _window: &mut Window,
13121 _cx: &mut Context<Self>,
13122 ) -> impl IntoElement {
13123 Empty
13124 }
13125 }
13126
13127 impl ProjectItem for TestPngItemView {
13128 type Item = TestPngItem;
13129
13130 fn for_project_item(
13131 _project: Entity<Project>,
13132 _pane: Option<&Pane>,
13133 _item: Entity<Self::Item>,
13134 _: &mut Window,
13135 cx: &mut Context<Self>,
13136 ) -> Self
13137 where
13138 Self: Sized,
13139 {
13140 Self {
13141 focus_handle: cx.focus_handle(),
13142 }
13143 }
13144 }
13145
13146 // View
13147 struct TestIpynbItemView {
13148 focus_handle: FocusHandle,
13149 }
13150 // Model
13151 struct TestIpynbItem {}
13152
13153 impl project::ProjectItem for TestIpynbItem {
13154 fn try_open(
13155 _project: &Entity<Project>,
13156 path: &ProjectPath,
13157 cx: &mut App,
13158 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13159 if path.path.extension().unwrap() == "ipynb" {
13160 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13161 } else {
13162 None
13163 }
13164 }
13165
13166 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13167 None
13168 }
13169
13170 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13171 None
13172 }
13173
13174 fn is_dirty(&self) -> bool {
13175 false
13176 }
13177 }
13178
13179 impl Item for TestIpynbItemView {
13180 type Event = ();
13181 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13182 "".into()
13183 }
13184 }
13185 impl EventEmitter<()> for TestIpynbItemView {}
13186 impl Focusable for TestIpynbItemView {
13187 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13188 self.focus_handle.clone()
13189 }
13190 }
13191
13192 impl Render for TestIpynbItemView {
13193 fn render(
13194 &mut self,
13195 _window: &mut Window,
13196 _cx: &mut Context<Self>,
13197 ) -> impl IntoElement {
13198 Empty
13199 }
13200 }
13201
13202 impl ProjectItem for TestIpynbItemView {
13203 type Item = TestIpynbItem;
13204
13205 fn for_project_item(
13206 _project: Entity<Project>,
13207 _pane: Option<&Pane>,
13208 _item: Entity<Self::Item>,
13209 _: &mut Window,
13210 cx: &mut Context<Self>,
13211 ) -> Self
13212 where
13213 Self: Sized,
13214 {
13215 Self {
13216 focus_handle: cx.focus_handle(),
13217 }
13218 }
13219 }
13220
13221 struct TestAlternatePngItemView {
13222 focus_handle: FocusHandle,
13223 }
13224
13225 impl Item for TestAlternatePngItemView {
13226 type Event = ();
13227 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13228 "".into()
13229 }
13230 }
13231
13232 impl EventEmitter<()> for TestAlternatePngItemView {}
13233 impl Focusable for TestAlternatePngItemView {
13234 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13235 self.focus_handle.clone()
13236 }
13237 }
13238
13239 impl Render for TestAlternatePngItemView {
13240 fn render(
13241 &mut self,
13242 _window: &mut Window,
13243 _cx: &mut Context<Self>,
13244 ) -> impl IntoElement {
13245 Empty
13246 }
13247 }
13248
13249 impl ProjectItem for TestAlternatePngItemView {
13250 type Item = TestPngItem;
13251
13252 fn for_project_item(
13253 _project: Entity<Project>,
13254 _pane: Option<&Pane>,
13255 _item: Entity<Self::Item>,
13256 _: &mut Window,
13257 cx: &mut Context<Self>,
13258 ) -> Self
13259 where
13260 Self: Sized,
13261 {
13262 Self {
13263 focus_handle: cx.focus_handle(),
13264 }
13265 }
13266 }
13267
13268 #[gpui::test]
13269 async fn test_register_project_item(cx: &mut TestAppContext) {
13270 init_test(cx);
13271
13272 cx.update(|cx| {
13273 register_project_item::<TestPngItemView>(cx);
13274 register_project_item::<TestIpynbItemView>(cx);
13275 });
13276
13277 let fs = FakeFs::new(cx.executor());
13278 fs.insert_tree(
13279 "/root1",
13280 json!({
13281 "one.png": "BINARYDATAHERE",
13282 "two.ipynb": "{ totally a notebook }",
13283 "three.txt": "editing text, sure why not?"
13284 }),
13285 )
13286 .await;
13287
13288 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13289 let (workspace, cx) =
13290 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13291
13292 let worktree_id = project.update(cx, |project, cx| {
13293 project.worktrees(cx).next().unwrap().read(cx).id()
13294 });
13295
13296 let handle = workspace
13297 .update_in(cx, |workspace, window, cx| {
13298 let project_path = (worktree_id, rel_path("one.png"));
13299 workspace.open_path(project_path, None, true, window, cx)
13300 })
13301 .await
13302 .unwrap();
13303
13304 // Now we can check if the handle we got back errored or not
13305 assert_eq!(
13306 handle.to_any_view().entity_type(),
13307 TypeId::of::<TestPngItemView>()
13308 );
13309
13310 let handle = workspace
13311 .update_in(cx, |workspace, window, cx| {
13312 let project_path = (worktree_id, rel_path("two.ipynb"));
13313 workspace.open_path(project_path, None, true, window, cx)
13314 })
13315 .await
13316 .unwrap();
13317
13318 assert_eq!(
13319 handle.to_any_view().entity_type(),
13320 TypeId::of::<TestIpynbItemView>()
13321 );
13322
13323 let handle = workspace
13324 .update_in(cx, |workspace, window, cx| {
13325 let project_path = (worktree_id, rel_path("three.txt"));
13326 workspace.open_path(project_path, None, true, window, cx)
13327 })
13328 .await;
13329 assert!(handle.is_err());
13330 }
13331
13332 #[gpui::test]
13333 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
13334 init_test(cx);
13335
13336 cx.update(|cx| {
13337 register_project_item::<TestPngItemView>(cx);
13338 register_project_item::<TestAlternatePngItemView>(cx);
13339 });
13340
13341 let fs = FakeFs::new(cx.executor());
13342 fs.insert_tree(
13343 "/root1",
13344 json!({
13345 "one.png": "BINARYDATAHERE",
13346 "two.ipynb": "{ totally a notebook }",
13347 "three.txt": "editing text, sure why not?"
13348 }),
13349 )
13350 .await;
13351 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13352 let (workspace, cx) =
13353 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13354 let worktree_id = project.update(cx, |project, cx| {
13355 project.worktrees(cx).next().unwrap().read(cx).id()
13356 });
13357
13358 let handle = workspace
13359 .update_in(cx, |workspace, window, cx| {
13360 let project_path = (worktree_id, rel_path("one.png"));
13361 workspace.open_path(project_path, None, true, window, cx)
13362 })
13363 .await
13364 .unwrap();
13365
13366 // This _must_ be the second item registered
13367 assert_eq!(
13368 handle.to_any_view().entity_type(),
13369 TypeId::of::<TestAlternatePngItemView>()
13370 );
13371
13372 let handle = workspace
13373 .update_in(cx, |workspace, window, cx| {
13374 let project_path = (worktree_id, rel_path("three.txt"));
13375 workspace.open_path(project_path, None, true, window, cx)
13376 })
13377 .await;
13378 assert!(handle.is_err());
13379 }
13380 }
13381
13382 #[gpui::test]
13383 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13384 init_test(cx);
13385
13386 let fs = FakeFs::new(cx.executor());
13387 let project = Project::test(fs, [], cx).await;
13388 let (workspace, _cx) =
13389 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13390
13391 // Test with status bar shown (default)
13392 workspace.read_with(cx, |workspace, cx| {
13393 let visible = workspace.status_bar_visible(cx);
13394 assert!(visible, "Status bar should be visible by default");
13395 });
13396
13397 // Test with status bar hidden
13398 cx.update_global(|store: &mut SettingsStore, cx| {
13399 store.update_user_settings(cx, |settings| {
13400 settings.status_bar.get_or_insert_default().show = Some(false);
13401 });
13402 });
13403
13404 workspace.read_with(cx, |workspace, cx| {
13405 let visible = workspace.status_bar_visible(cx);
13406 assert!(!visible, "Status bar should be hidden when show is false");
13407 });
13408
13409 // Test with status bar shown explicitly
13410 cx.update_global(|store: &mut SettingsStore, cx| {
13411 store.update_user_settings(cx, |settings| {
13412 settings.status_bar.get_or_insert_default().show = Some(true);
13413 });
13414 });
13415
13416 workspace.read_with(cx, |workspace, cx| {
13417 let visible = workspace.status_bar_visible(cx);
13418 assert!(visible, "Status bar should be visible when show is true");
13419 });
13420 }
13421
13422 #[gpui::test]
13423 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13424 init_test(cx);
13425
13426 let fs = FakeFs::new(cx.executor());
13427 let project = Project::test(fs, [], cx).await;
13428 let (multi_workspace, cx) =
13429 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13430 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13431 let panel = workspace.update_in(cx, |workspace, window, cx| {
13432 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13433 workspace.add_panel(panel.clone(), window, cx);
13434
13435 workspace
13436 .right_dock()
13437 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13438
13439 panel
13440 });
13441
13442 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13443 let item_a = cx.new(TestItem::new);
13444 let item_b = cx.new(TestItem::new);
13445 let item_a_id = item_a.entity_id();
13446 let item_b_id = item_b.entity_id();
13447
13448 pane.update_in(cx, |pane, window, cx| {
13449 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13450 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13451 });
13452
13453 pane.read_with(cx, |pane, _| {
13454 assert_eq!(pane.items_len(), 2);
13455 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13456 });
13457
13458 workspace.update_in(cx, |workspace, window, cx| {
13459 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13460 });
13461
13462 workspace.update_in(cx, |_, window, cx| {
13463 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13464 });
13465
13466 // Assert that the `pane::CloseActiveItem` action is handled at the
13467 // workspace level when one of the dock panels is focused and, in that
13468 // case, the center pane's active item is closed but the focus is not
13469 // moved.
13470 cx.dispatch_action(pane::CloseActiveItem::default());
13471 cx.run_until_parked();
13472
13473 pane.read_with(cx, |pane, _| {
13474 assert_eq!(pane.items_len(), 1);
13475 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13476 });
13477
13478 workspace.update_in(cx, |workspace, window, cx| {
13479 assert!(workspace.right_dock().read(cx).is_open());
13480 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13481 });
13482 }
13483
13484 #[gpui::test]
13485 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13486 init_test(cx);
13487 let fs = FakeFs::new(cx.executor());
13488
13489 let project_a = Project::test(fs.clone(), [], cx).await;
13490 let project_b = Project::test(fs, [], cx).await;
13491
13492 let multi_workspace_handle =
13493 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13494 cx.run_until_parked();
13495
13496 let workspace_a = multi_workspace_handle
13497 .read_with(cx, |mw, _| mw.workspace().clone())
13498 .unwrap();
13499
13500 let _workspace_b = multi_workspace_handle
13501 .update(cx, |mw, window, cx| {
13502 mw.test_add_workspace(project_b, window, cx)
13503 })
13504 .unwrap();
13505
13506 // Switch to workspace A
13507 multi_workspace_handle
13508 .update(cx, |mw, window, cx| {
13509 mw.activate_index(0, window, cx);
13510 })
13511 .unwrap();
13512
13513 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13514
13515 // Add a panel to workspace A's right dock and open the dock
13516 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13517 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13518 workspace.add_panel(panel.clone(), window, cx);
13519 workspace
13520 .right_dock()
13521 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13522 panel
13523 });
13524
13525 // Focus the panel through the workspace (matching existing test pattern)
13526 workspace_a.update_in(cx, |workspace, window, cx| {
13527 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13528 });
13529
13530 // Zoom the panel
13531 panel.update_in(cx, |panel, window, cx| {
13532 panel.set_zoomed(true, window, cx);
13533 });
13534
13535 // Verify the panel is zoomed and the dock is open
13536 workspace_a.update_in(cx, |workspace, window, cx| {
13537 assert!(
13538 workspace.right_dock().read(cx).is_open(),
13539 "dock should be open before switch"
13540 );
13541 assert!(
13542 panel.is_zoomed(window, cx),
13543 "panel should be zoomed before switch"
13544 );
13545 assert!(
13546 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13547 "panel should be focused before switch"
13548 );
13549 });
13550
13551 // Switch to workspace B
13552 multi_workspace_handle
13553 .update(cx, |mw, window, cx| {
13554 mw.activate_index(1, window, cx);
13555 })
13556 .unwrap();
13557 cx.run_until_parked();
13558
13559 // Switch back to workspace A
13560 multi_workspace_handle
13561 .update(cx, |mw, window, cx| {
13562 mw.activate_index(0, window, cx);
13563 })
13564 .unwrap();
13565 cx.run_until_parked();
13566
13567 // Verify the panel is still zoomed and the dock is still open
13568 workspace_a.update_in(cx, |workspace, window, cx| {
13569 assert!(
13570 workspace.right_dock().read(cx).is_open(),
13571 "dock should still be open after switching back"
13572 );
13573 assert!(
13574 panel.is_zoomed(window, cx),
13575 "panel should still be zoomed after switching back"
13576 );
13577 });
13578 }
13579
13580 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13581 pane.read(cx)
13582 .items()
13583 .flat_map(|item| {
13584 item.project_paths(cx)
13585 .into_iter()
13586 .map(|path| path.path.display(PathStyle::local()).into_owned())
13587 })
13588 .collect()
13589 }
13590
13591 pub fn init_test(cx: &mut TestAppContext) {
13592 cx.update(|cx| {
13593 let settings_store = SettingsStore::test(cx);
13594 cx.set_global(settings_store);
13595 theme::init(theme::LoadThemes::JustBase, cx);
13596 });
13597 }
13598
13599 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13600 let item = TestProjectItem::new(id, path, cx);
13601 item.update(cx, |item, _| {
13602 item.is_dirty = true;
13603 });
13604 item
13605 }
13606
13607 #[gpui::test]
13608 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13609 cx: &mut gpui::TestAppContext,
13610 ) {
13611 init_test(cx);
13612 let fs = FakeFs::new(cx.executor());
13613
13614 let project = Project::test(fs, [], cx).await;
13615 let (workspace, cx) =
13616 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13617
13618 let panel = workspace.update_in(cx, |workspace, window, cx| {
13619 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13620 workspace.add_panel(panel.clone(), window, cx);
13621 workspace
13622 .right_dock()
13623 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13624 panel
13625 });
13626
13627 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13628 pane.update_in(cx, |pane, window, cx| {
13629 let item = cx.new(TestItem::new);
13630 pane.add_item(Box::new(item), true, true, None, window, cx);
13631 });
13632
13633 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13634 // mirrors the real-world flow and avoids side effects from directly
13635 // focusing the panel while the center pane is active.
13636 workspace.update_in(cx, |workspace, window, cx| {
13637 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13638 });
13639
13640 panel.update_in(cx, |panel, window, cx| {
13641 panel.set_zoomed(true, window, cx);
13642 });
13643
13644 workspace.update_in(cx, |workspace, window, cx| {
13645 assert!(workspace.right_dock().read(cx).is_open());
13646 assert!(panel.is_zoomed(window, cx));
13647 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13648 });
13649
13650 // Simulate a spurious pane::Event::Focus on the center pane while the
13651 // panel still has focus. This mirrors what happens during macOS window
13652 // activation: the center pane fires a focus event even though actual
13653 // focus remains on the dock panel.
13654 pane.update_in(cx, |_, _, cx| {
13655 cx.emit(pane::Event::Focus);
13656 });
13657
13658 // The dock must remain open because the panel had focus at the time the
13659 // event was processed. Before the fix, dock_to_preserve was None for
13660 // panels that don't implement pane(), causing the dock to close.
13661 workspace.update_in(cx, |workspace, window, cx| {
13662 assert!(
13663 workspace.right_dock().read(cx).is_open(),
13664 "Dock should stay open when its zoomed panel (without pane()) still has focus"
13665 );
13666 assert!(panel.is_zoomed(window, cx));
13667 });
13668 }
13669}