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;
10mod path_list;
11mod persistence;
12pub mod searchable;
13mod security_modal;
14pub mod shared_screen;
15mod status_bar;
16pub mod tasks;
17mod theme_preview;
18mod toast_layer;
19mod toolbar;
20pub mod welcome;
21mod workspace_settings;
22
23pub use crate::notifications::NotificationFrame;
24pub use dock::Panel;
25pub use multi_workspace::{
26 DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace, NewWorkspaceInWindow,
27 NextWorkspaceInWindow, PreviousWorkspaceInWindow, Sidebar, SidebarEvent, SidebarHandle,
28 ToggleWorkspaceSidebar,
29};
30pub use path_list::PathList;
31pub use toast_layer::{ToastAction, ToastLayer, ToastView};
32
33use anyhow::{Context as _, Result, anyhow};
34use call::{ActiveCall, call_settings::CallSettings};
35use client::{
36 ChannelId, Client, ErrorExt, Status, TypedEnvelope, UserStore,
37 proto::{self, ErrorCode, PanelId, PeerId},
38};
39use collections::{HashMap, HashSet, hash_map};
40use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
41use futures::{
42 Future, FutureExt, StreamExt,
43 channel::{
44 mpsc::{self, UnboundedReceiver, UnboundedSender},
45 oneshot,
46 },
47 future::{Shared, try_join_all},
48};
49use gpui::{
50 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
51 CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
52 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
53 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
54 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
55 WindowOptions, actions, canvas, point, relative, size, transparent_black,
56};
57pub use history_manager::*;
58pub use item::{
59 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
60 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
61};
62use itertools::Itertools;
63use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
64pub use modal_layer::*;
65use node_runtime::NodeRuntime;
66use notifications::{
67 DetachAndPromptErr, Notifications, dismiss_app_notification,
68 simple_message_notification::MessageNotification,
69};
70pub use pane::*;
71pub use pane_group::{
72 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
73 SplitDirection,
74};
75use persistence::{DB, SerializedWindowBounds, model::SerializedWorkspace};
76pub use persistence::{
77 DB as WORKSPACE_DB, WorkspaceDb, delete_unloaded_items,
78 model::{ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation, SessionWorkspace},
79 read_serialized_multi_workspaces,
80};
81use postage::stream::Stream;
82use project::{
83 DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
84 WorktreeSettings,
85 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
86 project_settings::ProjectSettings,
87 toolchain_store::ToolchainStoreEvent,
88 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
89};
90use remote::{
91 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
92 remote_client::ConnectionIdentifier,
93};
94use schemars::JsonSchema;
95use serde::Deserialize;
96use session::AppSession;
97use settings::{
98 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
99};
100use shared_screen::SharedScreen;
101use sqlez::{
102 bindable::{Bind, Column, StaticColumnCount},
103 statement::Statement,
104};
105use status_bar::StatusBar;
106pub use status_bar::StatusItemView;
107use std::{
108 any::TypeId,
109 borrow::Cow,
110 cell::RefCell,
111 cmp,
112 collections::VecDeque,
113 env,
114 hash::Hash,
115 path::{Path, PathBuf},
116 process::ExitStatus,
117 rc::Rc,
118 sync::{
119 Arc, LazyLock, Weak,
120 atomic::{AtomicBool, AtomicUsize},
121 },
122 time::Duration,
123};
124use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
125use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
126pub use toolbar::{
127 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
128};
129pub use ui;
130use ui::{Window, prelude::*};
131use util::{
132 ResultExt, TryFutureExt,
133 paths::{PathStyle, SanitizedPath},
134 rel_path::RelPath,
135 serde::default_true,
136};
137use uuid::Uuid;
138pub use workspace_settings::{
139 AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
140 WorkspaceSettings,
141};
142use zed_actions::{Spawn, feedback::FileBugReport};
143
144use crate::{item::ItemBufferKind, notifications::NotificationId};
145use crate::{
146 persistence::{
147 SerializedAxis,
148 model::{DockData, DockStructure, SerializedItem, SerializedPane, SerializedPaneGroup},
149 },
150 security_modal::SecurityModal,
151};
152
153pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
154
155static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
156 env::var("ZED_WINDOW_SIZE")
157 .ok()
158 .as_deref()
159 .and_then(parse_pixel_size_env_var)
160});
161
162static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
163 env::var("ZED_WINDOW_POSITION")
164 .ok()
165 .as_deref()
166 .and_then(parse_pixel_position_env_var)
167});
168
169pub trait TerminalProvider {
170 fn spawn(
171 &self,
172 task: SpawnInTerminal,
173 window: &mut Window,
174 cx: &mut App,
175 ) -> Task<Option<Result<ExitStatus>>>;
176}
177
178pub trait DebuggerProvider {
179 // `active_buffer` is used to resolve build task's name against language-specific tasks.
180 fn start_session(
181 &self,
182 definition: DebugScenario,
183 task_context: SharedTaskContext,
184 active_buffer: Option<Entity<Buffer>>,
185 worktree_id: Option<WorktreeId>,
186 window: &mut Window,
187 cx: &mut App,
188 );
189
190 fn spawn_task_or_modal(
191 &self,
192 workspace: &mut Workspace,
193 action: &Spawn,
194 window: &mut Window,
195 cx: &mut Context<Workspace>,
196 );
197
198 fn task_scheduled(&self, cx: &mut App);
199 fn debug_scenario_scheduled(&self, cx: &mut App);
200 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
201
202 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
203}
204
205actions!(
206 workspace,
207 [
208 /// Activates the next pane in the workspace.
209 ActivateNextPane,
210 /// Activates the previous pane in the workspace.
211 ActivatePreviousPane,
212 /// Switches to the next window.
213 ActivateNextWindow,
214 /// Switches to the previous window.
215 ActivatePreviousWindow,
216 /// Adds a folder to the current project.
217 AddFolderToProject,
218 /// Clears all notifications.
219 ClearAllNotifications,
220 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
221 ClearNavigationHistory,
222 /// Closes the active dock.
223 CloseActiveDock,
224 /// Closes all docks.
225 CloseAllDocks,
226 /// Toggles all docks.
227 ToggleAllDocks,
228 /// Closes the current window.
229 CloseWindow,
230 /// Closes the current project.
231 CloseProject,
232 /// Opens the feedback dialog.
233 Feedback,
234 /// Follows the next collaborator in the session.
235 FollowNextCollaborator,
236 /// Moves the focused panel to the next position.
237 MoveFocusedPanelToNextPosition,
238 /// Creates a new file.
239 NewFile,
240 /// Creates a new file in a vertical split.
241 NewFileSplitVertical,
242 /// Creates a new file in a horizontal split.
243 NewFileSplitHorizontal,
244 /// Opens a new search.
245 NewSearch,
246 /// Opens a new window.
247 NewWindow,
248 /// Opens a file or directory.
249 Open,
250 /// Opens multiple files.
251 OpenFiles,
252 /// Opens the current location in terminal.
253 OpenInTerminal,
254 /// Opens the component preview.
255 OpenComponentPreview,
256 /// Reloads the active item.
257 ReloadActiveItem,
258 /// Resets the active dock to its default size.
259 ResetActiveDockSize,
260 /// Resets all open docks to their default sizes.
261 ResetOpenDocksSize,
262 /// Reloads the application
263 Reload,
264 /// Saves the current file with a new name.
265 SaveAs,
266 /// Saves without formatting.
267 SaveWithoutFormat,
268 /// Shuts down all debug adapters.
269 ShutdownDebugAdapters,
270 /// Suppresses the current notification.
271 SuppressNotification,
272 /// Toggles the bottom dock.
273 ToggleBottomDock,
274 /// Toggles centered layout mode.
275 ToggleCenteredLayout,
276 /// Toggles edit prediction feature globally for all files.
277 ToggleEditPrediction,
278 /// Toggles the left dock.
279 ToggleLeftDock,
280 /// Toggles the right dock.
281 ToggleRightDock,
282 /// Toggles zoom on the active pane.
283 ToggleZoom,
284 /// Toggles read-only mode for the active item (if supported by that item).
285 ToggleReadOnlyFile,
286 /// Zooms in on the active pane.
287 ZoomIn,
288 /// Zooms out of the active pane.
289 ZoomOut,
290 /// If any worktrees are in restricted mode, shows a modal with possible actions.
291 /// If the modal is shown already, closes it without trusting any worktree.
292 ToggleWorktreeSecurity,
293 /// Clears all trusted worktrees, placing them in restricted mode on next open.
294 /// Requires restart to take effect on already opened projects.
295 ClearTrustedWorktrees,
296 /// Stops following a collaborator.
297 Unfollow,
298 /// Restores the banner.
299 RestoreBanner,
300 /// Toggles expansion of the selected item.
301 ToggleExpandItem,
302 ]
303);
304
305/// Activates a specific pane by its index.
306#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
307#[action(namespace = workspace)]
308pub struct ActivatePane(pub usize);
309
310/// Moves an item to a specific pane by index.
311#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
312#[action(namespace = workspace)]
313#[serde(deny_unknown_fields)]
314pub struct MoveItemToPane {
315 #[serde(default = "default_1")]
316 pub destination: usize,
317 #[serde(default = "default_true")]
318 pub focus: bool,
319 #[serde(default)]
320 pub clone: bool,
321}
322
323fn default_1() -> usize {
324 1
325}
326
327/// Moves an item to a pane in the specified direction.
328#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
329#[action(namespace = workspace)]
330#[serde(deny_unknown_fields)]
331pub struct MoveItemToPaneInDirection {
332 #[serde(default = "default_right")]
333 pub direction: SplitDirection,
334 #[serde(default = "default_true")]
335 pub focus: bool,
336 #[serde(default)]
337 pub clone: bool,
338}
339
340/// Creates a new file in a split of the desired direction.
341#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
342#[action(namespace = workspace)]
343#[serde(deny_unknown_fields)]
344pub struct NewFileSplit(pub SplitDirection);
345
346fn default_right() -> SplitDirection {
347 SplitDirection::Right
348}
349
350/// Saves all open files in the workspace.
351#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
352#[action(namespace = workspace)]
353#[serde(deny_unknown_fields)]
354pub struct SaveAll {
355 #[serde(default)]
356 pub save_intent: Option<SaveIntent>,
357}
358
359/// Saves the current file with the specified options.
360#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
361#[action(namespace = workspace)]
362#[serde(deny_unknown_fields)]
363pub struct Save {
364 #[serde(default)]
365 pub save_intent: Option<SaveIntent>,
366}
367
368/// Closes all items and panes in the workspace.
369#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
370#[action(namespace = workspace)]
371#[serde(deny_unknown_fields)]
372pub struct CloseAllItemsAndPanes {
373 #[serde(default)]
374 pub save_intent: Option<SaveIntent>,
375}
376
377/// Closes all inactive tabs and panes in the workspace.
378#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
379#[action(namespace = workspace)]
380#[serde(deny_unknown_fields)]
381pub struct CloseInactiveTabsAndPanes {
382 #[serde(default)]
383 pub save_intent: Option<SaveIntent>,
384}
385
386/// Closes the active item across all panes.
387#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
388#[action(namespace = workspace)]
389#[serde(deny_unknown_fields)]
390pub struct CloseItemInAllPanes {
391 #[serde(default)]
392 pub save_intent: Option<SaveIntent>,
393 #[serde(default)]
394 pub close_pinned: bool,
395}
396
397/// Sends a sequence of keystrokes to the active element.
398#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
399#[action(namespace = workspace)]
400pub struct SendKeystrokes(pub String);
401
402actions!(
403 project_symbols,
404 [
405 /// Toggles the project symbols search.
406 #[action(name = "Toggle")]
407 ToggleProjectSymbols
408 ]
409);
410
411/// Toggles the file finder interface.
412#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
413#[action(namespace = file_finder, name = "Toggle")]
414#[serde(deny_unknown_fields)]
415pub struct ToggleFileFinder {
416 #[serde(default)]
417 pub separate_history: bool,
418}
419
420/// Opens a new terminal in the center.
421#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
422#[action(namespace = workspace)]
423#[serde(deny_unknown_fields)]
424pub struct NewCenterTerminal {
425 /// If true, creates a local terminal even in remote projects.
426 #[serde(default)]
427 pub local: bool,
428}
429
430/// Opens a new terminal.
431#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
432#[action(namespace = workspace)]
433#[serde(deny_unknown_fields)]
434pub struct NewTerminal {
435 /// If true, creates a local terminal even in remote projects.
436 #[serde(default)]
437 pub local: bool,
438}
439
440/// Increases size of a currently focused dock by a given amount of pixels.
441#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
442#[action(namespace = workspace)]
443#[serde(deny_unknown_fields)]
444pub struct IncreaseActiveDockSize {
445 /// For 0px parameter, uses UI font size value.
446 #[serde(default)]
447 pub px: u32,
448}
449
450/// Decreases size of a currently focused dock by a given amount of pixels.
451#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
452#[action(namespace = workspace)]
453#[serde(deny_unknown_fields)]
454pub struct DecreaseActiveDockSize {
455 /// For 0px parameter, uses UI font size value.
456 #[serde(default)]
457 pub px: u32,
458}
459
460/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
461#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
462#[action(namespace = workspace)]
463#[serde(deny_unknown_fields)]
464pub struct IncreaseOpenDocksSize {
465 /// For 0px parameter, uses UI font size value.
466 #[serde(default)]
467 pub px: u32,
468}
469
470/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
471#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
472#[action(namespace = workspace)]
473#[serde(deny_unknown_fields)]
474pub struct DecreaseOpenDocksSize {
475 /// For 0px parameter, uses UI font size value.
476 #[serde(default)]
477 pub px: u32,
478}
479
480actions!(
481 workspace,
482 [
483 /// Activates the pane to the left.
484 ActivatePaneLeft,
485 /// Activates the pane to the right.
486 ActivatePaneRight,
487 /// Activates the pane above.
488 ActivatePaneUp,
489 /// Activates the pane below.
490 ActivatePaneDown,
491 /// Swaps the current pane with the one to the left.
492 SwapPaneLeft,
493 /// Swaps the current pane with the one to the right.
494 SwapPaneRight,
495 /// Swaps the current pane with the one above.
496 SwapPaneUp,
497 /// Swaps the current pane with the one below.
498 SwapPaneDown,
499 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
500 SwapPaneAdjacent,
501 /// Move the current pane to be at the far left.
502 MovePaneLeft,
503 /// Move the current pane to be at the far right.
504 MovePaneRight,
505 /// Move the current pane to be at the very top.
506 MovePaneUp,
507 /// Move the current pane to be at the very bottom.
508 MovePaneDown,
509 ]
510);
511
512#[derive(PartialEq, Eq, Debug)]
513pub enum CloseIntent {
514 /// Quit the program entirely.
515 Quit,
516 /// Close a window.
517 CloseWindow,
518 /// Replace the workspace in an existing window.
519 ReplaceWindow,
520}
521
522#[derive(Clone)]
523pub struct Toast {
524 id: NotificationId,
525 msg: Cow<'static, str>,
526 autohide: bool,
527 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
528}
529
530impl Toast {
531 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
532 Toast {
533 id,
534 msg: msg.into(),
535 on_click: None,
536 autohide: false,
537 }
538 }
539
540 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
541 where
542 M: Into<Cow<'static, str>>,
543 F: Fn(&mut Window, &mut App) + 'static,
544 {
545 self.on_click = Some((message.into(), Arc::new(on_click)));
546 self
547 }
548
549 pub fn autohide(mut self) -> Self {
550 self.autohide = true;
551 self
552 }
553}
554
555impl PartialEq for Toast {
556 fn eq(&self, other: &Self) -> bool {
557 self.id == other.id
558 && self.msg == other.msg
559 && self.on_click.is_some() == other.on_click.is_some()
560 }
561}
562
563/// Opens a new terminal with the specified working directory.
564#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
565#[action(namespace = workspace)]
566#[serde(deny_unknown_fields)]
567pub struct OpenTerminal {
568 pub working_directory: PathBuf,
569 /// If true, creates a local terminal even in remote projects.
570 #[serde(default)]
571 pub local: bool,
572}
573
574#[derive(
575 Clone,
576 Copy,
577 Debug,
578 Default,
579 Hash,
580 PartialEq,
581 Eq,
582 PartialOrd,
583 Ord,
584 serde::Serialize,
585 serde::Deserialize,
586)]
587pub struct WorkspaceId(i64);
588
589impl WorkspaceId {
590 pub fn from_i64(value: i64) -> Self {
591 Self(value)
592 }
593}
594
595impl StaticColumnCount for WorkspaceId {}
596impl Bind for WorkspaceId {
597 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
598 self.0.bind(statement, start_index)
599 }
600}
601impl Column for WorkspaceId {
602 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
603 i64::column(statement, start_index)
604 .map(|(i, next_index)| (Self(i), next_index))
605 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
606 }
607}
608impl From<WorkspaceId> for i64 {
609 fn from(val: WorkspaceId) -> Self {
610 val.0
611 }
612}
613
614fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
615 let paths = cx.prompt_for_paths(options);
616 cx.spawn(
617 async move |cx| match paths.await.anyhow().and_then(|res| res) {
618 Ok(Some(paths)) => {
619 cx.update(|cx| {
620 open_paths(&paths, app_state, OpenOptions::default(), cx).detach_and_log_err(cx)
621 });
622 }
623 Ok(None) => {}
624 Err(err) => {
625 util::log_err(&err);
626 cx.update(|cx| {
627 if let Some(workspace_window) = cx
628 .active_window()
629 .and_then(|window| window.downcast::<MultiWorkspace>())
630 {
631 workspace_window
632 .update(cx, |multi_workspace, _, cx| {
633 let workspace = multi_workspace.workspace().clone();
634 workspace.update(cx, |workspace, cx| {
635 workspace.show_portal_error(err.to_string(), cx);
636 });
637 })
638 .ok();
639 }
640 });
641 }
642 },
643 )
644 .detach();
645}
646
647pub fn init(app_state: Arc<AppState>, cx: &mut App) {
648 component::init();
649 theme_preview::init(cx);
650 toast_layer::init(cx);
651 history_manager::init(app_state.fs.clone(), cx);
652
653 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
654 .on_action(|_: &Reload, cx| reload(cx))
655 .on_action({
656 let app_state = Arc::downgrade(&app_state);
657 move |_: &Open, cx: &mut App| {
658 if let Some(app_state) = app_state.upgrade() {
659 prompt_and_open_paths(
660 app_state,
661 PathPromptOptions {
662 files: true,
663 directories: true,
664 multiple: true,
665 prompt: None,
666 },
667 cx,
668 );
669 }
670 }
671 })
672 .on_action({
673 let app_state = Arc::downgrade(&app_state);
674 move |_: &OpenFiles, cx: &mut App| {
675 let directories = cx.can_select_mixed_files_and_dirs();
676 if let Some(app_state) = app_state.upgrade() {
677 prompt_and_open_paths(
678 app_state,
679 PathPromptOptions {
680 files: true,
681 directories,
682 multiple: true,
683 prompt: None,
684 },
685 cx,
686 );
687 }
688 }
689 });
690}
691
692type BuildProjectItemFn =
693 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
694
695type BuildProjectItemForPathFn =
696 fn(
697 &Entity<Project>,
698 &ProjectPath,
699 &mut Window,
700 &mut App,
701 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
702
703#[derive(Clone, Default)]
704struct ProjectItemRegistry {
705 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
706 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
707}
708
709impl ProjectItemRegistry {
710 fn register<T: ProjectItem>(&mut self) {
711 self.build_project_item_fns_by_type.insert(
712 TypeId::of::<T::Item>(),
713 |item, project, pane, window, cx| {
714 let item = item.downcast().unwrap();
715 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
716 as Box<dyn ItemHandle>
717 },
718 );
719 self.build_project_item_for_path_fns
720 .push(|project, project_path, window, cx| {
721 let project_path = project_path.clone();
722 let is_file = project
723 .read(cx)
724 .entry_for_path(&project_path, cx)
725 .is_some_and(|entry| entry.is_file());
726 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
727 let is_local = project.read(cx).is_local();
728 let project_item =
729 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
730 let project = project.clone();
731 Some(window.spawn(cx, async move |cx| {
732 match project_item.await.with_context(|| {
733 format!(
734 "opening project path {:?}",
735 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
736 )
737 }) {
738 Ok(project_item) => {
739 let project_item = project_item;
740 let project_entry_id: Option<ProjectEntryId> =
741 project_item.read_with(cx, project::ProjectItem::entry_id);
742 let build_workspace_item = Box::new(
743 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
744 Box::new(cx.new(|cx| {
745 T::for_project_item(
746 project,
747 Some(pane),
748 project_item,
749 window,
750 cx,
751 )
752 })) as Box<dyn ItemHandle>
753 },
754 ) as Box<_>;
755 Ok((project_entry_id, build_workspace_item))
756 }
757 Err(e) => {
758 log::warn!("Failed to open a project item: {e:#}");
759 if e.error_code() == ErrorCode::Internal {
760 if let Some(abs_path) =
761 entry_abs_path.as_deref().filter(|_| is_file)
762 {
763 if let Some(broken_project_item_view) =
764 cx.update(|window, cx| {
765 T::for_broken_project_item(
766 abs_path, is_local, &e, window, cx,
767 )
768 })?
769 {
770 let build_workspace_item = Box::new(
771 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
772 cx.new(|_| broken_project_item_view).boxed_clone()
773 },
774 )
775 as Box<_>;
776 return Ok((None, build_workspace_item));
777 }
778 }
779 }
780 Err(e)
781 }
782 }
783 }))
784 });
785 }
786
787 fn open_path(
788 &self,
789 project: &Entity<Project>,
790 path: &ProjectPath,
791 window: &mut Window,
792 cx: &mut App,
793 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
794 let Some(open_project_item) = self
795 .build_project_item_for_path_fns
796 .iter()
797 .rev()
798 .find_map(|open_project_item| open_project_item(project, path, window, cx))
799 else {
800 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
801 };
802 open_project_item
803 }
804
805 fn build_item<T: project::ProjectItem>(
806 &self,
807 item: Entity<T>,
808 project: Entity<Project>,
809 pane: Option<&Pane>,
810 window: &mut Window,
811 cx: &mut App,
812 ) -> Option<Box<dyn ItemHandle>> {
813 let build = self
814 .build_project_item_fns_by_type
815 .get(&TypeId::of::<T>())?;
816 Some(build(item.into_any(), project, pane, window, cx))
817 }
818}
819
820type WorkspaceItemBuilder =
821 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
822
823impl Global for ProjectItemRegistry {}
824
825/// Registers a [ProjectItem] for the app. When opening a file, all the registered
826/// items will get a chance to open the file, starting from the project item that
827/// was added last.
828pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
829 cx.default_global::<ProjectItemRegistry>().register::<I>();
830}
831
832#[derive(Default)]
833pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
834
835struct FollowableViewDescriptor {
836 from_state_proto: fn(
837 Entity<Workspace>,
838 ViewId,
839 &mut Option<proto::view::Variant>,
840 &mut Window,
841 &mut App,
842 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
843 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
844}
845
846impl Global for FollowableViewRegistry {}
847
848impl FollowableViewRegistry {
849 pub fn register<I: FollowableItem>(cx: &mut App) {
850 cx.default_global::<Self>().0.insert(
851 TypeId::of::<I>(),
852 FollowableViewDescriptor {
853 from_state_proto: |workspace, id, state, window, cx| {
854 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
855 cx.foreground_executor()
856 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
857 })
858 },
859 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
860 },
861 );
862 }
863
864 pub fn from_state_proto(
865 workspace: Entity<Workspace>,
866 view_id: ViewId,
867 mut state: Option<proto::view::Variant>,
868 window: &mut Window,
869 cx: &mut App,
870 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
871 cx.update_default_global(|this: &mut Self, cx| {
872 this.0.values().find_map(|descriptor| {
873 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
874 })
875 })
876 }
877
878 pub fn to_followable_view(
879 view: impl Into<AnyView>,
880 cx: &App,
881 ) -> Option<Box<dyn FollowableItemHandle>> {
882 let this = cx.try_global::<Self>()?;
883 let view = view.into();
884 let descriptor = this.0.get(&view.entity_type())?;
885 Some((descriptor.to_followable_view)(&view))
886 }
887}
888
889#[derive(Copy, Clone)]
890struct SerializableItemDescriptor {
891 deserialize: fn(
892 Entity<Project>,
893 WeakEntity<Workspace>,
894 WorkspaceId,
895 ItemId,
896 &mut Window,
897 &mut Context<Pane>,
898 ) -> Task<Result<Box<dyn ItemHandle>>>,
899 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
900 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
901}
902
903#[derive(Default)]
904struct SerializableItemRegistry {
905 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
906 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
907}
908
909impl Global for SerializableItemRegistry {}
910
911impl SerializableItemRegistry {
912 fn deserialize(
913 item_kind: &str,
914 project: Entity<Project>,
915 workspace: WeakEntity<Workspace>,
916 workspace_id: WorkspaceId,
917 item_item: ItemId,
918 window: &mut Window,
919 cx: &mut Context<Pane>,
920 ) -> Task<Result<Box<dyn ItemHandle>>> {
921 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
922 return Task::ready(Err(anyhow!(
923 "cannot deserialize {}, descriptor not found",
924 item_kind
925 )));
926 };
927
928 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
929 }
930
931 fn cleanup(
932 item_kind: &str,
933 workspace_id: WorkspaceId,
934 loaded_items: Vec<ItemId>,
935 window: &mut Window,
936 cx: &mut App,
937 ) -> Task<Result<()>> {
938 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
939 return Task::ready(Err(anyhow!(
940 "cannot cleanup {}, descriptor not found",
941 item_kind
942 )));
943 };
944
945 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
946 }
947
948 fn view_to_serializable_item_handle(
949 view: AnyView,
950 cx: &App,
951 ) -> Option<Box<dyn SerializableItemHandle>> {
952 let this = cx.try_global::<Self>()?;
953 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
954 Some((descriptor.view_to_serializable_item)(view))
955 }
956
957 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
958 let this = cx.try_global::<Self>()?;
959 this.descriptors_by_kind.get(item_kind).copied()
960 }
961}
962
963pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
964 let serialized_item_kind = I::serialized_item_kind();
965
966 let registry = cx.default_global::<SerializableItemRegistry>();
967 let descriptor = SerializableItemDescriptor {
968 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
969 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
970 cx.foreground_executor()
971 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
972 },
973 cleanup: |workspace_id, loaded_items, window, cx| {
974 I::cleanup(workspace_id, loaded_items, window, cx)
975 },
976 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
977 };
978 registry
979 .descriptors_by_kind
980 .insert(Arc::from(serialized_item_kind), descriptor);
981 registry
982 .descriptors_by_type
983 .insert(TypeId::of::<I>(), descriptor);
984}
985
986pub struct AppState {
987 pub languages: Arc<LanguageRegistry>,
988 pub client: Arc<Client>,
989 pub user_store: Entity<UserStore>,
990 pub workspace_store: Entity<WorkspaceStore>,
991 pub fs: Arc<dyn fs::Fs>,
992 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
993 pub node_runtime: NodeRuntime,
994 pub session: Entity<AppSession>,
995}
996
997struct GlobalAppState(Weak<AppState>);
998
999impl Global for GlobalAppState {}
1000
1001pub struct WorkspaceStore {
1002 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1003 client: Arc<Client>,
1004 _subscriptions: Vec<client::Subscription>,
1005}
1006
1007#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1008pub enum CollaboratorId {
1009 PeerId(PeerId),
1010 Agent,
1011}
1012
1013impl From<PeerId> for CollaboratorId {
1014 fn from(peer_id: PeerId) -> Self {
1015 CollaboratorId::PeerId(peer_id)
1016 }
1017}
1018
1019impl From<&PeerId> for CollaboratorId {
1020 fn from(peer_id: &PeerId) -> Self {
1021 CollaboratorId::PeerId(*peer_id)
1022 }
1023}
1024
1025#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1026struct Follower {
1027 project_id: Option<u64>,
1028 peer_id: PeerId,
1029}
1030
1031impl AppState {
1032 #[track_caller]
1033 pub fn global(cx: &App) -> Weak<Self> {
1034 cx.global::<GlobalAppState>().0.clone()
1035 }
1036 pub fn try_global(cx: &App) -> Option<Weak<Self>> {
1037 cx.try_global::<GlobalAppState>()
1038 .map(|state| state.0.clone())
1039 }
1040 pub fn set_global(state: Weak<AppState>, cx: &mut App) {
1041 cx.set_global(GlobalAppState(state));
1042 }
1043
1044 #[cfg(any(test, feature = "test-support"))]
1045 pub fn test(cx: &mut App) -> Arc<Self> {
1046 use fs::Fs;
1047 use node_runtime::NodeRuntime;
1048 use session::Session;
1049 use settings::SettingsStore;
1050
1051 if !cx.has_global::<SettingsStore>() {
1052 let settings_store = SettingsStore::test(cx);
1053 cx.set_global(settings_store);
1054 }
1055
1056 let fs = fs::FakeFs::new(cx.background_executor().clone());
1057 <dyn Fs>::set_global(fs.clone(), cx);
1058 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1059 let clock = Arc::new(clock::FakeSystemClock::new());
1060 let http_client = http_client::FakeHttpClient::with_404_response();
1061 let client = Client::new(clock, http_client, cx);
1062 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1063 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1064 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1065
1066 theme::init(theme::LoadThemes::JustBase, cx);
1067 client::init(&client, cx);
1068
1069 Arc::new(Self {
1070 client,
1071 fs,
1072 languages,
1073 user_store,
1074 workspace_store,
1075 node_runtime: NodeRuntime::unavailable(),
1076 build_window_options: |_, _| Default::default(),
1077 session,
1078 })
1079 }
1080}
1081
1082struct DelayedDebouncedEditAction {
1083 task: Option<Task<()>>,
1084 cancel_channel: Option<oneshot::Sender<()>>,
1085}
1086
1087impl DelayedDebouncedEditAction {
1088 fn new() -> DelayedDebouncedEditAction {
1089 DelayedDebouncedEditAction {
1090 task: None,
1091 cancel_channel: None,
1092 }
1093 }
1094
1095 fn fire_new<F>(
1096 &mut self,
1097 delay: Duration,
1098 window: &mut Window,
1099 cx: &mut Context<Workspace>,
1100 func: F,
1101 ) where
1102 F: 'static
1103 + Send
1104 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1105 {
1106 if let Some(channel) = self.cancel_channel.take() {
1107 _ = channel.send(());
1108 }
1109
1110 let (sender, mut receiver) = oneshot::channel::<()>();
1111 self.cancel_channel = Some(sender);
1112
1113 let previous_task = self.task.take();
1114 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1115 let mut timer = cx.background_executor().timer(delay).fuse();
1116 if let Some(previous_task) = previous_task {
1117 previous_task.await;
1118 }
1119
1120 futures::select_biased! {
1121 _ = receiver => return,
1122 _ = timer => {}
1123 }
1124
1125 if let Some(result) = workspace
1126 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1127 .log_err()
1128 {
1129 result.await.log_err();
1130 }
1131 }));
1132 }
1133}
1134
1135pub enum Event {
1136 PaneAdded(Entity<Pane>),
1137 PaneRemoved,
1138 ItemAdded {
1139 item: Box<dyn ItemHandle>,
1140 },
1141 ActiveItemChanged,
1142 ItemRemoved {
1143 item_id: EntityId,
1144 },
1145 UserSavedItem {
1146 pane: WeakEntity<Pane>,
1147 item: Box<dyn WeakItemHandle>,
1148 save_intent: SaveIntent,
1149 },
1150 ContactRequestedJoin(u64),
1151 WorkspaceCreated(WeakEntity<Workspace>),
1152 OpenBundledFile {
1153 text: Cow<'static, str>,
1154 title: &'static str,
1155 language: &'static str,
1156 },
1157 ZoomChanged,
1158 ModalOpened,
1159}
1160
1161#[derive(Debug, Clone)]
1162pub enum OpenVisible {
1163 All,
1164 None,
1165 OnlyFiles,
1166 OnlyDirectories,
1167}
1168
1169enum WorkspaceLocation {
1170 // Valid local paths or SSH project to serialize
1171 Location(SerializedWorkspaceLocation, PathList),
1172 // No valid location found hence clear session id
1173 DetachFromSession,
1174 // No valid location found to serialize
1175 None,
1176}
1177
1178type PromptForNewPath = Box<
1179 dyn Fn(
1180 &mut Workspace,
1181 DirectoryLister,
1182 Option<String>,
1183 &mut Window,
1184 &mut Context<Workspace>,
1185 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1186>;
1187
1188type PromptForOpenPath = Box<
1189 dyn Fn(
1190 &mut Workspace,
1191 DirectoryLister,
1192 &mut Window,
1193 &mut Context<Workspace>,
1194 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1195>;
1196
1197#[derive(Default)]
1198struct DispatchingKeystrokes {
1199 dispatched: HashSet<Vec<Keystroke>>,
1200 queue: VecDeque<Keystroke>,
1201 task: Option<Shared<Task<()>>>,
1202}
1203
1204/// Collects everything project-related for a certain window opened.
1205/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1206///
1207/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1208/// The `Workspace` owns everybody's state and serves as a default, "global context",
1209/// that can be used to register a global action to be triggered from any place in the window.
1210pub struct Workspace {
1211 weak_self: WeakEntity<Self>,
1212 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1213 zoomed: Option<AnyWeakView>,
1214 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1215 zoomed_position: Option<DockPosition>,
1216 center: PaneGroup,
1217 left_dock: Entity<Dock>,
1218 bottom_dock: Entity<Dock>,
1219 right_dock: Entity<Dock>,
1220 panes: Vec<Entity<Pane>>,
1221 active_worktree_override: Option<WorktreeId>,
1222 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1223 active_pane: Entity<Pane>,
1224 last_active_center_pane: Option<WeakEntity<Pane>>,
1225 last_active_view_id: Option<proto::ViewId>,
1226 status_bar: Entity<StatusBar>,
1227 modal_layer: Entity<ModalLayer>,
1228 toast_layer: Entity<ToastLayer>,
1229 titlebar_item: Option<AnyView>,
1230 notifications: Notifications,
1231 suppressed_notifications: HashSet<NotificationId>,
1232 project: Entity<Project>,
1233 follower_states: HashMap<CollaboratorId, FollowerState>,
1234 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1235 window_edited: bool,
1236 last_window_title: Option<String>,
1237 dirty_items: HashMap<EntityId, Subscription>,
1238 active_call: Option<(Entity<ActiveCall>, Vec<Subscription>)>,
1239 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1240 database_id: Option<WorkspaceId>,
1241 app_state: Arc<AppState>,
1242 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1243 _subscriptions: Vec<Subscription>,
1244 _apply_leader_updates: Task<Result<()>>,
1245 _observe_current_user: Task<Result<()>>,
1246 _schedule_serialize_workspace: Option<Task<()>>,
1247 _serialize_workspace_task: Option<Task<()>>,
1248 _schedule_serialize_ssh_paths: Option<Task<()>>,
1249 pane_history_timestamp: Arc<AtomicUsize>,
1250 bounds: Bounds<Pixels>,
1251 pub centered_layout: bool,
1252 bounds_save_task_queued: Option<Task<()>>,
1253 on_prompt_for_new_path: Option<PromptForNewPath>,
1254 on_prompt_for_open_path: Option<PromptForOpenPath>,
1255 terminal_provider: Option<Box<dyn TerminalProvider>>,
1256 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1257 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1258 _items_serializer: Task<Result<()>>,
1259 session_id: Option<String>,
1260 scheduled_tasks: Vec<Task<()>>,
1261 last_open_dock_positions: Vec<DockPosition>,
1262 removing: bool,
1263}
1264
1265impl EventEmitter<Event> for Workspace {}
1266
1267#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1268pub struct ViewId {
1269 pub creator: CollaboratorId,
1270 pub id: u64,
1271}
1272
1273pub struct FollowerState {
1274 center_pane: Entity<Pane>,
1275 dock_pane: Option<Entity<Pane>>,
1276 active_view_id: Option<ViewId>,
1277 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1278}
1279
1280struct FollowerView {
1281 view: Box<dyn FollowableItemHandle>,
1282 location: Option<proto::PanelId>,
1283}
1284
1285impl Workspace {
1286 pub fn new(
1287 workspace_id: Option<WorkspaceId>,
1288 project: Entity<Project>,
1289 app_state: Arc<AppState>,
1290 window: &mut Window,
1291 cx: &mut Context<Self>,
1292 ) -> Self {
1293 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1294 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1295 if let TrustedWorktreesEvent::Trusted(..) = e {
1296 // Do not persist auto trusted worktrees
1297 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1298 worktrees_store.update(cx, |worktrees_store, cx| {
1299 worktrees_store.schedule_serialization(
1300 cx,
1301 |new_trusted_worktrees, cx| {
1302 let timeout =
1303 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1304 cx.background_spawn(async move {
1305 timeout.await;
1306 persistence::DB
1307 .save_trusted_worktrees(new_trusted_worktrees)
1308 .await
1309 .log_err();
1310 })
1311 },
1312 )
1313 });
1314 }
1315 }
1316 })
1317 .detach();
1318
1319 cx.observe_global::<SettingsStore>(|_, cx| {
1320 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1321 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1322 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1323 trusted_worktrees.auto_trust_all(cx);
1324 })
1325 }
1326 }
1327 })
1328 .detach();
1329 }
1330
1331 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1332 match event {
1333 project::Event::RemoteIdChanged(_) => {
1334 this.update_window_title(window, cx);
1335 }
1336
1337 project::Event::CollaboratorLeft(peer_id) => {
1338 this.collaborator_left(*peer_id, window, cx);
1339 }
1340
1341 &project::Event::WorktreeRemoved(id) | &project::Event::WorktreeAdded(id) => {
1342 this.update_window_title(window, cx);
1343 if this
1344 .project()
1345 .read(cx)
1346 .worktree_for_id(id, cx)
1347 .is_some_and(|wt| wt.read(cx).is_visible())
1348 {
1349 this.serialize_workspace(window, cx);
1350 this.update_history(cx);
1351 }
1352 }
1353 project::Event::WorktreeUpdatedEntries(..) => {
1354 this.update_window_title(window, cx);
1355 this.serialize_workspace(window, cx);
1356 }
1357
1358 project::Event::DisconnectedFromHost => {
1359 this.update_window_edited(window, cx);
1360 let leaders_to_unfollow =
1361 this.follower_states.keys().copied().collect::<Vec<_>>();
1362 for leader_id in leaders_to_unfollow {
1363 this.unfollow(leader_id, window, cx);
1364 }
1365 }
1366
1367 project::Event::DisconnectedFromRemote {
1368 server_not_running: _,
1369 } => {
1370 this.update_window_edited(window, cx);
1371 }
1372
1373 project::Event::Closed => {
1374 window.remove_window();
1375 }
1376
1377 project::Event::DeletedEntry(_, entry_id) => {
1378 for pane in this.panes.iter() {
1379 pane.update(cx, |pane, cx| {
1380 pane.handle_deleted_project_item(*entry_id, window, cx)
1381 });
1382 }
1383 }
1384
1385 project::Event::Toast {
1386 notification_id,
1387 message,
1388 link,
1389 } => this.show_notification(
1390 NotificationId::named(notification_id.clone()),
1391 cx,
1392 |cx| {
1393 let mut notification = MessageNotification::new(message.clone(), cx);
1394 if let Some(link) = link {
1395 notification = notification
1396 .more_info_message(link.label)
1397 .more_info_url(link.url);
1398 }
1399
1400 cx.new(|_| notification)
1401 },
1402 ),
1403
1404 project::Event::HideToast { notification_id } => {
1405 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1406 }
1407
1408 project::Event::LanguageServerPrompt(request) => {
1409 struct LanguageServerPrompt;
1410
1411 this.show_notification(
1412 NotificationId::composite::<LanguageServerPrompt>(request.id),
1413 cx,
1414 |cx| {
1415 cx.new(|cx| {
1416 notifications::LanguageServerPrompt::new(request.clone(), cx)
1417 })
1418 },
1419 );
1420 }
1421
1422 project::Event::AgentLocationChanged => {
1423 this.handle_agent_location_changed(window, cx)
1424 }
1425
1426 _ => {}
1427 }
1428 cx.notify()
1429 })
1430 .detach();
1431
1432 cx.subscribe_in(
1433 &project.read(cx).breakpoint_store(),
1434 window,
1435 |workspace, _, event, window, cx| match event {
1436 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1437 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1438 workspace.serialize_workspace(window, cx);
1439 }
1440 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1441 },
1442 )
1443 .detach();
1444 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1445 cx.subscribe_in(
1446 &toolchain_store,
1447 window,
1448 |workspace, _, event, window, cx| match event {
1449 ToolchainStoreEvent::CustomToolchainsModified => {
1450 workspace.serialize_workspace(window, cx);
1451 }
1452 _ => {}
1453 },
1454 )
1455 .detach();
1456 }
1457
1458 cx.on_focus_lost(window, |this, window, cx| {
1459 let focus_handle = this.focus_handle(cx);
1460 window.focus(&focus_handle, cx);
1461 })
1462 .detach();
1463
1464 let weak_handle = cx.entity().downgrade();
1465 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1466
1467 let center_pane = cx.new(|cx| {
1468 let mut center_pane = Pane::new(
1469 weak_handle.clone(),
1470 project.clone(),
1471 pane_history_timestamp.clone(),
1472 None,
1473 NewFile.boxed_clone(),
1474 true,
1475 window,
1476 cx,
1477 );
1478 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1479 center_pane.set_should_display_welcome_page(true);
1480 center_pane
1481 });
1482 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1483 .detach();
1484
1485 window.focus(¢er_pane.focus_handle(cx), cx);
1486
1487 cx.emit(Event::PaneAdded(center_pane.clone()));
1488
1489 let any_window_handle = window.window_handle();
1490 app_state.workspace_store.update(cx, |store, _| {
1491 store
1492 .workspaces
1493 .insert((any_window_handle, weak_handle.clone()));
1494 });
1495
1496 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1497 let mut connection_status = app_state.client.status();
1498 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1499 current_user.next().await;
1500 connection_status.next().await;
1501 let mut stream =
1502 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1503
1504 while stream.recv().await.is_some() {
1505 this.update(cx, |_, cx| cx.notify())?;
1506 }
1507 anyhow::Ok(())
1508 });
1509
1510 // All leader updates are enqueued and then processed in a single task, so
1511 // that each asynchronous operation can be run in order.
1512 let (leader_updates_tx, mut leader_updates_rx) =
1513 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1514 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1515 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1516 Self::process_leader_update(&this, leader_id, update, cx)
1517 .await
1518 .log_err();
1519 }
1520
1521 Ok(())
1522 });
1523
1524 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1525 let modal_layer = cx.new(|_| ModalLayer::new());
1526 let toast_layer = cx.new(|_| ToastLayer::new());
1527 cx.subscribe(
1528 &modal_layer,
1529 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1530 cx.emit(Event::ModalOpened);
1531 },
1532 )
1533 .detach();
1534
1535 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1536 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1537 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1538 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1539 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1540 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1541 let status_bar = cx.new(|cx| {
1542 let mut status_bar = StatusBar::new(¢er_pane.clone(), window, cx);
1543 status_bar.add_left_item(left_dock_buttons, window, cx);
1544 status_bar.add_right_item(right_dock_buttons, window, cx);
1545 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1546 status_bar
1547 });
1548
1549 let session_id = app_state.session.read(cx).id().to_owned();
1550
1551 let mut active_call = None;
1552 if let Some(call) = ActiveCall::try_global(cx) {
1553 let subscriptions = vec![cx.subscribe_in(&call, window, Self::on_active_call_event)];
1554 active_call = Some((call, subscriptions));
1555 }
1556
1557 let (serializable_items_tx, serializable_items_rx) =
1558 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1559 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1560 Self::serialize_items(&this, serializable_items_rx, cx).await
1561 });
1562
1563 let subscriptions = vec![
1564 cx.observe_window_activation(window, Self::on_window_activation_changed),
1565 cx.observe_window_bounds(window, move |this, window, cx| {
1566 if this.bounds_save_task_queued.is_some() {
1567 return;
1568 }
1569 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1570 cx.background_executor()
1571 .timer(Duration::from_millis(100))
1572 .await;
1573 this.update_in(cx, |this, window, cx| {
1574 if let Some(display) = window.display(cx)
1575 && let Ok(display_uuid) = display.uuid()
1576 {
1577 let window_bounds = window.inner_window_bounds();
1578 let has_paths = !this.root_paths(cx).is_empty();
1579 if !has_paths {
1580 cx.background_executor()
1581 .spawn(persistence::write_default_window_bounds(
1582 window_bounds,
1583 display_uuid,
1584 ))
1585 .detach_and_log_err(cx);
1586 }
1587 if let Some(database_id) = workspace_id {
1588 cx.background_executor()
1589 .spawn(DB.set_window_open_status(
1590 database_id,
1591 SerializedWindowBounds(window_bounds),
1592 display_uuid,
1593 ))
1594 .detach_and_log_err(cx);
1595 } else {
1596 cx.background_executor()
1597 .spawn(persistence::write_default_window_bounds(
1598 window_bounds,
1599 display_uuid,
1600 ))
1601 .detach_and_log_err(cx);
1602 }
1603 }
1604 this.bounds_save_task_queued.take();
1605 })
1606 .ok();
1607 }));
1608 cx.notify();
1609 }),
1610 cx.observe_window_appearance(window, |_, window, cx| {
1611 let window_appearance = window.appearance();
1612
1613 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1614
1615 GlobalTheme::reload_theme(cx);
1616 GlobalTheme::reload_icon_theme(cx);
1617 }),
1618 cx.on_release({
1619 let weak_handle = weak_handle.clone();
1620 move |this, cx| {
1621 this.app_state.workspace_store.update(cx, move |store, _| {
1622 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1623 })
1624 }
1625 }),
1626 ];
1627
1628 cx.defer_in(window, move |this, window, cx| {
1629 this.update_window_title(window, cx);
1630 this.show_initial_notifications(cx);
1631 });
1632
1633 let mut center = PaneGroup::new(center_pane.clone());
1634 center.set_is_center(true);
1635 center.mark_positions(cx);
1636
1637 Workspace {
1638 weak_self: weak_handle.clone(),
1639 zoomed: None,
1640 zoomed_position: None,
1641 previous_dock_drag_coordinates: None,
1642 center,
1643 panes: vec![center_pane.clone()],
1644 panes_by_item: Default::default(),
1645 active_pane: center_pane.clone(),
1646 last_active_center_pane: Some(center_pane.downgrade()),
1647 last_active_view_id: None,
1648 status_bar,
1649 modal_layer,
1650 toast_layer,
1651 titlebar_item: None,
1652 active_worktree_override: None,
1653 notifications: Notifications::default(),
1654 suppressed_notifications: HashSet::default(),
1655 left_dock,
1656 bottom_dock,
1657 right_dock,
1658 project: project.clone(),
1659 follower_states: Default::default(),
1660 last_leaders_by_pane: Default::default(),
1661 dispatching_keystrokes: Default::default(),
1662 window_edited: false,
1663 last_window_title: None,
1664 dirty_items: Default::default(),
1665 active_call,
1666 database_id: workspace_id,
1667 app_state,
1668 _observe_current_user,
1669 _apply_leader_updates,
1670 _schedule_serialize_workspace: None,
1671 _serialize_workspace_task: None,
1672 _schedule_serialize_ssh_paths: None,
1673 leader_updates_tx,
1674 _subscriptions: subscriptions,
1675 pane_history_timestamp,
1676 workspace_actions: Default::default(),
1677 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1678 bounds: Default::default(),
1679 centered_layout: false,
1680 bounds_save_task_queued: None,
1681 on_prompt_for_new_path: None,
1682 on_prompt_for_open_path: None,
1683 terminal_provider: None,
1684 debugger_provider: None,
1685 serializable_items_tx,
1686 _items_serializer,
1687 session_id: Some(session_id),
1688
1689 scheduled_tasks: Vec::new(),
1690 last_open_dock_positions: Vec::new(),
1691 removing: false,
1692 }
1693 }
1694
1695 pub fn new_local(
1696 abs_paths: Vec<PathBuf>,
1697 app_state: Arc<AppState>,
1698 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1699 env: Option<HashMap<String, String>>,
1700 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1701 cx: &mut App,
1702 ) -> Task<
1703 anyhow::Result<(
1704 WindowHandle<MultiWorkspace>,
1705 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
1706 )>,
1707 > {
1708 let project_handle = Project::local(
1709 app_state.client.clone(),
1710 app_state.node_runtime.clone(),
1711 app_state.user_store.clone(),
1712 app_state.languages.clone(),
1713 app_state.fs.clone(),
1714 env,
1715 Default::default(),
1716 cx,
1717 );
1718
1719 cx.spawn(async move |cx| {
1720 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1721 for path in abs_paths.into_iter() {
1722 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1723 paths_to_open.push(canonical)
1724 } else {
1725 paths_to_open.push(path)
1726 }
1727 }
1728
1729 let serialized_workspace =
1730 persistence::DB.workspace_for_roots(paths_to_open.as_slice());
1731
1732 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1733 paths_to_open = paths.ordered_paths().cloned().collect();
1734 if !paths.is_lexicographically_ordered() {
1735 project_handle.update(cx, |project, cx| {
1736 project.set_worktrees_reordered(true, cx);
1737 });
1738 }
1739 }
1740
1741 // Get project paths for all of the abs_paths
1742 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1743 Vec::with_capacity(paths_to_open.len());
1744
1745 for path in paths_to_open.into_iter() {
1746 if let Some((_, project_entry)) = cx
1747 .update(|cx| {
1748 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1749 })
1750 .await
1751 .log_err()
1752 {
1753 project_paths.push((path, Some(project_entry)));
1754 } else {
1755 project_paths.push((path, None));
1756 }
1757 }
1758
1759 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1760 serialized_workspace.id
1761 } else {
1762 DB.next_id().await.unwrap_or_else(|_| Default::default())
1763 };
1764
1765 let toolchains = DB.toolchains(workspace_id).await?;
1766
1767 for (toolchain, worktree_path, path) in toolchains {
1768 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1769 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1770 this.find_worktree(&worktree_path, cx)
1771 .and_then(|(worktree, rel_path)| {
1772 if rel_path.is_empty() {
1773 Some(worktree.read(cx).id())
1774 } else {
1775 None
1776 }
1777 })
1778 }) else {
1779 // We did not find a worktree with a given path, but that's whatever.
1780 continue;
1781 };
1782 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1783 continue;
1784 }
1785
1786 project_handle
1787 .update(cx, |this, cx| {
1788 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1789 })
1790 .await;
1791 }
1792 if let Some(workspace) = serialized_workspace.as_ref() {
1793 project_handle.update(cx, |this, cx| {
1794 for (scope, toolchains) in &workspace.user_toolchains {
1795 for toolchain in toolchains {
1796 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1797 }
1798 }
1799 });
1800 }
1801
1802 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1803 if let Some(window) = requesting_window {
1804 let centered_layout = serialized_workspace
1805 .as_ref()
1806 .map(|w| w.centered_layout)
1807 .unwrap_or(false);
1808
1809 let workspace = window.update(cx, |multi_workspace, window, cx| {
1810 let workspace = cx.new(|cx| {
1811 let mut workspace = Workspace::new(
1812 Some(workspace_id),
1813 project_handle.clone(),
1814 app_state.clone(),
1815 window,
1816 cx,
1817 );
1818
1819 workspace.centered_layout = centered_layout;
1820
1821 // Call init callback to add items before window renders
1822 if let Some(init) = init {
1823 init(&mut workspace, window, cx);
1824 }
1825
1826 workspace
1827 });
1828 multi_workspace.activate(workspace.clone(), cx);
1829 workspace
1830 })?;
1831 (window, workspace)
1832 } else {
1833 let window_bounds_override = window_bounds_env_override();
1834
1835 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1836 (Some(WindowBounds::Windowed(bounds)), None)
1837 } else if let Some(workspace) = serialized_workspace.as_ref()
1838 && let Some(display) = workspace.display
1839 && let Some(bounds) = workspace.window_bounds.as_ref()
1840 {
1841 // Reopening an existing workspace - restore its saved bounds
1842 (Some(bounds.0), Some(display))
1843 } else if let Some((display, bounds)) =
1844 persistence::read_default_window_bounds()
1845 {
1846 // New or empty workspace - use the last known window bounds
1847 (Some(bounds), Some(display))
1848 } else {
1849 // New window - let GPUI's default_bounds() handle cascading
1850 (None, None)
1851 };
1852
1853 // Use the serialized workspace to construct the new window
1854 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1855 options.window_bounds = window_bounds;
1856 let centered_layout = serialized_workspace
1857 .as_ref()
1858 .map(|w| w.centered_layout)
1859 .unwrap_or(false);
1860 let window = cx.open_window(options, {
1861 let app_state = app_state.clone();
1862 let project_handle = project_handle.clone();
1863 move |window, cx| {
1864 let workspace = cx.new(|cx| {
1865 let mut workspace = Workspace::new(
1866 Some(workspace_id),
1867 project_handle,
1868 app_state,
1869 window,
1870 cx,
1871 );
1872 workspace.centered_layout = centered_layout;
1873
1874 // Call init callback to add items before window renders
1875 if let Some(init) = init {
1876 init(&mut workspace, window, cx);
1877 }
1878
1879 workspace
1880 });
1881 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1882 }
1883 })?;
1884 let workspace =
1885 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
1886 multi_workspace.workspace().clone()
1887 })?;
1888 (window, workspace)
1889 };
1890
1891 notify_if_database_failed(window, cx);
1892 // Check if this is an empty workspace (no paths to open)
1893 // An empty workspace is one where project_paths is empty
1894 let is_empty_workspace = project_paths.is_empty();
1895 // Check if serialized workspace has paths before it's moved
1896 let serialized_workspace_has_paths = serialized_workspace
1897 .as_ref()
1898 .map(|ws| !ws.paths.is_empty())
1899 .unwrap_or(false);
1900
1901 let opened_items = window
1902 .update(cx, |_, window, cx| {
1903 workspace.update(cx, |_workspace: &mut Workspace, cx| {
1904 open_items(serialized_workspace, project_paths, window, cx)
1905 })
1906 })?
1907 .await
1908 .unwrap_or_default();
1909
1910 // Restore default dock state for empty workspaces
1911 // Only restore if:
1912 // 1. This is an empty workspace (no paths), AND
1913 // 2. The serialized workspace either doesn't exist or has no paths
1914 if is_empty_workspace && !serialized_workspace_has_paths {
1915 if let Some(default_docks) = persistence::read_default_dock_state() {
1916 window
1917 .update(cx, |_, window, cx| {
1918 workspace.update(cx, |workspace, cx| {
1919 for (dock, serialized_dock) in [
1920 (&workspace.right_dock, &default_docks.right),
1921 (&workspace.left_dock, &default_docks.left),
1922 (&workspace.bottom_dock, &default_docks.bottom),
1923 ] {
1924 dock.update(cx, |dock, cx| {
1925 dock.serialized_dock = Some(serialized_dock.clone());
1926 dock.restore_state(window, cx);
1927 });
1928 }
1929 cx.notify();
1930 });
1931 })
1932 .log_err();
1933 }
1934 }
1935
1936 window
1937 .update(cx, |_, _window, cx| {
1938 workspace.update(cx, |this: &mut Workspace, cx| {
1939 this.update_history(cx);
1940 });
1941 })
1942 .log_err();
1943 Ok((window, opened_items))
1944 })
1945 }
1946
1947 pub fn weak_handle(&self) -> WeakEntity<Self> {
1948 self.weak_self.clone()
1949 }
1950
1951 pub fn left_dock(&self) -> &Entity<Dock> {
1952 &self.left_dock
1953 }
1954
1955 pub fn bottom_dock(&self) -> &Entity<Dock> {
1956 &self.bottom_dock
1957 }
1958
1959 pub fn set_bottom_dock_layout(
1960 &mut self,
1961 layout: BottomDockLayout,
1962 window: &mut Window,
1963 cx: &mut Context<Self>,
1964 ) {
1965 let fs = self.project().read(cx).fs();
1966 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
1967 content.workspace.bottom_dock_layout = Some(layout);
1968 });
1969
1970 cx.notify();
1971 self.serialize_workspace(window, cx);
1972 }
1973
1974 pub fn right_dock(&self) -> &Entity<Dock> {
1975 &self.right_dock
1976 }
1977
1978 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
1979 [&self.left_dock, &self.bottom_dock, &self.right_dock]
1980 }
1981
1982 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
1983 match position {
1984 DockPosition::Left => &self.left_dock,
1985 DockPosition::Bottom => &self.bottom_dock,
1986 DockPosition::Right => &self.right_dock,
1987 }
1988 }
1989
1990 pub fn is_edited(&self) -> bool {
1991 self.window_edited
1992 }
1993
1994 pub fn add_panel<T: Panel>(
1995 &mut self,
1996 panel: Entity<T>,
1997 window: &mut Window,
1998 cx: &mut Context<Self>,
1999 ) {
2000 let focus_handle = panel.panel_focus_handle(cx);
2001 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2002 .detach();
2003
2004 let dock_position = panel.position(window, cx);
2005 let dock = self.dock_at_position(dock_position);
2006
2007 dock.update(cx, |dock, cx| {
2008 dock.add_panel(panel, self.weak_self.clone(), window, cx)
2009 });
2010 }
2011
2012 pub fn remove_panel<T: Panel>(
2013 &mut self,
2014 panel: &Entity<T>,
2015 window: &mut Window,
2016 cx: &mut Context<Self>,
2017 ) {
2018 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2019 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2020 }
2021 }
2022
2023 pub fn status_bar(&self) -> &Entity<StatusBar> {
2024 &self.status_bar
2025 }
2026
2027 pub fn set_workspace_sidebar_open(&self, open: bool, cx: &mut App) {
2028 self.status_bar.update(cx, |status_bar, cx| {
2029 status_bar.set_workspace_sidebar_open(open, cx);
2030 });
2031 }
2032
2033 pub fn status_bar_visible(&self, cx: &App) -> bool {
2034 StatusBarSettings::get_global(cx).show
2035 }
2036
2037 pub fn app_state(&self) -> &Arc<AppState> {
2038 &self.app_state
2039 }
2040
2041 pub fn user_store(&self) -> &Entity<UserStore> {
2042 &self.app_state.user_store
2043 }
2044
2045 pub fn project(&self) -> &Entity<Project> {
2046 &self.project
2047 }
2048
2049 pub fn path_style(&self, cx: &App) -> PathStyle {
2050 self.project.read(cx).path_style(cx)
2051 }
2052
2053 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2054 let mut history: HashMap<EntityId, usize> = HashMap::default();
2055
2056 for pane_handle in &self.panes {
2057 let pane = pane_handle.read(cx);
2058
2059 for entry in pane.activation_history() {
2060 history.insert(
2061 entry.entity_id,
2062 history
2063 .get(&entry.entity_id)
2064 .cloned()
2065 .unwrap_or(0)
2066 .max(entry.timestamp),
2067 );
2068 }
2069 }
2070
2071 history
2072 }
2073
2074 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2075 let mut recent_item: Option<Entity<T>> = None;
2076 let mut recent_timestamp = 0;
2077 for pane_handle in &self.panes {
2078 let pane = pane_handle.read(cx);
2079 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2080 pane.items().map(|item| (item.item_id(), item)).collect();
2081 for entry in pane.activation_history() {
2082 if entry.timestamp > recent_timestamp
2083 && let Some(&item) = item_map.get(&entry.entity_id)
2084 && let Some(typed_item) = item.act_as::<T>(cx)
2085 {
2086 recent_timestamp = entry.timestamp;
2087 recent_item = Some(typed_item);
2088 }
2089 }
2090 }
2091 recent_item
2092 }
2093
2094 pub fn recent_navigation_history_iter(
2095 &self,
2096 cx: &App,
2097 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2098 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2099 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2100
2101 for pane in &self.panes {
2102 let pane = pane.read(cx);
2103
2104 pane.nav_history()
2105 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2106 if let Some(fs_path) = &fs_path {
2107 abs_paths_opened
2108 .entry(fs_path.clone())
2109 .or_default()
2110 .insert(project_path.clone());
2111 }
2112 let timestamp = entry.timestamp;
2113 match history.entry(project_path) {
2114 hash_map::Entry::Occupied(mut entry) => {
2115 let (_, old_timestamp) = entry.get();
2116 if ×tamp > old_timestamp {
2117 entry.insert((fs_path, timestamp));
2118 }
2119 }
2120 hash_map::Entry::Vacant(entry) => {
2121 entry.insert((fs_path, timestamp));
2122 }
2123 }
2124 });
2125
2126 if let Some(item) = pane.active_item()
2127 && let Some(project_path) = item.project_path(cx)
2128 {
2129 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2130
2131 if let Some(fs_path) = &fs_path {
2132 abs_paths_opened
2133 .entry(fs_path.clone())
2134 .or_default()
2135 .insert(project_path.clone());
2136 }
2137
2138 history.insert(project_path, (fs_path, std::usize::MAX));
2139 }
2140 }
2141
2142 history
2143 .into_iter()
2144 .sorted_by_key(|(_, (_, order))| *order)
2145 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2146 .rev()
2147 .filter(move |(history_path, abs_path)| {
2148 let latest_project_path_opened = abs_path
2149 .as_ref()
2150 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2151 .and_then(|project_paths| {
2152 project_paths
2153 .iter()
2154 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2155 });
2156
2157 latest_project_path_opened.is_none_or(|path| path == history_path)
2158 })
2159 }
2160
2161 pub fn recent_navigation_history(
2162 &self,
2163 limit: Option<usize>,
2164 cx: &App,
2165 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2166 self.recent_navigation_history_iter(cx)
2167 .take(limit.unwrap_or(usize::MAX))
2168 .collect()
2169 }
2170
2171 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2172 for pane in &self.panes {
2173 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2174 }
2175 }
2176
2177 fn navigate_history(
2178 &mut self,
2179 pane: WeakEntity<Pane>,
2180 mode: NavigationMode,
2181 window: &mut Window,
2182 cx: &mut Context<Workspace>,
2183 ) -> Task<Result<()>> {
2184 self.navigate_history_impl(
2185 pane,
2186 mode,
2187 window,
2188 &mut |history, cx| history.pop(mode, cx),
2189 cx,
2190 )
2191 }
2192
2193 fn navigate_tag_history(
2194 &mut self,
2195 pane: WeakEntity<Pane>,
2196 mode: TagNavigationMode,
2197 window: &mut Window,
2198 cx: &mut Context<Workspace>,
2199 ) -> Task<Result<()>> {
2200 self.navigate_history_impl(
2201 pane,
2202 NavigationMode::Normal,
2203 window,
2204 &mut |history, _cx| history.pop_tag(mode),
2205 cx,
2206 )
2207 }
2208
2209 fn navigate_history_impl(
2210 &mut self,
2211 pane: WeakEntity<Pane>,
2212 mode: NavigationMode,
2213 window: &mut Window,
2214 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2215 cx: &mut Context<Workspace>,
2216 ) -> Task<Result<()>> {
2217 let to_load = if let Some(pane) = pane.upgrade() {
2218 pane.update(cx, |pane, cx| {
2219 window.focus(&pane.focus_handle(cx), cx);
2220 loop {
2221 // Retrieve the weak item handle from the history.
2222 let entry = cb(pane.nav_history_mut(), cx)?;
2223
2224 // If the item is still present in this pane, then activate it.
2225 if let Some(index) = entry
2226 .item
2227 .upgrade()
2228 .and_then(|v| pane.index_for_item(v.as_ref()))
2229 {
2230 let prev_active_item_index = pane.active_item_index();
2231 pane.nav_history_mut().set_mode(mode);
2232 pane.activate_item(index, true, true, window, cx);
2233 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2234
2235 let mut navigated = prev_active_item_index != pane.active_item_index();
2236 if let Some(data) = entry.data {
2237 navigated |= pane.active_item()?.navigate(data, window, cx);
2238 }
2239
2240 if navigated {
2241 break None;
2242 }
2243 } else {
2244 // If the item is no longer present in this pane, then retrieve its
2245 // path info in order to reopen it.
2246 break pane
2247 .nav_history()
2248 .path_for_item(entry.item.id())
2249 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2250 }
2251 }
2252 })
2253 } else {
2254 None
2255 };
2256
2257 if let Some((project_path, abs_path, entry)) = to_load {
2258 // If the item was no longer present, then load it again from its previous path, first try the local path
2259 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2260
2261 cx.spawn_in(window, async move |workspace, cx| {
2262 let open_by_project_path = open_by_project_path.await;
2263 let mut navigated = false;
2264 match open_by_project_path
2265 .with_context(|| format!("Navigating to {project_path:?}"))
2266 {
2267 Ok((project_entry_id, build_item)) => {
2268 let prev_active_item_id = pane.update(cx, |pane, _| {
2269 pane.nav_history_mut().set_mode(mode);
2270 pane.active_item().map(|p| p.item_id())
2271 })?;
2272
2273 pane.update_in(cx, |pane, window, cx| {
2274 let item = pane.open_item(
2275 project_entry_id,
2276 project_path,
2277 true,
2278 entry.is_preview,
2279 true,
2280 None,
2281 window, cx,
2282 build_item,
2283 );
2284 navigated |= Some(item.item_id()) != prev_active_item_id;
2285 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2286 if let Some(data) = entry.data {
2287 navigated |= item.navigate(data, window, cx);
2288 }
2289 })?;
2290 }
2291 Err(open_by_project_path_e) => {
2292 // Fall back to opening by abs path, in case an external file was opened and closed,
2293 // and its worktree is now dropped
2294 if let Some(abs_path) = abs_path {
2295 let prev_active_item_id = pane.update(cx, |pane, _| {
2296 pane.nav_history_mut().set_mode(mode);
2297 pane.active_item().map(|p| p.item_id())
2298 })?;
2299 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2300 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2301 })?;
2302 match open_by_abs_path
2303 .await
2304 .with_context(|| format!("Navigating to {abs_path:?}"))
2305 {
2306 Ok(item) => {
2307 pane.update_in(cx, |pane, window, cx| {
2308 navigated |= Some(item.item_id()) != prev_active_item_id;
2309 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2310 if let Some(data) = entry.data {
2311 navigated |= item.navigate(data, window, cx);
2312 }
2313 })?;
2314 }
2315 Err(open_by_abs_path_e) => {
2316 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2317 }
2318 }
2319 }
2320 }
2321 }
2322
2323 if !navigated {
2324 workspace
2325 .update_in(cx, |workspace, window, cx| {
2326 Self::navigate_history(workspace, pane, mode, window, cx)
2327 })?
2328 .await?;
2329 }
2330
2331 Ok(())
2332 })
2333 } else {
2334 Task::ready(Ok(()))
2335 }
2336 }
2337
2338 pub fn go_back(
2339 &mut self,
2340 pane: WeakEntity<Pane>,
2341 window: &mut Window,
2342 cx: &mut Context<Workspace>,
2343 ) -> Task<Result<()>> {
2344 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2345 }
2346
2347 pub fn go_forward(
2348 &mut self,
2349 pane: WeakEntity<Pane>,
2350 window: &mut Window,
2351 cx: &mut Context<Workspace>,
2352 ) -> Task<Result<()>> {
2353 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2354 }
2355
2356 pub fn reopen_closed_item(
2357 &mut self,
2358 window: &mut Window,
2359 cx: &mut Context<Workspace>,
2360 ) -> Task<Result<()>> {
2361 self.navigate_history(
2362 self.active_pane().downgrade(),
2363 NavigationMode::ReopeningClosedItem,
2364 window,
2365 cx,
2366 )
2367 }
2368
2369 pub fn client(&self) -> &Arc<Client> {
2370 &self.app_state.client
2371 }
2372
2373 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2374 self.titlebar_item = Some(item);
2375 cx.notify();
2376 }
2377
2378 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2379 self.on_prompt_for_new_path = Some(prompt)
2380 }
2381
2382 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2383 self.on_prompt_for_open_path = Some(prompt)
2384 }
2385
2386 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2387 self.terminal_provider = Some(Box::new(provider));
2388 }
2389
2390 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2391 self.debugger_provider = Some(Arc::new(provider));
2392 }
2393
2394 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2395 self.debugger_provider.clone()
2396 }
2397
2398 pub fn prompt_for_open_path(
2399 &mut self,
2400 path_prompt_options: PathPromptOptions,
2401 lister: DirectoryLister,
2402 window: &mut Window,
2403 cx: &mut Context<Self>,
2404 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2405 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2406 let prompt = self.on_prompt_for_open_path.take().unwrap();
2407 let rx = prompt(self, lister, window, cx);
2408 self.on_prompt_for_open_path = Some(prompt);
2409 rx
2410 } else {
2411 let (tx, rx) = oneshot::channel();
2412 let abs_path = cx.prompt_for_paths(path_prompt_options);
2413
2414 cx.spawn_in(window, async move |workspace, cx| {
2415 let Ok(result) = abs_path.await else {
2416 return Ok(());
2417 };
2418
2419 match result {
2420 Ok(result) => {
2421 tx.send(result).ok();
2422 }
2423 Err(err) => {
2424 let rx = workspace.update_in(cx, |workspace, window, cx| {
2425 workspace.show_portal_error(err.to_string(), cx);
2426 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2427 let rx = prompt(workspace, lister, window, cx);
2428 workspace.on_prompt_for_open_path = Some(prompt);
2429 rx
2430 })?;
2431 if let Ok(path) = rx.await {
2432 tx.send(path).ok();
2433 }
2434 }
2435 };
2436 anyhow::Ok(())
2437 })
2438 .detach();
2439
2440 rx
2441 }
2442 }
2443
2444 pub fn prompt_for_new_path(
2445 &mut self,
2446 lister: DirectoryLister,
2447 suggested_name: Option<String>,
2448 window: &mut Window,
2449 cx: &mut Context<Self>,
2450 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2451 if self.project.read(cx).is_via_collab()
2452 || self.project.read(cx).is_via_remote_server()
2453 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2454 {
2455 let prompt = self.on_prompt_for_new_path.take().unwrap();
2456 let rx = prompt(self, lister, suggested_name, window, cx);
2457 self.on_prompt_for_new_path = Some(prompt);
2458 return rx;
2459 }
2460
2461 let (tx, rx) = oneshot::channel();
2462 cx.spawn_in(window, async move |workspace, cx| {
2463 let abs_path = workspace.update(cx, |workspace, cx| {
2464 let relative_to = workspace
2465 .most_recent_active_path(cx)
2466 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2467 .or_else(|| {
2468 let project = workspace.project.read(cx);
2469 project.visible_worktrees(cx).find_map(|worktree| {
2470 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2471 })
2472 })
2473 .or_else(std::env::home_dir)
2474 .unwrap_or_else(|| PathBuf::from(""));
2475 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2476 })?;
2477 let abs_path = match abs_path.await? {
2478 Ok(path) => path,
2479 Err(err) => {
2480 let rx = workspace.update_in(cx, |workspace, window, cx| {
2481 workspace.show_portal_error(err.to_string(), cx);
2482
2483 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2484 let rx = prompt(workspace, lister, suggested_name, window, cx);
2485 workspace.on_prompt_for_new_path = Some(prompt);
2486 rx
2487 })?;
2488 if let Ok(path) = rx.await {
2489 tx.send(path).ok();
2490 }
2491 return anyhow::Ok(());
2492 }
2493 };
2494
2495 tx.send(abs_path.map(|path| vec![path])).ok();
2496 anyhow::Ok(())
2497 })
2498 .detach();
2499
2500 rx
2501 }
2502
2503 pub fn titlebar_item(&self) -> Option<AnyView> {
2504 self.titlebar_item.clone()
2505 }
2506
2507 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2508 /// When set, git-related operations should use this worktree instead of deriving
2509 /// the active worktree from the focused file.
2510 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2511 self.active_worktree_override
2512 }
2513
2514 pub fn set_active_worktree_override(
2515 &mut self,
2516 worktree_id: Option<WorktreeId>,
2517 cx: &mut Context<Self>,
2518 ) {
2519 self.active_worktree_override = worktree_id;
2520 cx.notify();
2521 }
2522
2523 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2524 self.active_worktree_override = None;
2525 cx.notify();
2526 }
2527
2528 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2529 ///
2530 /// If the given workspace has a local project, then it will be passed
2531 /// to the callback. Otherwise, a new empty window will be created.
2532 pub fn with_local_workspace<T, F>(
2533 &mut self,
2534 window: &mut Window,
2535 cx: &mut Context<Self>,
2536 callback: F,
2537 ) -> Task<Result<T>>
2538 where
2539 T: 'static,
2540 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2541 {
2542 if self.project.read(cx).is_local() {
2543 Task::ready(Ok(callback(self, window, cx)))
2544 } else {
2545 let env = self.project.read(cx).cli_environment(cx);
2546 let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, None, cx);
2547 cx.spawn_in(window, async move |_vh, cx| {
2548 let (multi_workspace_window, _) = task.await?;
2549 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2550 let workspace = multi_workspace.workspace().clone();
2551 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2552 })
2553 })
2554 }
2555 }
2556
2557 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2558 ///
2559 /// If the given workspace has a local project, then it will be passed
2560 /// to the callback. Otherwise, a new empty window will be created.
2561 pub fn with_local_or_wsl_workspace<T, F>(
2562 &mut self,
2563 window: &mut Window,
2564 cx: &mut Context<Self>,
2565 callback: F,
2566 ) -> Task<Result<T>>
2567 where
2568 T: 'static,
2569 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2570 {
2571 let project = self.project.read(cx);
2572 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
2573 Task::ready(Ok(callback(self, window, cx)))
2574 } else {
2575 let env = self.project.read(cx).cli_environment(cx);
2576 let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, None, cx);
2577 cx.spawn_in(window, async move |_vh, cx| {
2578 let (multi_workspace_window, _) = task.await?;
2579 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2580 let workspace = multi_workspace.workspace().clone();
2581 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2582 })
2583 })
2584 }
2585 }
2586
2587 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2588 self.project.read(cx).worktrees(cx)
2589 }
2590
2591 pub fn visible_worktrees<'a>(
2592 &self,
2593 cx: &'a App,
2594 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2595 self.project.read(cx).visible_worktrees(cx)
2596 }
2597
2598 #[cfg(any(test, feature = "test-support"))]
2599 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
2600 let futures = self
2601 .worktrees(cx)
2602 .filter_map(|worktree| worktree.read(cx).as_local())
2603 .map(|worktree| worktree.scan_complete())
2604 .collect::<Vec<_>>();
2605 async move {
2606 for future in futures {
2607 future.await;
2608 }
2609 }
2610 }
2611
2612 pub fn close_global(cx: &mut App) {
2613 cx.defer(|cx| {
2614 cx.windows().iter().find(|window| {
2615 window
2616 .update(cx, |_, window, _| {
2617 if window.is_window_active() {
2618 //This can only get called when the window's project connection has been lost
2619 //so we don't need to prompt the user for anything and instead just close the window
2620 window.remove_window();
2621 true
2622 } else {
2623 false
2624 }
2625 })
2626 .unwrap_or(false)
2627 });
2628 });
2629 }
2630
2631 pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
2632 let prepare = self.prepare_to_close(CloseIntent::CloseWindow, window, cx);
2633 cx.spawn_in(window, async move |_, cx| {
2634 if prepare.await? {
2635 cx.update(|window, _cx| window.remove_window())?;
2636 }
2637 anyhow::Ok(())
2638 })
2639 .detach_and_log_err(cx)
2640 }
2641
2642 pub fn move_focused_panel_to_next_position(
2643 &mut self,
2644 _: &MoveFocusedPanelToNextPosition,
2645 window: &mut Window,
2646 cx: &mut Context<Self>,
2647 ) {
2648 let docks = self.all_docks();
2649 let active_dock = docks
2650 .into_iter()
2651 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
2652
2653 if let Some(dock) = active_dock {
2654 dock.update(cx, |dock, cx| {
2655 let active_panel = dock
2656 .active_panel()
2657 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
2658
2659 if let Some(panel) = active_panel {
2660 panel.move_to_next_position(window, cx);
2661 }
2662 })
2663 }
2664 }
2665
2666 pub fn prepare_to_close(
2667 &mut self,
2668 close_intent: CloseIntent,
2669 window: &mut Window,
2670 cx: &mut Context<Self>,
2671 ) -> Task<Result<bool>> {
2672 let active_call = self.active_call().cloned();
2673
2674 cx.spawn_in(window, async move |this, cx| {
2675 this.update(cx, |this, _| {
2676 if close_intent == CloseIntent::CloseWindow {
2677 this.removing = true;
2678 }
2679 })?;
2680
2681 let workspace_count = cx.update(|_window, cx| {
2682 cx.windows()
2683 .iter()
2684 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
2685 .count()
2686 })?;
2687
2688 #[cfg(target_os = "macos")]
2689 let save_last_workspace = false;
2690
2691 // On Linux and Windows, closing the last window should restore the last workspace.
2692 #[cfg(not(target_os = "macos"))]
2693 let save_last_workspace = {
2694 let remaining_workspaces = cx.update(|_window, cx| {
2695 cx.windows()
2696 .iter()
2697 .filter_map(|window| window.downcast::<MultiWorkspace>())
2698 .filter_map(|multi_workspace| {
2699 multi_workspace
2700 .update(cx, |multi_workspace, _, cx| {
2701 multi_workspace.workspace().read(cx).removing
2702 })
2703 .ok()
2704 })
2705 .filter(|removing| !removing)
2706 .count()
2707 })?;
2708
2709 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
2710 };
2711
2712 if let Some(active_call) = active_call
2713 && workspace_count == 1
2714 && active_call.read_with(cx, |call, _| call.room().is_some())
2715 {
2716 if close_intent == CloseIntent::CloseWindow {
2717 let answer = cx.update(|window, cx| {
2718 window.prompt(
2719 PromptLevel::Warning,
2720 "Do you want to leave the current call?",
2721 None,
2722 &["Close window and hang up", "Cancel"],
2723 cx,
2724 )
2725 })?;
2726
2727 if answer.await.log_err() == Some(1) {
2728 return anyhow::Ok(false);
2729 } else {
2730 active_call
2731 .update(cx, |call, cx| call.hang_up(cx))
2732 .await
2733 .log_err();
2734 }
2735 }
2736 if close_intent == CloseIntent::ReplaceWindow {
2737 _ = active_call.update(cx, |this, cx| {
2738 let multi_workspace = cx
2739 .windows()
2740 .iter()
2741 .filter_map(|window| window.downcast::<MultiWorkspace>())
2742 .next()
2743 .unwrap();
2744 let project = multi_workspace
2745 .read(cx)?
2746 .workspace()
2747 .read(cx)
2748 .project
2749 .clone();
2750 if project.read(cx).is_shared() {
2751 this.unshare_project(project, cx)?;
2752 }
2753 Ok::<_, anyhow::Error>(())
2754 })?;
2755 }
2756 }
2757
2758 let save_result = this
2759 .update_in(cx, |this, window, cx| {
2760 this.save_all_internal(SaveIntent::Close, window, cx)
2761 })?
2762 .await;
2763
2764 // If we're not quitting, but closing, we remove the workspace from
2765 // the current session.
2766 if close_intent != CloseIntent::Quit
2767 && !save_last_workspace
2768 && save_result.as_ref().is_ok_and(|&res| res)
2769 {
2770 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
2771 .await;
2772 }
2773
2774 save_result
2775 })
2776 }
2777
2778 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
2779 self.save_all_internal(
2780 action.save_intent.unwrap_or(SaveIntent::SaveAll),
2781 window,
2782 cx,
2783 )
2784 .detach_and_log_err(cx);
2785 }
2786
2787 fn send_keystrokes(
2788 &mut self,
2789 action: &SendKeystrokes,
2790 window: &mut Window,
2791 cx: &mut Context<Self>,
2792 ) {
2793 let keystrokes: Vec<Keystroke> = action
2794 .0
2795 .split(' ')
2796 .flat_map(|k| Keystroke::parse(k).log_err())
2797 .map(|k| {
2798 cx.keyboard_mapper()
2799 .map_key_equivalent(k, false)
2800 .inner()
2801 .clone()
2802 })
2803 .collect();
2804 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
2805 }
2806
2807 pub fn send_keystrokes_impl(
2808 &mut self,
2809 keystrokes: Vec<Keystroke>,
2810 window: &mut Window,
2811 cx: &mut Context<Self>,
2812 ) -> Shared<Task<()>> {
2813 let mut state = self.dispatching_keystrokes.borrow_mut();
2814 if !state.dispatched.insert(keystrokes.clone()) {
2815 cx.propagate();
2816 return state.task.clone().unwrap();
2817 }
2818
2819 state.queue.extend(keystrokes);
2820
2821 let keystrokes = self.dispatching_keystrokes.clone();
2822 if state.task.is_none() {
2823 state.task = Some(
2824 window
2825 .spawn(cx, async move |cx| {
2826 // limit to 100 keystrokes to avoid infinite recursion.
2827 for _ in 0..100 {
2828 let mut state = keystrokes.borrow_mut();
2829 let Some(keystroke) = state.queue.pop_front() else {
2830 state.dispatched.clear();
2831 state.task.take();
2832 return;
2833 };
2834 drop(state);
2835 cx.update(|window, cx| {
2836 let focused = window.focused(cx);
2837 window.dispatch_keystroke(keystroke.clone(), cx);
2838 if window.focused(cx) != focused {
2839 // dispatch_keystroke may cause the focus to change.
2840 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
2841 // And we need that to happen before the next keystroke to keep vim mode happy...
2842 // (Note that the tests always do this implicitly, so you must manually test with something like:
2843 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
2844 // )
2845 window.draw(cx).clear();
2846 }
2847 })
2848 .ok();
2849 }
2850
2851 *keystrokes.borrow_mut() = Default::default();
2852 log::error!("over 100 keystrokes passed to send_keystrokes");
2853 })
2854 .shared(),
2855 );
2856 }
2857 state.task.clone().unwrap()
2858 }
2859
2860 fn save_all_internal(
2861 &mut self,
2862 mut save_intent: SaveIntent,
2863 window: &mut Window,
2864 cx: &mut Context<Self>,
2865 ) -> Task<Result<bool>> {
2866 if self.project.read(cx).is_disconnected(cx) {
2867 return Task::ready(Ok(true));
2868 }
2869 let dirty_items = self
2870 .panes
2871 .iter()
2872 .flat_map(|pane| {
2873 pane.read(cx).items().filter_map(|item| {
2874 if item.is_dirty(cx) {
2875 item.tab_content_text(0, cx);
2876 Some((pane.downgrade(), item.boxed_clone()))
2877 } else {
2878 None
2879 }
2880 })
2881 })
2882 .collect::<Vec<_>>();
2883
2884 let project = self.project.clone();
2885 cx.spawn_in(window, async move |workspace, cx| {
2886 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
2887 let (serialize_tasks, remaining_dirty_items) =
2888 workspace.update_in(cx, |workspace, window, cx| {
2889 let mut remaining_dirty_items = Vec::new();
2890 let mut serialize_tasks = Vec::new();
2891 for (pane, item) in dirty_items {
2892 if let Some(task) = item
2893 .to_serializable_item_handle(cx)
2894 .and_then(|handle| handle.serialize(workspace, true, window, cx))
2895 {
2896 serialize_tasks.push(task);
2897 } else {
2898 remaining_dirty_items.push((pane, item));
2899 }
2900 }
2901 (serialize_tasks, remaining_dirty_items)
2902 })?;
2903
2904 futures::future::try_join_all(serialize_tasks).await?;
2905
2906 if remaining_dirty_items.len() > 1 {
2907 let answer = workspace.update_in(cx, |_, window, cx| {
2908 let detail = Pane::file_names_for_prompt(
2909 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
2910 cx,
2911 );
2912 window.prompt(
2913 PromptLevel::Warning,
2914 "Do you want to save all changes in the following files?",
2915 Some(&detail),
2916 &["Save all", "Discard all", "Cancel"],
2917 cx,
2918 )
2919 })?;
2920 match answer.await.log_err() {
2921 Some(0) => save_intent = SaveIntent::SaveAll,
2922 Some(1) => save_intent = SaveIntent::Skip,
2923 Some(2) => return Ok(false),
2924 _ => {}
2925 }
2926 }
2927
2928 remaining_dirty_items
2929 } else {
2930 dirty_items
2931 };
2932
2933 for (pane, item) in dirty_items {
2934 let (singleton, project_entry_ids) = cx.update(|_, cx| {
2935 (
2936 item.buffer_kind(cx) == ItemBufferKind::Singleton,
2937 item.project_entry_ids(cx),
2938 )
2939 })?;
2940 if (singleton || !project_entry_ids.is_empty())
2941 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
2942 {
2943 return Ok(false);
2944 }
2945 }
2946 Ok(true)
2947 })
2948 }
2949
2950 pub fn open_workspace_for_paths(
2951 &mut self,
2952 replace_current_window: bool,
2953 paths: Vec<PathBuf>,
2954 window: &mut Window,
2955 cx: &mut Context<Self>,
2956 ) -> Task<Result<()>> {
2957 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
2958 let is_remote = self.project.read(cx).is_via_collab();
2959 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
2960 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
2961
2962 let window_to_replace = if replace_current_window {
2963 window_handle
2964 } else if is_remote || has_worktree || has_dirty_items {
2965 None
2966 } else {
2967 window_handle
2968 };
2969 let app_state = self.app_state.clone();
2970
2971 cx.spawn(async move |_, cx| {
2972 cx.update(|cx| {
2973 open_paths(
2974 &paths,
2975 app_state,
2976 OpenOptions {
2977 replace_window: window_to_replace,
2978 ..Default::default()
2979 },
2980 cx,
2981 )
2982 })
2983 .await?;
2984 Ok(())
2985 })
2986 }
2987
2988 #[allow(clippy::type_complexity)]
2989 pub fn open_paths(
2990 &mut self,
2991 mut abs_paths: Vec<PathBuf>,
2992 options: OpenOptions,
2993 pane: Option<WeakEntity<Pane>>,
2994 window: &mut Window,
2995 cx: &mut Context<Self>,
2996 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
2997 let fs = self.app_state.fs.clone();
2998
2999 let caller_ordered_abs_paths = abs_paths.clone();
3000
3001 // Sort the paths to ensure we add worktrees for parents before their children.
3002 abs_paths.sort_unstable();
3003 cx.spawn_in(window, async move |this, cx| {
3004 let mut tasks = Vec::with_capacity(abs_paths.len());
3005
3006 for abs_path in &abs_paths {
3007 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3008 OpenVisible::All => Some(true),
3009 OpenVisible::None => Some(false),
3010 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3011 Some(Some(metadata)) => Some(!metadata.is_dir),
3012 Some(None) => Some(true),
3013 None => None,
3014 },
3015 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3016 Some(Some(metadata)) => Some(metadata.is_dir),
3017 Some(None) => Some(false),
3018 None => None,
3019 },
3020 };
3021 let project_path = match visible {
3022 Some(visible) => match this
3023 .update(cx, |this, cx| {
3024 Workspace::project_path_for_path(
3025 this.project.clone(),
3026 abs_path,
3027 visible,
3028 cx,
3029 )
3030 })
3031 .log_err()
3032 {
3033 Some(project_path) => project_path.await.log_err(),
3034 None => None,
3035 },
3036 None => None,
3037 };
3038
3039 let this = this.clone();
3040 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3041 let fs = fs.clone();
3042 let pane = pane.clone();
3043 let task = cx.spawn(async move |cx| {
3044 let (_worktree, project_path) = project_path?;
3045 if fs.is_dir(&abs_path).await {
3046 // Opening a directory should not race to update the active entry.
3047 // We'll select/reveal a deterministic final entry after all paths finish opening.
3048 None
3049 } else {
3050 Some(
3051 this.update_in(cx, |this, window, cx| {
3052 this.open_path(
3053 project_path,
3054 pane,
3055 options.focus.unwrap_or(true),
3056 window,
3057 cx,
3058 )
3059 })
3060 .ok()?
3061 .await,
3062 )
3063 }
3064 });
3065 tasks.push(task);
3066 }
3067
3068 let results = futures::future::join_all(tasks).await;
3069
3070 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3071 let mut winner: Option<(PathBuf, bool)> = None;
3072 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3073 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3074 if !metadata.is_dir {
3075 winner = Some((abs_path, false));
3076 break;
3077 }
3078 if winner.is_none() {
3079 winner = Some((abs_path, true));
3080 }
3081 } else if winner.is_none() {
3082 winner = Some((abs_path, false));
3083 }
3084 }
3085
3086 // Compute the winner entry id on the foreground thread and emit once, after all
3087 // paths finish opening. This avoids races between concurrently-opening paths
3088 // (directories in particular) and makes the resulting project panel selection
3089 // deterministic.
3090 if let Some((winner_abs_path, winner_is_dir)) = winner {
3091 'emit_winner: {
3092 let winner_abs_path: Arc<Path> =
3093 SanitizedPath::new(&winner_abs_path).as_path().into();
3094
3095 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3096 OpenVisible::All => true,
3097 OpenVisible::None => false,
3098 OpenVisible::OnlyFiles => !winner_is_dir,
3099 OpenVisible::OnlyDirectories => winner_is_dir,
3100 };
3101
3102 let Some(worktree_task) = this
3103 .update(cx, |workspace, cx| {
3104 workspace.project.update(cx, |project, cx| {
3105 project.find_or_create_worktree(
3106 winner_abs_path.as_ref(),
3107 visible,
3108 cx,
3109 )
3110 })
3111 })
3112 .ok()
3113 else {
3114 break 'emit_winner;
3115 };
3116
3117 let Ok((worktree, _)) = worktree_task.await else {
3118 break 'emit_winner;
3119 };
3120
3121 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3122 let worktree = worktree.read(cx);
3123 let worktree_abs_path = worktree.abs_path();
3124 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3125 worktree.root_entry()
3126 } else {
3127 winner_abs_path
3128 .strip_prefix(worktree_abs_path.as_ref())
3129 .ok()
3130 .and_then(|relative_path| {
3131 let relative_path =
3132 RelPath::new(relative_path, PathStyle::local())
3133 .log_err()?;
3134 worktree.entry_for_path(&relative_path)
3135 })
3136 }?;
3137 Some(entry.id)
3138 }) else {
3139 break 'emit_winner;
3140 };
3141
3142 this.update(cx, |workspace, cx| {
3143 workspace.project.update(cx, |_, cx| {
3144 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3145 });
3146 })
3147 .ok();
3148 }
3149 }
3150
3151 results
3152 })
3153 }
3154
3155 pub fn open_resolved_path(
3156 &mut self,
3157 path: ResolvedPath,
3158 window: &mut Window,
3159 cx: &mut Context<Self>,
3160 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3161 match path {
3162 ResolvedPath::ProjectPath { project_path, .. } => {
3163 self.open_path(project_path, None, true, window, cx)
3164 }
3165 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3166 PathBuf::from(path),
3167 OpenOptions {
3168 visible: Some(OpenVisible::None),
3169 ..Default::default()
3170 },
3171 window,
3172 cx,
3173 ),
3174 }
3175 }
3176
3177 pub fn absolute_path_of_worktree(
3178 &self,
3179 worktree_id: WorktreeId,
3180 cx: &mut Context<Self>,
3181 ) -> Option<PathBuf> {
3182 self.project
3183 .read(cx)
3184 .worktree_for_id(worktree_id, cx)
3185 // TODO: use `abs_path` or `root_dir`
3186 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3187 }
3188
3189 fn add_folder_to_project(
3190 &mut self,
3191 _: &AddFolderToProject,
3192 window: &mut Window,
3193 cx: &mut Context<Self>,
3194 ) {
3195 let project = self.project.read(cx);
3196 if project.is_via_collab() {
3197 self.show_error(
3198 &anyhow!("You cannot add folders to someone else's project"),
3199 cx,
3200 );
3201 return;
3202 }
3203 let paths = self.prompt_for_open_path(
3204 PathPromptOptions {
3205 files: false,
3206 directories: true,
3207 multiple: true,
3208 prompt: None,
3209 },
3210 DirectoryLister::Project(self.project.clone()),
3211 window,
3212 cx,
3213 );
3214 cx.spawn_in(window, async move |this, cx| {
3215 if let Some(paths) = paths.await.log_err().flatten() {
3216 let results = this
3217 .update_in(cx, |this, window, cx| {
3218 this.open_paths(
3219 paths,
3220 OpenOptions {
3221 visible: Some(OpenVisible::All),
3222 ..Default::default()
3223 },
3224 None,
3225 window,
3226 cx,
3227 )
3228 })?
3229 .await;
3230 for result in results.into_iter().flatten() {
3231 result.log_err();
3232 }
3233 }
3234 anyhow::Ok(())
3235 })
3236 .detach_and_log_err(cx);
3237 }
3238
3239 pub fn project_path_for_path(
3240 project: Entity<Project>,
3241 abs_path: &Path,
3242 visible: bool,
3243 cx: &mut App,
3244 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3245 let entry = project.update(cx, |project, cx| {
3246 project.find_or_create_worktree(abs_path, visible, cx)
3247 });
3248 cx.spawn(async move |cx| {
3249 let (worktree, path) = entry.await?;
3250 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3251 Ok((worktree, ProjectPath { worktree_id, path }))
3252 })
3253 }
3254
3255 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3256 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3257 }
3258
3259 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3260 self.items_of_type(cx).max_by_key(|item| item.item_id())
3261 }
3262
3263 pub fn items_of_type<'a, T: Item>(
3264 &'a self,
3265 cx: &'a App,
3266 ) -> impl 'a + Iterator<Item = Entity<T>> {
3267 self.panes
3268 .iter()
3269 .flat_map(|pane| pane.read(cx).items_of_type())
3270 }
3271
3272 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3273 self.active_pane().read(cx).active_item()
3274 }
3275
3276 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3277 let item = self.active_item(cx)?;
3278 item.to_any_view().downcast::<I>().ok()
3279 }
3280
3281 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3282 self.active_item(cx).and_then(|item| item.project_path(cx))
3283 }
3284
3285 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3286 self.recent_navigation_history_iter(cx)
3287 .filter_map(|(path, abs_path)| {
3288 let worktree = self
3289 .project
3290 .read(cx)
3291 .worktree_for_id(path.worktree_id, cx)?;
3292 if worktree.read(cx).is_visible() {
3293 abs_path
3294 } else {
3295 None
3296 }
3297 })
3298 .next()
3299 }
3300
3301 pub fn save_active_item(
3302 &mut self,
3303 save_intent: SaveIntent,
3304 window: &mut Window,
3305 cx: &mut App,
3306 ) -> Task<Result<()>> {
3307 let project = self.project.clone();
3308 let pane = self.active_pane();
3309 let item = pane.read(cx).active_item();
3310 let pane = pane.downgrade();
3311
3312 window.spawn(cx, async move |cx| {
3313 if let Some(item) = item {
3314 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3315 .await
3316 .map(|_| ())
3317 } else {
3318 Ok(())
3319 }
3320 })
3321 }
3322
3323 pub fn close_inactive_items_and_panes(
3324 &mut self,
3325 action: &CloseInactiveTabsAndPanes,
3326 window: &mut Window,
3327 cx: &mut Context<Self>,
3328 ) {
3329 if let Some(task) = self.close_all_internal(
3330 true,
3331 action.save_intent.unwrap_or(SaveIntent::Close),
3332 window,
3333 cx,
3334 ) {
3335 task.detach_and_log_err(cx)
3336 }
3337 }
3338
3339 pub fn close_all_items_and_panes(
3340 &mut self,
3341 action: &CloseAllItemsAndPanes,
3342 window: &mut Window,
3343 cx: &mut Context<Self>,
3344 ) {
3345 if let Some(task) = self.close_all_internal(
3346 false,
3347 action.save_intent.unwrap_or(SaveIntent::Close),
3348 window,
3349 cx,
3350 ) {
3351 task.detach_and_log_err(cx)
3352 }
3353 }
3354
3355 /// Closes the active item across all panes.
3356 pub fn close_item_in_all_panes(
3357 &mut self,
3358 action: &CloseItemInAllPanes,
3359 window: &mut Window,
3360 cx: &mut Context<Self>,
3361 ) {
3362 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3363 return;
3364 };
3365
3366 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3367 let close_pinned = action.close_pinned;
3368
3369 if let Some(project_path) = active_item.project_path(cx) {
3370 self.close_items_with_project_path(
3371 &project_path,
3372 save_intent,
3373 close_pinned,
3374 window,
3375 cx,
3376 );
3377 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3378 let item_id = active_item.item_id();
3379 self.active_pane().update(cx, |pane, cx| {
3380 pane.close_item_by_id(item_id, save_intent, window, cx)
3381 .detach_and_log_err(cx);
3382 });
3383 }
3384 }
3385
3386 /// Closes all items with the given project path across all panes.
3387 pub fn close_items_with_project_path(
3388 &mut self,
3389 project_path: &ProjectPath,
3390 save_intent: SaveIntent,
3391 close_pinned: bool,
3392 window: &mut Window,
3393 cx: &mut Context<Self>,
3394 ) {
3395 let panes = self.panes().to_vec();
3396 for pane in panes {
3397 pane.update(cx, |pane, cx| {
3398 pane.close_items_for_project_path(
3399 project_path,
3400 save_intent,
3401 close_pinned,
3402 window,
3403 cx,
3404 )
3405 .detach_and_log_err(cx);
3406 });
3407 }
3408 }
3409
3410 fn close_all_internal(
3411 &mut self,
3412 retain_active_pane: bool,
3413 save_intent: SaveIntent,
3414 window: &mut Window,
3415 cx: &mut Context<Self>,
3416 ) -> Option<Task<Result<()>>> {
3417 let current_pane = self.active_pane();
3418
3419 let mut tasks = Vec::new();
3420
3421 if retain_active_pane {
3422 let current_pane_close = current_pane.update(cx, |pane, cx| {
3423 pane.close_other_items(
3424 &CloseOtherItems {
3425 save_intent: None,
3426 close_pinned: false,
3427 },
3428 None,
3429 window,
3430 cx,
3431 )
3432 });
3433
3434 tasks.push(current_pane_close);
3435 }
3436
3437 for pane in self.panes() {
3438 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3439 continue;
3440 }
3441
3442 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3443 pane.close_all_items(
3444 &CloseAllItems {
3445 save_intent: Some(save_intent),
3446 close_pinned: false,
3447 },
3448 window,
3449 cx,
3450 )
3451 });
3452
3453 tasks.push(close_pane_items)
3454 }
3455
3456 if tasks.is_empty() {
3457 None
3458 } else {
3459 Some(cx.spawn_in(window, async move |_, _| {
3460 for task in tasks {
3461 task.await?
3462 }
3463 Ok(())
3464 }))
3465 }
3466 }
3467
3468 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3469 self.dock_at_position(position).read(cx).is_open()
3470 }
3471
3472 pub fn toggle_dock(
3473 &mut self,
3474 dock_side: DockPosition,
3475 window: &mut Window,
3476 cx: &mut Context<Self>,
3477 ) {
3478 let mut focus_center = false;
3479 let mut reveal_dock = false;
3480
3481 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3482 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3483
3484 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3485 telemetry::event!(
3486 "Panel Button Clicked",
3487 name = panel.persistent_name(),
3488 toggle_state = !was_visible
3489 );
3490 }
3491 if was_visible {
3492 self.save_open_dock_positions(cx);
3493 }
3494
3495 let dock = self.dock_at_position(dock_side);
3496 dock.update(cx, |dock, cx| {
3497 dock.set_open(!was_visible, window, cx);
3498
3499 if dock.active_panel().is_none() {
3500 let Some(panel_ix) = dock
3501 .first_enabled_panel_idx(cx)
3502 .log_with_level(log::Level::Info)
3503 else {
3504 return;
3505 };
3506 dock.activate_panel(panel_ix, window, cx);
3507 }
3508
3509 if let Some(active_panel) = dock.active_panel() {
3510 if was_visible {
3511 if active_panel
3512 .panel_focus_handle(cx)
3513 .contains_focused(window, cx)
3514 {
3515 focus_center = true;
3516 }
3517 } else {
3518 let focus_handle = &active_panel.panel_focus_handle(cx);
3519 window.focus(focus_handle, cx);
3520 reveal_dock = true;
3521 }
3522 }
3523 });
3524
3525 if reveal_dock {
3526 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3527 }
3528
3529 if focus_center {
3530 self.active_pane
3531 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3532 }
3533
3534 cx.notify();
3535 self.serialize_workspace(window, cx);
3536 }
3537
3538 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3539 self.all_docks().into_iter().find(|&dock| {
3540 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3541 })
3542 }
3543
3544 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3545 if let Some(dock) = self.active_dock(window, cx).cloned() {
3546 self.save_open_dock_positions(cx);
3547 dock.update(cx, |dock, cx| {
3548 dock.set_open(false, window, cx);
3549 });
3550 return true;
3551 }
3552 false
3553 }
3554
3555 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3556 self.save_open_dock_positions(cx);
3557 for dock in self.all_docks() {
3558 dock.update(cx, |dock, cx| {
3559 dock.set_open(false, window, cx);
3560 });
3561 }
3562
3563 cx.focus_self(window);
3564 cx.notify();
3565 self.serialize_workspace(window, cx);
3566 }
3567
3568 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
3569 self.all_docks()
3570 .into_iter()
3571 .filter_map(|dock| {
3572 let dock_ref = dock.read(cx);
3573 if dock_ref.is_open() {
3574 Some(dock_ref.position())
3575 } else {
3576 None
3577 }
3578 })
3579 .collect()
3580 }
3581
3582 /// Saves the positions of currently open docks.
3583 ///
3584 /// Updates `last_open_dock_positions` with positions of all currently open
3585 /// docks, to later be restored by the 'Toggle All Docks' action.
3586 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
3587 let open_dock_positions = self.get_open_dock_positions(cx);
3588 if !open_dock_positions.is_empty() {
3589 self.last_open_dock_positions = open_dock_positions;
3590 }
3591 }
3592
3593 /// Toggles all docks between open and closed states.
3594 ///
3595 /// If any docks are open, closes all and remembers their positions. If all
3596 /// docks are closed, restores the last remembered dock configuration.
3597 fn toggle_all_docks(
3598 &mut self,
3599 _: &ToggleAllDocks,
3600 window: &mut Window,
3601 cx: &mut Context<Self>,
3602 ) {
3603 let open_dock_positions = self.get_open_dock_positions(cx);
3604
3605 if !open_dock_positions.is_empty() {
3606 self.close_all_docks(window, cx);
3607 } else if !self.last_open_dock_positions.is_empty() {
3608 self.restore_last_open_docks(window, cx);
3609 }
3610 }
3611
3612 /// Reopens docks from the most recently remembered configuration.
3613 ///
3614 /// Opens all docks whose positions are stored in `last_open_dock_positions`
3615 /// and clears the stored positions.
3616 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3617 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
3618
3619 for position in positions_to_open {
3620 let dock = self.dock_at_position(position);
3621 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
3622 }
3623
3624 cx.focus_self(window);
3625 cx.notify();
3626 self.serialize_workspace(window, cx);
3627 }
3628
3629 /// Transfer focus to the panel of the given type.
3630 pub fn focus_panel<T: Panel>(
3631 &mut self,
3632 window: &mut Window,
3633 cx: &mut Context<Self>,
3634 ) -> Option<Entity<T>> {
3635 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
3636 panel.to_any().downcast().ok()
3637 }
3638
3639 /// Focus the panel of the given type if it isn't already focused. If it is
3640 /// already focused, then transfer focus back to the workspace center.
3641 /// When the `close_panel_on_toggle` setting is enabled, also closes the
3642 /// panel when transferring focus back to the center.
3643 pub fn toggle_panel_focus<T: Panel>(
3644 &mut self,
3645 window: &mut Window,
3646 cx: &mut Context<Self>,
3647 ) -> bool {
3648 let mut did_focus_panel = false;
3649 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
3650 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
3651 did_focus_panel
3652 });
3653
3654 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
3655 self.close_panel::<T>(window, cx);
3656 }
3657
3658 telemetry::event!(
3659 "Panel Button Clicked",
3660 name = T::persistent_name(),
3661 toggle_state = did_focus_panel
3662 );
3663
3664 did_focus_panel
3665 }
3666
3667 pub fn activate_panel_for_proto_id(
3668 &mut self,
3669 panel_id: PanelId,
3670 window: &mut Window,
3671 cx: &mut Context<Self>,
3672 ) -> Option<Arc<dyn PanelHandle>> {
3673 let mut panel = None;
3674 for dock in self.all_docks() {
3675 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
3676 panel = dock.update(cx, |dock, cx| {
3677 dock.activate_panel(panel_index, window, cx);
3678 dock.set_open(true, window, cx);
3679 dock.active_panel().cloned()
3680 });
3681 break;
3682 }
3683 }
3684
3685 if panel.is_some() {
3686 cx.notify();
3687 self.serialize_workspace(window, cx);
3688 }
3689
3690 panel
3691 }
3692
3693 /// Focus or unfocus the given panel type, depending on the given callback.
3694 fn focus_or_unfocus_panel<T: Panel>(
3695 &mut self,
3696 window: &mut Window,
3697 cx: &mut Context<Self>,
3698 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
3699 ) -> Option<Arc<dyn PanelHandle>> {
3700 let mut result_panel = None;
3701 let mut serialize = false;
3702 for dock in self.all_docks() {
3703 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3704 let mut focus_center = false;
3705 let panel = dock.update(cx, |dock, cx| {
3706 dock.activate_panel(panel_index, window, cx);
3707
3708 let panel = dock.active_panel().cloned();
3709 if let Some(panel) = panel.as_ref() {
3710 if should_focus(&**panel, window, cx) {
3711 dock.set_open(true, window, cx);
3712 panel.panel_focus_handle(cx).focus(window, cx);
3713 } else {
3714 focus_center = true;
3715 }
3716 }
3717 panel
3718 });
3719
3720 if focus_center {
3721 self.active_pane
3722 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3723 }
3724
3725 result_panel = panel;
3726 serialize = true;
3727 break;
3728 }
3729 }
3730
3731 if serialize {
3732 self.serialize_workspace(window, cx);
3733 }
3734
3735 cx.notify();
3736 result_panel
3737 }
3738
3739 /// Open the panel of the given type
3740 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3741 for dock in self.all_docks() {
3742 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3743 dock.update(cx, |dock, cx| {
3744 dock.activate_panel(panel_index, window, cx);
3745 dock.set_open(true, window, cx);
3746 });
3747 }
3748 }
3749 }
3750
3751 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
3752 for dock in self.all_docks().iter() {
3753 dock.update(cx, |dock, cx| {
3754 if dock.panel::<T>().is_some() {
3755 dock.set_open(false, window, cx)
3756 }
3757 })
3758 }
3759 }
3760
3761 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
3762 self.all_docks()
3763 .iter()
3764 .find_map(|dock| dock.read(cx).panel::<T>())
3765 }
3766
3767 fn dismiss_zoomed_items_to_reveal(
3768 &mut self,
3769 dock_to_reveal: Option<DockPosition>,
3770 window: &mut Window,
3771 cx: &mut Context<Self>,
3772 ) {
3773 // If a center pane is zoomed, unzoom it.
3774 for pane in &self.panes {
3775 if pane != &self.active_pane || dock_to_reveal.is_some() {
3776 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
3777 }
3778 }
3779
3780 // If another dock is zoomed, hide it.
3781 let mut focus_center = false;
3782 for dock in self.all_docks() {
3783 dock.update(cx, |dock, cx| {
3784 if Some(dock.position()) != dock_to_reveal
3785 && let Some(panel) = dock.active_panel()
3786 && panel.is_zoomed(window, cx)
3787 {
3788 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
3789 dock.set_open(false, window, cx);
3790 }
3791 });
3792 }
3793
3794 if focus_center {
3795 self.active_pane
3796 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3797 }
3798
3799 if self.zoomed_position != dock_to_reveal {
3800 self.zoomed = None;
3801 self.zoomed_position = None;
3802 cx.emit(Event::ZoomChanged);
3803 }
3804
3805 cx.notify();
3806 }
3807
3808 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
3809 let pane = cx.new(|cx| {
3810 let mut pane = Pane::new(
3811 self.weak_handle(),
3812 self.project.clone(),
3813 self.pane_history_timestamp.clone(),
3814 None,
3815 NewFile.boxed_clone(),
3816 true,
3817 window,
3818 cx,
3819 );
3820 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
3821 pane
3822 });
3823 cx.subscribe_in(&pane, window, Self::handle_pane_event)
3824 .detach();
3825 self.panes.push(pane.clone());
3826
3827 window.focus(&pane.focus_handle(cx), cx);
3828
3829 cx.emit(Event::PaneAdded(pane.clone()));
3830 pane
3831 }
3832
3833 pub fn add_item_to_center(
3834 &mut self,
3835 item: Box<dyn ItemHandle>,
3836 window: &mut Window,
3837 cx: &mut Context<Self>,
3838 ) -> bool {
3839 if let Some(center_pane) = self.last_active_center_pane.clone() {
3840 if let Some(center_pane) = center_pane.upgrade() {
3841 center_pane.update(cx, |pane, cx| {
3842 pane.add_item(item, true, true, None, window, cx)
3843 });
3844 true
3845 } else {
3846 false
3847 }
3848 } else {
3849 false
3850 }
3851 }
3852
3853 pub fn add_item_to_active_pane(
3854 &mut self,
3855 item: Box<dyn ItemHandle>,
3856 destination_index: Option<usize>,
3857 focus_item: bool,
3858 window: &mut Window,
3859 cx: &mut App,
3860 ) {
3861 self.add_item(
3862 self.active_pane.clone(),
3863 item,
3864 destination_index,
3865 false,
3866 focus_item,
3867 window,
3868 cx,
3869 )
3870 }
3871
3872 pub fn add_item(
3873 &mut self,
3874 pane: Entity<Pane>,
3875 item: Box<dyn ItemHandle>,
3876 destination_index: Option<usize>,
3877 activate_pane: bool,
3878 focus_item: bool,
3879 window: &mut Window,
3880 cx: &mut App,
3881 ) {
3882 pane.update(cx, |pane, cx| {
3883 pane.add_item(
3884 item,
3885 activate_pane,
3886 focus_item,
3887 destination_index,
3888 window,
3889 cx,
3890 )
3891 });
3892 }
3893
3894 pub fn split_item(
3895 &mut self,
3896 split_direction: SplitDirection,
3897 item: Box<dyn ItemHandle>,
3898 window: &mut Window,
3899 cx: &mut Context<Self>,
3900 ) {
3901 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
3902 self.add_item(new_pane, item, None, true, true, window, cx);
3903 }
3904
3905 pub fn open_abs_path(
3906 &mut self,
3907 abs_path: PathBuf,
3908 options: OpenOptions,
3909 window: &mut Window,
3910 cx: &mut Context<Self>,
3911 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3912 cx.spawn_in(window, async move |workspace, cx| {
3913 let open_paths_task_result = workspace
3914 .update_in(cx, |workspace, window, cx| {
3915 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
3916 })
3917 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
3918 .await;
3919 anyhow::ensure!(
3920 open_paths_task_result.len() == 1,
3921 "open abs path {abs_path:?} task returned incorrect number of results"
3922 );
3923 match open_paths_task_result
3924 .into_iter()
3925 .next()
3926 .expect("ensured single task result")
3927 {
3928 Some(open_result) => {
3929 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
3930 }
3931 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
3932 }
3933 })
3934 }
3935
3936 pub fn split_abs_path(
3937 &mut self,
3938 abs_path: PathBuf,
3939 visible: bool,
3940 window: &mut Window,
3941 cx: &mut Context<Self>,
3942 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3943 let project_path_task =
3944 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
3945 cx.spawn_in(window, async move |this, cx| {
3946 let (_, path) = project_path_task.await?;
3947 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
3948 .await
3949 })
3950 }
3951
3952 pub fn open_path(
3953 &mut self,
3954 path: impl Into<ProjectPath>,
3955 pane: Option<WeakEntity<Pane>>,
3956 focus_item: bool,
3957 window: &mut Window,
3958 cx: &mut App,
3959 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3960 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
3961 }
3962
3963 pub fn open_path_preview(
3964 &mut self,
3965 path: impl Into<ProjectPath>,
3966 pane: Option<WeakEntity<Pane>>,
3967 focus_item: bool,
3968 allow_preview: bool,
3969 activate: bool,
3970 window: &mut Window,
3971 cx: &mut App,
3972 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3973 let pane = pane.unwrap_or_else(|| {
3974 self.last_active_center_pane.clone().unwrap_or_else(|| {
3975 self.panes
3976 .first()
3977 .expect("There must be an active pane")
3978 .downgrade()
3979 })
3980 });
3981
3982 let project_path = path.into();
3983 let task = self.load_path(project_path.clone(), window, cx);
3984 window.spawn(cx, async move |cx| {
3985 let (project_entry_id, build_item) = task.await?;
3986
3987 pane.update_in(cx, |pane, window, cx| {
3988 pane.open_item(
3989 project_entry_id,
3990 project_path,
3991 focus_item,
3992 allow_preview,
3993 activate,
3994 None,
3995 window,
3996 cx,
3997 build_item,
3998 )
3999 })
4000 })
4001 }
4002
4003 pub fn split_path(
4004 &mut self,
4005 path: impl Into<ProjectPath>,
4006 window: &mut Window,
4007 cx: &mut Context<Self>,
4008 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4009 self.split_path_preview(path, false, None, window, cx)
4010 }
4011
4012 pub fn split_path_preview(
4013 &mut self,
4014 path: impl Into<ProjectPath>,
4015 allow_preview: bool,
4016 split_direction: Option<SplitDirection>,
4017 window: &mut Window,
4018 cx: &mut Context<Self>,
4019 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4020 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4021 self.panes
4022 .first()
4023 .expect("There must be an active pane")
4024 .downgrade()
4025 });
4026
4027 if let Member::Pane(center_pane) = &self.center.root
4028 && center_pane.read(cx).items_len() == 0
4029 {
4030 return self.open_path(path, Some(pane), true, window, cx);
4031 }
4032
4033 let project_path = path.into();
4034 let task = self.load_path(project_path.clone(), window, cx);
4035 cx.spawn_in(window, async move |this, cx| {
4036 let (project_entry_id, build_item) = task.await?;
4037 this.update_in(cx, move |this, window, cx| -> Option<_> {
4038 let pane = pane.upgrade()?;
4039 let new_pane = this.split_pane(
4040 pane,
4041 split_direction.unwrap_or(SplitDirection::Right),
4042 window,
4043 cx,
4044 );
4045 new_pane.update(cx, |new_pane, cx| {
4046 Some(new_pane.open_item(
4047 project_entry_id,
4048 project_path,
4049 true,
4050 allow_preview,
4051 true,
4052 None,
4053 window,
4054 cx,
4055 build_item,
4056 ))
4057 })
4058 })
4059 .map(|option| option.context("pane was dropped"))?
4060 })
4061 }
4062
4063 fn load_path(
4064 &mut self,
4065 path: ProjectPath,
4066 window: &mut Window,
4067 cx: &mut App,
4068 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4069 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4070 registry.open_path(self.project(), &path, window, cx)
4071 }
4072
4073 pub fn find_project_item<T>(
4074 &self,
4075 pane: &Entity<Pane>,
4076 project_item: &Entity<T::Item>,
4077 cx: &App,
4078 ) -> Option<Entity<T>>
4079 where
4080 T: ProjectItem,
4081 {
4082 use project::ProjectItem as _;
4083 let project_item = project_item.read(cx);
4084 let entry_id = project_item.entry_id(cx);
4085 let project_path = project_item.project_path(cx);
4086
4087 let mut item = None;
4088 if let Some(entry_id) = entry_id {
4089 item = pane.read(cx).item_for_entry(entry_id, cx);
4090 }
4091 if item.is_none()
4092 && let Some(project_path) = project_path
4093 {
4094 item = pane.read(cx).item_for_path(project_path, cx);
4095 }
4096
4097 item.and_then(|item| item.downcast::<T>())
4098 }
4099
4100 pub fn is_project_item_open<T>(
4101 &self,
4102 pane: &Entity<Pane>,
4103 project_item: &Entity<T::Item>,
4104 cx: &App,
4105 ) -> bool
4106 where
4107 T: ProjectItem,
4108 {
4109 self.find_project_item::<T>(pane, project_item, cx)
4110 .is_some()
4111 }
4112
4113 pub fn open_project_item<T>(
4114 &mut self,
4115 pane: Entity<Pane>,
4116 project_item: Entity<T::Item>,
4117 activate_pane: bool,
4118 focus_item: bool,
4119 keep_old_preview: bool,
4120 allow_new_preview: bool,
4121 window: &mut Window,
4122 cx: &mut Context<Self>,
4123 ) -> Entity<T>
4124 where
4125 T: ProjectItem,
4126 {
4127 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4128
4129 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4130 if !keep_old_preview
4131 && let Some(old_id) = old_item_id
4132 && old_id != item.item_id()
4133 {
4134 // switching to a different item, so unpreview old active item
4135 pane.update(cx, |pane, _| {
4136 pane.unpreview_item_if_preview(old_id);
4137 });
4138 }
4139
4140 self.activate_item(&item, activate_pane, focus_item, window, cx);
4141 if !allow_new_preview {
4142 pane.update(cx, |pane, _| {
4143 pane.unpreview_item_if_preview(item.item_id());
4144 });
4145 }
4146 return item;
4147 }
4148
4149 let item = pane.update(cx, |pane, cx| {
4150 cx.new(|cx| {
4151 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4152 })
4153 });
4154 let mut destination_index = None;
4155 pane.update(cx, |pane, cx| {
4156 if !keep_old_preview && let Some(old_id) = old_item_id {
4157 pane.unpreview_item_if_preview(old_id);
4158 }
4159 if allow_new_preview {
4160 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4161 }
4162 });
4163
4164 self.add_item(
4165 pane,
4166 Box::new(item.clone()),
4167 destination_index,
4168 activate_pane,
4169 focus_item,
4170 window,
4171 cx,
4172 );
4173 item
4174 }
4175
4176 pub fn open_shared_screen(
4177 &mut self,
4178 peer_id: PeerId,
4179 window: &mut Window,
4180 cx: &mut Context<Self>,
4181 ) {
4182 if let Some(shared_screen) =
4183 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4184 {
4185 self.active_pane.update(cx, |pane, cx| {
4186 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4187 });
4188 }
4189 }
4190
4191 pub fn activate_item(
4192 &mut self,
4193 item: &dyn ItemHandle,
4194 activate_pane: bool,
4195 focus_item: bool,
4196 window: &mut Window,
4197 cx: &mut App,
4198 ) -> bool {
4199 let result = self.panes.iter().find_map(|pane| {
4200 pane.read(cx)
4201 .index_for_item(item)
4202 .map(|ix| (pane.clone(), ix))
4203 });
4204 if let Some((pane, ix)) = result {
4205 pane.update(cx, |pane, cx| {
4206 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4207 });
4208 true
4209 } else {
4210 false
4211 }
4212 }
4213
4214 fn activate_pane_at_index(
4215 &mut self,
4216 action: &ActivatePane,
4217 window: &mut Window,
4218 cx: &mut Context<Self>,
4219 ) {
4220 let panes = self.center.panes();
4221 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4222 window.focus(&pane.focus_handle(cx), cx);
4223 } else {
4224 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4225 .detach();
4226 }
4227 }
4228
4229 fn move_item_to_pane_at_index(
4230 &mut self,
4231 action: &MoveItemToPane,
4232 window: &mut Window,
4233 cx: &mut Context<Self>,
4234 ) {
4235 let panes = self.center.panes();
4236 let destination = match panes.get(action.destination) {
4237 Some(&destination) => destination.clone(),
4238 None => {
4239 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4240 return;
4241 }
4242 let direction = SplitDirection::Right;
4243 let split_off_pane = self
4244 .find_pane_in_direction(direction, cx)
4245 .unwrap_or_else(|| self.active_pane.clone());
4246 let new_pane = self.add_pane(window, cx);
4247 if self
4248 .center
4249 .split(&split_off_pane, &new_pane, direction, cx)
4250 .log_err()
4251 .is_none()
4252 {
4253 return;
4254 };
4255 new_pane
4256 }
4257 };
4258
4259 if action.clone {
4260 if self
4261 .active_pane
4262 .read(cx)
4263 .active_item()
4264 .is_some_and(|item| item.can_split(cx))
4265 {
4266 clone_active_item(
4267 self.database_id(),
4268 &self.active_pane,
4269 &destination,
4270 action.focus,
4271 window,
4272 cx,
4273 );
4274 return;
4275 }
4276 }
4277 move_active_item(
4278 &self.active_pane,
4279 &destination,
4280 action.focus,
4281 true,
4282 window,
4283 cx,
4284 )
4285 }
4286
4287 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4288 let panes = self.center.panes();
4289 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4290 let next_ix = (ix + 1) % panes.len();
4291 let next_pane = panes[next_ix].clone();
4292 window.focus(&next_pane.focus_handle(cx), cx);
4293 }
4294 }
4295
4296 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4297 let panes = self.center.panes();
4298 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4299 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4300 let prev_pane = panes[prev_ix].clone();
4301 window.focus(&prev_pane.focus_handle(cx), cx);
4302 }
4303 }
4304
4305 pub fn activate_pane_in_direction(
4306 &mut self,
4307 direction: SplitDirection,
4308 window: &mut Window,
4309 cx: &mut App,
4310 ) {
4311 use ActivateInDirectionTarget as Target;
4312 enum Origin {
4313 LeftDock,
4314 RightDock,
4315 BottomDock,
4316 Center,
4317 }
4318
4319 let origin: Origin = [
4320 (&self.left_dock, Origin::LeftDock),
4321 (&self.right_dock, Origin::RightDock),
4322 (&self.bottom_dock, Origin::BottomDock),
4323 ]
4324 .into_iter()
4325 .find_map(|(dock, origin)| {
4326 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4327 Some(origin)
4328 } else {
4329 None
4330 }
4331 })
4332 .unwrap_or(Origin::Center);
4333
4334 let get_last_active_pane = || {
4335 let pane = self
4336 .last_active_center_pane
4337 .clone()
4338 .unwrap_or_else(|| {
4339 self.panes
4340 .first()
4341 .expect("There must be an active pane")
4342 .downgrade()
4343 })
4344 .upgrade()?;
4345 (pane.read(cx).items_len() != 0).then_some(pane)
4346 };
4347
4348 let try_dock =
4349 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4350
4351 let target = match (origin, direction) {
4352 // We're in the center, so we first try to go to a different pane,
4353 // otherwise try to go to a dock.
4354 (Origin::Center, direction) => {
4355 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4356 Some(Target::Pane(pane))
4357 } else {
4358 match direction {
4359 SplitDirection::Up => None,
4360 SplitDirection::Down => try_dock(&self.bottom_dock),
4361 SplitDirection::Left => try_dock(&self.left_dock),
4362 SplitDirection::Right => try_dock(&self.right_dock),
4363 }
4364 }
4365 }
4366
4367 (Origin::LeftDock, SplitDirection::Right) => {
4368 if let Some(last_active_pane) = get_last_active_pane() {
4369 Some(Target::Pane(last_active_pane))
4370 } else {
4371 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4372 }
4373 }
4374
4375 (Origin::LeftDock, SplitDirection::Down)
4376 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4377
4378 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4379 (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
4380 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4381
4382 (Origin::RightDock, SplitDirection::Left) => {
4383 if let Some(last_active_pane) = get_last_active_pane() {
4384 Some(Target::Pane(last_active_pane))
4385 } else {
4386 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
4387 }
4388 }
4389
4390 _ => None,
4391 };
4392
4393 match target {
4394 Some(ActivateInDirectionTarget::Pane(pane)) => {
4395 let pane = pane.read(cx);
4396 if let Some(item) = pane.active_item() {
4397 item.item_focus_handle(cx).focus(window, cx);
4398 } else {
4399 log::error!(
4400 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4401 );
4402 }
4403 }
4404 Some(ActivateInDirectionTarget::Dock(dock)) => {
4405 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4406 window.defer(cx, move |window, cx| {
4407 let dock = dock.read(cx);
4408 if let Some(panel) = dock.active_panel() {
4409 panel.panel_focus_handle(cx).focus(window, cx);
4410 } else {
4411 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4412 }
4413 })
4414 }
4415 None => {}
4416 }
4417 }
4418
4419 pub fn move_item_to_pane_in_direction(
4420 &mut self,
4421 action: &MoveItemToPaneInDirection,
4422 window: &mut Window,
4423 cx: &mut Context<Self>,
4424 ) {
4425 let destination = match self.find_pane_in_direction(action.direction, cx) {
4426 Some(destination) => destination,
4427 None => {
4428 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4429 return;
4430 }
4431 let new_pane = self.add_pane(window, cx);
4432 if self
4433 .center
4434 .split(&self.active_pane, &new_pane, action.direction, cx)
4435 .log_err()
4436 .is_none()
4437 {
4438 return;
4439 };
4440 new_pane
4441 }
4442 };
4443
4444 if action.clone {
4445 if self
4446 .active_pane
4447 .read(cx)
4448 .active_item()
4449 .is_some_and(|item| item.can_split(cx))
4450 {
4451 clone_active_item(
4452 self.database_id(),
4453 &self.active_pane,
4454 &destination,
4455 action.focus,
4456 window,
4457 cx,
4458 );
4459 return;
4460 }
4461 }
4462 move_active_item(
4463 &self.active_pane,
4464 &destination,
4465 action.focus,
4466 true,
4467 window,
4468 cx,
4469 );
4470 }
4471
4472 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4473 self.center.bounding_box_for_pane(pane)
4474 }
4475
4476 pub fn find_pane_in_direction(
4477 &mut self,
4478 direction: SplitDirection,
4479 cx: &App,
4480 ) -> Option<Entity<Pane>> {
4481 self.center
4482 .find_pane_in_direction(&self.active_pane, direction, cx)
4483 .cloned()
4484 }
4485
4486 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4487 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4488 self.center.swap(&self.active_pane, &to, cx);
4489 cx.notify();
4490 }
4491 }
4492
4493 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4494 if self
4495 .center
4496 .move_to_border(&self.active_pane, direction, cx)
4497 .unwrap()
4498 {
4499 cx.notify();
4500 }
4501 }
4502
4503 pub fn resize_pane(
4504 &mut self,
4505 axis: gpui::Axis,
4506 amount: Pixels,
4507 window: &mut Window,
4508 cx: &mut Context<Self>,
4509 ) {
4510 let docks = self.all_docks();
4511 let active_dock = docks
4512 .into_iter()
4513 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4514
4515 if let Some(dock) = active_dock {
4516 let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
4517 return;
4518 };
4519 match dock.read(cx).position() {
4520 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4521 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4522 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4523 }
4524 } else {
4525 self.center
4526 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
4527 }
4528 cx.notify();
4529 }
4530
4531 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
4532 self.center.reset_pane_sizes(cx);
4533 cx.notify();
4534 }
4535
4536 fn handle_pane_focused(
4537 &mut self,
4538 pane: Entity<Pane>,
4539 window: &mut Window,
4540 cx: &mut Context<Self>,
4541 ) {
4542 // This is explicitly hoisted out of the following check for pane identity as
4543 // terminal panel panes are not registered as a center panes.
4544 self.status_bar.update(cx, |status_bar, cx| {
4545 status_bar.set_active_pane(&pane, window, cx);
4546 });
4547 if self.active_pane != pane {
4548 self.set_active_pane(&pane, window, cx);
4549 }
4550
4551 if self.last_active_center_pane.is_none() {
4552 self.last_active_center_pane = Some(pane.downgrade());
4553 }
4554
4555 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
4556 // This prevents the dock from closing when focus events fire during window activation.
4557 // We also preserve any dock whose active panel itself has focus — this covers
4558 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
4559 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
4560 let dock_read = dock.read(cx);
4561 if let Some(panel) = dock_read.active_panel() {
4562 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
4563 || panel.panel_focus_handle(cx).contains_focused(window, cx)
4564 {
4565 return Some(dock_read.position());
4566 }
4567 }
4568 None
4569 });
4570
4571 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
4572 if pane.read(cx).is_zoomed() {
4573 self.zoomed = Some(pane.downgrade().into());
4574 } else {
4575 self.zoomed = None;
4576 }
4577 self.zoomed_position = None;
4578 cx.emit(Event::ZoomChanged);
4579 self.update_active_view_for_followers(window, cx);
4580 pane.update(cx, |pane, _| {
4581 pane.track_alternate_file_items();
4582 });
4583
4584 cx.notify();
4585 }
4586
4587 fn set_active_pane(
4588 &mut self,
4589 pane: &Entity<Pane>,
4590 window: &mut Window,
4591 cx: &mut Context<Self>,
4592 ) {
4593 self.active_pane = pane.clone();
4594 self.active_item_path_changed(true, window, cx);
4595 self.last_active_center_pane = Some(pane.downgrade());
4596 }
4597
4598 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4599 self.update_active_view_for_followers(window, cx);
4600 }
4601
4602 fn handle_pane_event(
4603 &mut self,
4604 pane: &Entity<Pane>,
4605 event: &pane::Event,
4606 window: &mut Window,
4607 cx: &mut Context<Self>,
4608 ) {
4609 let mut serialize_workspace = true;
4610 match event {
4611 pane::Event::AddItem { item } => {
4612 item.added_to_pane(self, pane.clone(), window, cx);
4613 cx.emit(Event::ItemAdded {
4614 item: item.boxed_clone(),
4615 });
4616 }
4617 pane::Event::Split { direction, mode } => {
4618 match mode {
4619 SplitMode::ClonePane => {
4620 self.split_and_clone(pane.clone(), *direction, window, cx)
4621 .detach();
4622 }
4623 SplitMode::EmptyPane => {
4624 self.split_pane(pane.clone(), *direction, window, cx);
4625 }
4626 SplitMode::MovePane => {
4627 self.split_and_move(pane.clone(), *direction, window, cx);
4628 }
4629 };
4630 }
4631 pane::Event::JoinIntoNext => {
4632 self.join_pane_into_next(pane.clone(), window, cx);
4633 }
4634 pane::Event::JoinAll => {
4635 self.join_all_panes(window, cx);
4636 }
4637 pane::Event::Remove { focus_on_pane } => {
4638 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
4639 }
4640 pane::Event::ActivateItem {
4641 local,
4642 focus_changed,
4643 } => {
4644 window.invalidate_character_coordinates();
4645
4646 pane.update(cx, |pane, _| {
4647 pane.track_alternate_file_items();
4648 });
4649 if *local {
4650 self.unfollow_in_pane(pane, window, cx);
4651 }
4652 serialize_workspace = *focus_changed || pane != self.active_pane();
4653 if pane == self.active_pane() {
4654 self.active_item_path_changed(*focus_changed, window, cx);
4655 self.update_active_view_for_followers(window, cx);
4656 } else if *local {
4657 self.set_active_pane(pane, window, cx);
4658 }
4659 }
4660 pane::Event::UserSavedItem { item, save_intent } => {
4661 cx.emit(Event::UserSavedItem {
4662 pane: pane.downgrade(),
4663 item: item.boxed_clone(),
4664 save_intent: *save_intent,
4665 });
4666 serialize_workspace = false;
4667 }
4668 pane::Event::ChangeItemTitle => {
4669 if *pane == self.active_pane {
4670 self.active_item_path_changed(false, window, cx);
4671 }
4672 serialize_workspace = false;
4673 }
4674 pane::Event::RemovedItem { item } => {
4675 cx.emit(Event::ActiveItemChanged);
4676 self.update_window_edited(window, cx);
4677 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
4678 && entry.get().entity_id() == pane.entity_id()
4679 {
4680 entry.remove();
4681 }
4682 cx.emit(Event::ItemRemoved {
4683 item_id: item.item_id(),
4684 });
4685 }
4686 pane::Event::Focus => {
4687 window.invalidate_character_coordinates();
4688 self.handle_pane_focused(pane.clone(), window, cx);
4689 }
4690 pane::Event::ZoomIn => {
4691 if *pane == self.active_pane {
4692 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
4693 if pane.read(cx).has_focus(window, cx) {
4694 self.zoomed = Some(pane.downgrade().into());
4695 self.zoomed_position = None;
4696 cx.emit(Event::ZoomChanged);
4697 }
4698 cx.notify();
4699 }
4700 }
4701 pane::Event::ZoomOut => {
4702 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4703 if self.zoomed_position.is_none() {
4704 self.zoomed = None;
4705 cx.emit(Event::ZoomChanged);
4706 }
4707 cx.notify();
4708 }
4709 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
4710 }
4711
4712 if serialize_workspace {
4713 self.serialize_workspace(window, cx);
4714 }
4715 }
4716
4717 pub fn unfollow_in_pane(
4718 &mut self,
4719 pane: &Entity<Pane>,
4720 window: &mut Window,
4721 cx: &mut Context<Workspace>,
4722 ) -> Option<CollaboratorId> {
4723 let leader_id = self.leader_for_pane(pane)?;
4724 self.unfollow(leader_id, window, cx);
4725 Some(leader_id)
4726 }
4727
4728 pub fn split_pane(
4729 &mut self,
4730 pane_to_split: Entity<Pane>,
4731 split_direction: SplitDirection,
4732 window: &mut Window,
4733 cx: &mut Context<Self>,
4734 ) -> Entity<Pane> {
4735 let new_pane = self.add_pane(window, cx);
4736 self.center
4737 .split(&pane_to_split, &new_pane, split_direction, cx)
4738 .unwrap();
4739 cx.notify();
4740 new_pane
4741 }
4742
4743 pub fn split_and_move(
4744 &mut self,
4745 pane: Entity<Pane>,
4746 direction: SplitDirection,
4747 window: &mut Window,
4748 cx: &mut Context<Self>,
4749 ) {
4750 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
4751 return;
4752 };
4753 let new_pane = self.add_pane(window, cx);
4754 new_pane.update(cx, |pane, cx| {
4755 pane.add_item(item, true, true, None, window, cx)
4756 });
4757 self.center.split(&pane, &new_pane, direction, cx).unwrap();
4758 cx.notify();
4759 }
4760
4761 pub fn split_and_clone(
4762 &mut self,
4763 pane: Entity<Pane>,
4764 direction: SplitDirection,
4765 window: &mut Window,
4766 cx: &mut Context<Self>,
4767 ) -> Task<Option<Entity<Pane>>> {
4768 let Some(item) = pane.read(cx).active_item() else {
4769 return Task::ready(None);
4770 };
4771 if !item.can_split(cx) {
4772 return Task::ready(None);
4773 }
4774 let task = item.clone_on_split(self.database_id(), window, cx);
4775 cx.spawn_in(window, async move |this, cx| {
4776 if let Some(clone) = task.await {
4777 this.update_in(cx, |this, window, cx| {
4778 let new_pane = this.add_pane(window, cx);
4779 let nav_history = pane.read(cx).fork_nav_history();
4780 new_pane.update(cx, |pane, cx| {
4781 pane.set_nav_history(nav_history, cx);
4782 pane.add_item(clone, true, true, None, window, cx)
4783 });
4784 this.center.split(&pane, &new_pane, direction, cx).unwrap();
4785 cx.notify();
4786 new_pane
4787 })
4788 .ok()
4789 } else {
4790 None
4791 }
4792 })
4793 }
4794
4795 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4796 let active_item = self.active_pane.read(cx).active_item();
4797 for pane in &self.panes {
4798 join_pane_into_active(&self.active_pane, pane, window, cx);
4799 }
4800 if let Some(active_item) = active_item {
4801 self.activate_item(active_item.as_ref(), true, true, window, cx);
4802 }
4803 cx.notify();
4804 }
4805
4806 pub fn join_pane_into_next(
4807 &mut self,
4808 pane: Entity<Pane>,
4809 window: &mut Window,
4810 cx: &mut Context<Self>,
4811 ) {
4812 let next_pane = self
4813 .find_pane_in_direction(SplitDirection::Right, cx)
4814 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
4815 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
4816 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
4817 let Some(next_pane) = next_pane else {
4818 return;
4819 };
4820 move_all_items(&pane, &next_pane, window, cx);
4821 cx.notify();
4822 }
4823
4824 fn remove_pane(
4825 &mut self,
4826 pane: Entity<Pane>,
4827 focus_on: Option<Entity<Pane>>,
4828 window: &mut Window,
4829 cx: &mut Context<Self>,
4830 ) {
4831 if self.center.remove(&pane, cx).unwrap() {
4832 self.force_remove_pane(&pane, &focus_on, window, cx);
4833 self.unfollow_in_pane(&pane, window, cx);
4834 self.last_leaders_by_pane.remove(&pane.downgrade());
4835 for removed_item in pane.read(cx).items() {
4836 self.panes_by_item.remove(&removed_item.item_id());
4837 }
4838
4839 cx.notify();
4840 } else {
4841 self.active_item_path_changed(true, window, cx);
4842 }
4843 cx.emit(Event::PaneRemoved);
4844 }
4845
4846 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
4847 &mut self.panes
4848 }
4849
4850 pub fn panes(&self) -> &[Entity<Pane>] {
4851 &self.panes
4852 }
4853
4854 pub fn active_pane(&self) -> &Entity<Pane> {
4855 &self.active_pane
4856 }
4857
4858 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
4859 for dock in self.all_docks() {
4860 if dock.focus_handle(cx).contains_focused(window, cx)
4861 && let Some(pane) = dock
4862 .read(cx)
4863 .active_panel()
4864 .and_then(|panel| panel.pane(cx))
4865 {
4866 return pane;
4867 }
4868 }
4869 self.active_pane().clone()
4870 }
4871
4872 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4873 self.find_pane_in_direction(SplitDirection::Right, cx)
4874 .unwrap_or_else(|| {
4875 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
4876 })
4877 }
4878
4879 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
4880 let weak_pane = self.panes_by_item.get(&handle.item_id())?;
4881 weak_pane.upgrade()
4882 }
4883
4884 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
4885 self.follower_states.retain(|leader_id, state| {
4886 if *leader_id == CollaboratorId::PeerId(peer_id) {
4887 for item in state.items_by_leader_view_id.values() {
4888 item.view.set_leader_id(None, window, cx);
4889 }
4890 false
4891 } else {
4892 true
4893 }
4894 });
4895 cx.notify();
4896 }
4897
4898 pub fn start_following(
4899 &mut self,
4900 leader_id: impl Into<CollaboratorId>,
4901 window: &mut Window,
4902 cx: &mut Context<Self>,
4903 ) -> Option<Task<Result<()>>> {
4904 let leader_id = leader_id.into();
4905 let pane = self.active_pane().clone();
4906
4907 self.last_leaders_by_pane
4908 .insert(pane.downgrade(), leader_id);
4909 self.unfollow(leader_id, window, cx);
4910 self.unfollow_in_pane(&pane, window, cx);
4911 self.follower_states.insert(
4912 leader_id,
4913 FollowerState {
4914 center_pane: pane.clone(),
4915 dock_pane: None,
4916 active_view_id: None,
4917 items_by_leader_view_id: Default::default(),
4918 },
4919 );
4920 cx.notify();
4921
4922 match leader_id {
4923 CollaboratorId::PeerId(leader_peer_id) => {
4924 let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
4925 let project_id = self.project.read(cx).remote_id();
4926 let request = self.app_state.client.request(proto::Follow {
4927 room_id,
4928 project_id,
4929 leader_id: Some(leader_peer_id),
4930 });
4931
4932 Some(cx.spawn_in(window, async move |this, cx| {
4933 let response = request.await?;
4934 this.update(cx, |this, _| {
4935 let state = this
4936 .follower_states
4937 .get_mut(&leader_id)
4938 .context("following interrupted")?;
4939 state.active_view_id = response
4940 .active_view
4941 .as_ref()
4942 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
4943 anyhow::Ok(())
4944 })??;
4945 if let Some(view) = response.active_view {
4946 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
4947 }
4948 this.update_in(cx, |this, window, cx| {
4949 this.leader_updated(leader_id, window, cx)
4950 })?;
4951 Ok(())
4952 }))
4953 }
4954 CollaboratorId::Agent => {
4955 self.leader_updated(leader_id, window, cx)?;
4956 Some(Task::ready(Ok(())))
4957 }
4958 }
4959 }
4960
4961 pub fn follow_next_collaborator(
4962 &mut self,
4963 _: &FollowNextCollaborator,
4964 window: &mut Window,
4965 cx: &mut Context<Self>,
4966 ) {
4967 let collaborators = self.project.read(cx).collaborators();
4968 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
4969 let mut collaborators = collaborators.keys().copied();
4970 for peer_id in collaborators.by_ref() {
4971 if CollaboratorId::PeerId(peer_id) == leader_id {
4972 break;
4973 }
4974 }
4975 collaborators.next().map(CollaboratorId::PeerId)
4976 } else if let Some(last_leader_id) =
4977 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
4978 {
4979 match last_leader_id {
4980 CollaboratorId::PeerId(peer_id) => {
4981 if collaborators.contains_key(peer_id) {
4982 Some(*last_leader_id)
4983 } else {
4984 None
4985 }
4986 }
4987 CollaboratorId::Agent => Some(CollaboratorId::Agent),
4988 }
4989 } else {
4990 None
4991 };
4992
4993 let pane = self.active_pane.clone();
4994 let Some(leader_id) = next_leader_id.or_else(|| {
4995 Some(CollaboratorId::PeerId(
4996 collaborators.keys().copied().next()?,
4997 ))
4998 }) else {
4999 return;
5000 };
5001 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5002 return;
5003 }
5004 if let Some(task) = self.start_following(leader_id, window, cx) {
5005 task.detach_and_log_err(cx)
5006 }
5007 }
5008
5009 pub fn follow(
5010 &mut self,
5011 leader_id: impl Into<CollaboratorId>,
5012 window: &mut Window,
5013 cx: &mut Context<Self>,
5014 ) {
5015 let leader_id = leader_id.into();
5016
5017 if let CollaboratorId::PeerId(peer_id) = leader_id {
5018 let Some(room) = ActiveCall::global(cx).read(cx).room() else {
5019 return;
5020 };
5021 let room = room.read(cx);
5022 let Some(remote_participant) = room.remote_participant_for_peer_id(peer_id) else {
5023 return;
5024 };
5025
5026 let project = self.project.read(cx);
5027
5028 let other_project_id = match remote_participant.location {
5029 call::ParticipantLocation::External => None,
5030 call::ParticipantLocation::UnsharedProject => None,
5031 call::ParticipantLocation::SharedProject { project_id } => {
5032 if Some(project_id) == project.remote_id() {
5033 None
5034 } else {
5035 Some(project_id)
5036 }
5037 }
5038 };
5039
5040 // if they are active in another project, follow there.
5041 if let Some(project_id) = other_project_id {
5042 let app_state = self.app_state.clone();
5043 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5044 .detach_and_log_err(cx);
5045 }
5046 }
5047
5048 // if you're already following, find the right pane and focus it.
5049 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5050 window.focus(&follower_state.pane().focus_handle(cx), cx);
5051
5052 return;
5053 }
5054
5055 // Otherwise, follow.
5056 if let Some(task) = self.start_following(leader_id, window, cx) {
5057 task.detach_and_log_err(cx)
5058 }
5059 }
5060
5061 pub fn unfollow(
5062 &mut self,
5063 leader_id: impl Into<CollaboratorId>,
5064 window: &mut Window,
5065 cx: &mut Context<Self>,
5066 ) -> Option<()> {
5067 cx.notify();
5068
5069 let leader_id = leader_id.into();
5070 let state = self.follower_states.remove(&leader_id)?;
5071 for (_, item) in state.items_by_leader_view_id {
5072 item.view.set_leader_id(None, window, cx);
5073 }
5074
5075 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5076 let project_id = self.project.read(cx).remote_id();
5077 let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
5078 self.app_state
5079 .client
5080 .send(proto::Unfollow {
5081 room_id,
5082 project_id,
5083 leader_id: Some(leader_peer_id),
5084 })
5085 .log_err();
5086 }
5087
5088 Some(())
5089 }
5090
5091 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5092 self.follower_states.contains_key(&id.into())
5093 }
5094
5095 fn active_item_path_changed(
5096 &mut self,
5097 focus_changed: bool,
5098 window: &mut Window,
5099 cx: &mut Context<Self>,
5100 ) {
5101 cx.emit(Event::ActiveItemChanged);
5102 let active_entry = self.active_project_path(cx);
5103 self.project.update(cx, |project, cx| {
5104 project.set_active_path(active_entry.clone(), cx)
5105 });
5106
5107 if focus_changed && let Some(project_path) = &active_entry {
5108 let git_store_entity = self.project.read(cx).git_store().clone();
5109 git_store_entity.update(cx, |git_store, cx| {
5110 git_store.set_active_repo_for_path(project_path, cx);
5111 });
5112 }
5113
5114 self.update_window_title(window, cx);
5115 }
5116
5117 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5118 let project = self.project().read(cx);
5119 let mut title = String::new();
5120
5121 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5122 let name = {
5123 let settings_location = SettingsLocation {
5124 worktree_id: worktree.read(cx).id(),
5125 path: RelPath::empty(),
5126 };
5127
5128 let settings = WorktreeSettings::get(Some(settings_location), cx);
5129 match &settings.project_name {
5130 Some(name) => name.as_str(),
5131 None => worktree.read(cx).root_name_str(),
5132 }
5133 };
5134 if i > 0 {
5135 title.push_str(", ");
5136 }
5137 title.push_str(name);
5138 }
5139
5140 if title.is_empty() {
5141 title = "empty project".to_string();
5142 }
5143
5144 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5145 let filename = path.path.file_name().or_else(|| {
5146 Some(
5147 project
5148 .worktree_for_id(path.worktree_id, cx)?
5149 .read(cx)
5150 .root_name_str(),
5151 )
5152 });
5153
5154 if let Some(filename) = filename {
5155 title.push_str(" — ");
5156 title.push_str(filename.as_ref());
5157 }
5158 }
5159
5160 if project.is_via_collab() {
5161 title.push_str(" ↙");
5162 } else if project.is_shared() {
5163 title.push_str(" ↗");
5164 }
5165
5166 if let Some(last_title) = self.last_window_title.as_ref()
5167 && &title == last_title
5168 {
5169 return;
5170 }
5171 window.set_window_title(&title);
5172 SystemWindowTabController::update_tab_title(
5173 cx,
5174 window.window_handle().window_id(),
5175 SharedString::from(&title),
5176 );
5177 self.last_window_title = Some(title);
5178 }
5179
5180 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5181 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5182 if is_edited != self.window_edited {
5183 self.window_edited = is_edited;
5184 window.set_window_edited(self.window_edited)
5185 }
5186 }
5187
5188 fn update_item_dirty_state(
5189 &mut self,
5190 item: &dyn ItemHandle,
5191 window: &mut Window,
5192 cx: &mut App,
5193 ) {
5194 let is_dirty = item.is_dirty(cx);
5195 let item_id = item.item_id();
5196 let was_dirty = self.dirty_items.contains_key(&item_id);
5197 if is_dirty == was_dirty {
5198 return;
5199 }
5200 if was_dirty {
5201 self.dirty_items.remove(&item_id);
5202 self.update_window_edited(window, cx);
5203 return;
5204 }
5205
5206 let workspace = self.weak_handle();
5207 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5208 return;
5209 };
5210 let on_release_callback = Box::new(move |cx: &mut App| {
5211 window_handle
5212 .update(cx, |_, window, cx| {
5213 workspace
5214 .update(cx, |workspace, cx| {
5215 workspace.dirty_items.remove(&item_id);
5216 workspace.update_window_edited(window, cx)
5217 })
5218 .ok();
5219 })
5220 .ok();
5221 });
5222
5223 let s = item.on_release(cx, on_release_callback);
5224 self.dirty_items.insert(item_id, s);
5225 self.update_window_edited(window, cx);
5226 }
5227
5228 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5229 if self.notifications.is_empty() {
5230 None
5231 } else {
5232 Some(
5233 div()
5234 .absolute()
5235 .right_3()
5236 .bottom_3()
5237 .w_112()
5238 .h_full()
5239 .flex()
5240 .flex_col()
5241 .justify_end()
5242 .gap_2()
5243 .children(
5244 self.notifications
5245 .iter()
5246 .map(|(_, notification)| notification.clone().into_any()),
5247 ),
5248 )
5249 }
5250 }
5251
5252 // RPC handlers
5253
5254 fn active_view_for_follower(
5255 &self,
5256 follower_project_id: Option<u64>,
5257 window: &mut Window,
5258 cx: &mut Context<Self>,
5259 ) -> Option<proto::View> {
5260 let (item, panel_id) = self.active_item_for_followers(window, cx);
5261 let item = item?;
5262 let leader_id = self
5263 .pane_for(&*item)
5264 .and_then(|pane| self.leader_for_pane(&pane));
5265 let leader_peer_id = match leader_id {
5266 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5267 Some(CollaboratorId::Agent) | None => None,
5268 };
5269
5270 let item_handle = item.to_followable_item_handle(cx)?;
5271 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5272 let variant = item_handle.to_state_proto(window, cx)?;
5273
5274 if item_handle.is_project_item(window, cx)
5275 && (follower_project_id.is_none()
5276 || follower_project_id != self.project.read(cx).remote_id())
5277 {
5278 return None;
5279 }
5280
5281 Some(proto::View {
5282 id: id.to_proto(),
5283 leader_id: leader_peer_id,
5284 variant: Some(variant),
5285 panel_id: panel_id.map(|id| id as i32),
5286 })
5287 }
5288
5289 fn handle_follow(
5290 &mut self,
5291 follower_project_id: Option<u64>,
5292 window: &mut Window,
5293 cx: &mut Context<Self>,
5294 ) -> proto::FollowResponse {
5295 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5296
5297 cx.notify();
5298 proto::FollowResponse {
5299 views: active_view.iter().cloned().collect(),
5300 active_view,
5301 }
5302 }
5303
5304 fn handle_update_followers(
5305 &mut self,
5306 leader_id: PeerId,
5307 message: proto::UpdateFollowers,
5308 _window: &mut Window,
5309 _cx: &mut Context<Self>,
5310 ) {
5311 self.leader_updates_tx
5312 .unbounded_send((leader_id, message))
5313 .ok();
5314 }
5315
5316 async fn process_leader_update(
5317 this: &WeakEntity<Self>,
5318 leader_id: PeerId,
5319 update: proto::UpdateFollowers,
5320 cx: &mut AsyncWindowContext,
5321 ) -> Result<()> {
5322 match update.variant.context("invalid update")? {
5323 proto::update_followers::Variant::CreateView(view) => {
5324 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5325 let should_add_view = this.update(cx, |this, _| {
5326 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5327 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5328 } else {
5329 anyhow::Ok(false)
5330 }
5331 })??;
5332
5333 if should_add_view {
5334 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5335 }
5336 }
5337 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5338 let should_add_view = this.update(cx, |this, _| {
5339 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5340 state.active_view_id = update_active_view
5341 .view
5342 .as_ref()
5343 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5344
5345 if state.active_view_id.is_some_and(|view_id| {
5346 !state.items_by_leader_view_id.contains_key(&view_id)
5347 }) {
5348 anyhow::Ok(true)
5349 } else {
5350 anyhow::Ok(false)
5351 }
5352 } else {
5353 anyhow::Ok(false)
5354 }
5355 })??;
5356
5357 if should_add_view && let Some(view) = update_active_view.view {
5358 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5359 }
5360 }
5361 proto::update_followers::Variant::UpdateView(update_view) => {
5362 let variant = update_view.variant.context("missing update view variant")?;
5363 let id = update_view.id.context("missing update view id")?;
5364 let mut tasks = Vec::new();
5365 this.update_in(cx, |this, window, cx| {
5366 let project = this.project.clone();
5367 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5368 let view_id = ViewId::from_proto(id.clone())?;
5369 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5370 tasks.push(item.view.apply_update_proto(
5371 &project,
5372 variant.clone(),
5373 window,
5374 cx,
5375 ));
5376 }
5377 }
5378 anyhow::Ok(())
5379 })??;
5380 try_join_all(tasks).await.log_err();
5381 }
5382 }
5383 this.update_in(cx, |this, window, cx| {
5384 this.leader_updated(leader_id, window, cx)
5385 })?;
5386 Ok(())
5387 }
5388
5389 async fn add_view_from_leader(
5390 this: WeakEntity<Self>,
5391 leader_id: PeerId,
5392 view: &proto::View,
5393 cx: &mut AsyncWindowContext,
5394 ) -> Result<()> {
5395 let this = this.upgrade().context("workspace dropped")?;
5396
5397 let Some(id) = view.id.clone() else {
5398 anyhow::bail!("no id for view");
5399 };
5400 let id = ViewId::from_proto(id)?;
5401 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5402
5403 let pane = this.update(cx, |this, _cx| {
5404 let state = this
5405 .follower_states
5406 .get(&leader_id.into())
5407 .context("stopped following")?;
5408 anyhow::Ok(state.pane().clone())
5409 })?;
5410 let existing_item = pane.update_in(cx, |pane, window, cx| {
5411 let client = this.read(cx).client().clone();
5412 pane.items().find_map(|item| {
5413 let item = item.to_followable_item_handle(cx)?;
5414 if item.remote_id(&client, window, cx) == Some(id) {
5415 Some(item)
5416 } else {
5417 None
5418 }
5419 })
5420 })?;
5421 let item = if let Some(existing_item) = existing_item {
5422 existing_item
5423 } else {
5424 let variant = view.variant.clone();
5425 anyhow::ensure!(variant.is_some(), "missing view variant");
5426
5427 let task = cx.update(|window, cx| {
5428 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5429 })?;
5430
5431 let Some(task) = task else {
5432 anyhow::bail!(
5433 "failed to construct view from leader (maybe from a different version of zed?)"
5434 );
5435 };
5436
5437 let mut new_item = task.await?;
5438 pane.update_in(cx, |pane, window, cx| {
5439 let mut item_to_remove = None;
5440 for (ix, item) in pane.items().enumerate() {
5441 if let Some(item) = item.to_followable_item_handle(cx) {
5442 match new_item.dedup(item.as_ref(), window, cx) {
5443 Some(item::Dedup::KeepExisting) => {
5444 new_item =
5445 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5446 break;
5447 }
5448 Some(item::Dedup::ReplaceExisting) => {
5449 item_to_remove = Some((ix, item.item_id()));
5450 break;
5451 }
5452 None => {}
5453 }
5454 }
5455 }
5456
5457 if let Some((ix, id)) = item_to_remove {
5458 pane.remove_item(id, false, false, window, cx);
5459 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5460 }
5461 })?;
5462
5463 new_item
5464 };
5465
5466 this.update_in(cx, |this, window, cx| {
5467 let state = this.follower_states.get_mut(&leader_id.into())?;
5468 item.set_leader_id(Some(leader_id.into()), window, cx);
5469 state.items_by_leader_view_id.insert(
5470 id,
5471 FollowerView {
5472 view: item,
5473 location: panel_id,
5474 },
5475 );
5476
5477 Some(())
5478 })
5479 .context("no follower state")?;
5480
5481 Ok(())
5482 }
5483
5484 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5485 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5486 return;
5487 };
5488
5489 if let Some(agent_location) = self.project.read(cx).agent_location() {
5490 let buffer_entity_id = agent_location.buffer.entity_id();
5491 let view_id = ViewId {
5492 creator: CollaboratorId::Agent,
5493 id: buffer_entity_id.as_u64(),
5494 };
5495 follower_state.active_view_id = Some(view_id);
5496
5497 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5498 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5499 hash_map::Entry::Vacant(entry) => {
5500 let existing_view =
5501 follower_state
5502 .center_pane
5503 .read(cx)
5504 .items()
5505 .find_map(|item| {
5506 let item = item.to_followable_item_handle(cx)?;
5507 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5508 && item.project_item_model_ids(cx).as_slice()
5509 == [buffer_entity_id]
5510 {
5511 Some(item)
5512 } else {
5513 None
5514 }
5515 });
5516 let view = existing_view.or_else(|| {
5517 agent_location.buffer.upgrade().and_then(|buffer| {
5518 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
5519 registry.build_item(buffer, self.project.clone(), None, window, cx)
5520 })?
5521 .to_followable_item_handle(cx)
5522 })
5523 });
5524
5525 view.map(|view| {
5526 entry.insert(FollowerView {
5527 view,
5528 location: None,
5529 })
5530 })
5531 }
5532 };
5533
5534 if let Some(item) = item {
5535 item.view
5536 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
5537 item.view
5538 .update_agent_location(agent_location.position, window, cx);
5539 }
5540 } else {
5541 follower_state.active_view_id = None;
5542 }
5543
5544 self.leader_updated(CollaboratorId::Agent, window, cx);
5545 }
5546
5547 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
5548 let mut is_project_item = true;
5549 let mut update = proto::UpdateActiveView::default();
5550 if window.is_window_active() {
5551 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
5552
5553 if let Some(item) = active_item
5554 && item.item_focus_handle(cx).contains_focused(window, cx)
5555 {
5556 let leader_id = self
5557 .pane_for(&*item)
5558 .and_then(|pane| self.leader_for_pane(&pane));
5559 let leader_peer_id = match leader_id {
5560 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5561 Some(CollaboratorId::Agent) | None => None,
5562 };
5563
5564 if let Some(item) = item.to_followable_item_handle(cx) {
5565 let id = item
5566 .remote_id(&self.app_state.client, window, cx)
5567 .map(|id| id.to_proto());
5568
5569 if let Some(id) = id
5570 && let Some(variant) = item.to_state_proto(window, cx)
5571 {
5572 let view = Some(proto::View {
5573 id,
5574 leader_id: leader_peer_id,
5575 variant: Some(variant),
5576 panel_id: panel_id.map(|id| id as i32),
5577 });
5578
5579 is_project_item = item.is_project_item(window, cx);
5580 update = proto::UpdateActiveView { view };
5581 };
5582 }
5583 }
5584 }
5585
5586 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
5587 if active_view_id != self.last_active_view_id.as_ref() {
5588 self.last_active_view_id = active_view_id.cloned();
5589 self.update_followers(
5590 is_project_item,
5591 proto::update_followers::Variant::UpdateActiveView(update),
5592 window,
5593 cx,
5594 );
5595 }
5596 }
5597
5598 fn active_item_for_followers(
5599 &self,
5600 window: &mut Window,
5601 cx: &mut App,
5602 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
5603 let mut active_item = None;
5604 let mut panel_id = None;
5605 for dock in self.all_docks() {
5606 if dock.focus_handle(cx).contains_focused(window, cx)
5607 && let Some(panel) = dock.read(cx).active_panel()
5608 && let Some(pane) = panel.pane(cx)
5609 && let Some(item) = pane.read(cx).active_item()
5610 {
5611 active_item = Some(item);
5612 panel_id = panel.remote_id();
5613 break;
5614 }
5615 }
5616
5617 if active_item.is_none() {
5618 active_item = self.active_pane().read(cx).active_item();
5619 }
5620 (active_item, panel_id)
5621 }
5622
5623 fn update_followers(
5624 &self,
5625 project_only: bool,
5626 update: proto::update_followers::Variant,
5627 _: &mut Window,
5628 cx: &mut App,
5629 ) -> Option<()> {
5630 // If this update only applies to for followers in the current project,
5631 // then skip it unless this project is shared. If it applies to all
5632 // followers, regardless of project, then set `project_id` to none,
5633 // indicating that it goes to all followers.
5634 let project_id = if project_only {
5635 Some(self.project.read(cx).remote_id()?)
5636 } else {
5637 None
5638 };
5639 self.app_state().workspace_store.update(cx, |store, cx| {
5640 store.update_followers(project_id, update, cx)
5641 })
5642 }
5643
5644 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
5645 self.follower_states.iter().find_map(|(leader_id, state)| {
5646 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
5647 Some(*leader_id)
5648 } else {
5649 None
5650 }
5651 })
5652 }
5653
5654 fn leader_updated(
5655 &mut self,
5656 leader_id: impl Into<CollaboratorId>,
5657 window: &mut Window,
5658 cx: &mut Context<Self>,
5659 ) -> Option<Box<dyn ItemHandle>> {
5660 cx.notify();
5661
5662 let leader_id = leader_id.into();
5663 let (panel_id, item) = match leader_id {
5664 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
5665 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
5666 };
5667
5668 let state = self.follower_states.get(&leader_id)?;
5669 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
5670 let pane;
5671 if let Some(panel_id) = panel_id {
5672 pane = self
5673 .activate_panel_for_proto_id(panel_id, window, cx)?
5674 .pane(cx)?;
5675 let state = self.follower_states.get_mut(&leader_id)?;
5676 state.dock_pane = Some(pane.clone());
5677 } else {
5678 pane = state.center_pane.clone();
5679 let state = self.follower_states.get_mut(&leader_id)?;
5680 if let Some(dock_pane) = state.dock_pane.take() {
5681 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
5682 }
5683 }
5684
5685 pane.update(cx, |pane, cx| {
5686 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
5687 if let Some(index) = pane.index_for_item(item.as_ref()) {
5688 pane.activate_item(index, false, false, window, cx);
5689 } else {
5690 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
5691 }
5692
5693 if focus_active_item {
5694 pane.focus_active_item(window, cx)
5695 }
5696 });
5697
5698 Some(item)
5699 }
5700
5701 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
5702 let state = self.follower_states.get(&CollaboratorId::Agent)?;
5703 let active_view_id = state.active_view_id?;
5704 Some(
5705 state
5706 .items_by_leader_view_id
5707 .get(&active_view_id)?
5708 .view
5709 .boxed_clone(),
5710 )
5711 }
5712
5713 fn active_item_for_peer(
5714 &self,
5715 peer_id: PeerId,
5716 window: &mut Window,
5717 cx: &mut Context<Self>,
5718 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
5719 let call = self.active_call()?;
5720 let room = call.read(cx).room()?.read(cx);
5721 let participant = room.remote_participant_for_peer_id(peer_id)?;
5722 let leader_in_this_app;
5723 let leader_in_this_project;
5724 match participant.location {
5725 call::ParticipantLocation::SharedProject { project_id } => {
5726 leader_in_this_app = true;
5727 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
5728 }
5729 call::ParticipantLocation::UnsharedProject => {
5730 leader_in_this_app = true;
5731 leader_in_this_project = false;
5732 }
5733 call::ParticipantLocation::External => {
5734 leader_in_this_app = false;
5735 leader_in_this_project = false;
5736 }
5737 };
5738 let state = self.follower_states.get(&peer_id.into())?;
5739 let mut item_to_activate = None;
5740 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
5741 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
5742 && (leader_in_this_project || !item.view.is_project_item(window, cx))
5743 {
5744 item_to_activate = Some((item.location, item.view.boxed_clone()));
5745 }
5746 } else if let Some(shared_screen) =
5747 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
5748 {
5749 item_to_activate = Some((None, Box::new(shared_screen)));
5750 }
5751 item_to_activate
5752 }
5753
5754 fn shared_screen_for_peer(
5755 &self,
5756 peer_id: PeerId,
5757 pane: &Entity<Pane>,
5758 window: &mut Window,
5759 cx: &mut App,
5760 ) -> Option<Entity<SharedScreen>> {
5761 let call = self.active_call()?;
5762 let room = call.read(cx).room()?.clone();
5763 let participant = room.read(cx).remote_participant_for_peer_id(peer_id)?;
5764 let track = participant.video_tracks.values().next()?.clone();
5765 let user = participant.user.clone();
5766
5767 for item in pane.read(cx).items_of_type::<SharedScreen>() {
5768 if item.read(cx).peer_id == peer_id {
5769 return Some(item);
5770 }
5771 }
5772
5773 Some(cx.new(|cx| SharedScreen::new(track, peer_id, user.clone(), room.clone(), window, cx)))
5774 }
5775
5776 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5777 if window.is_window_active() {
5778 self.update_active_view_for_followers(window, cx);
5779
5780 if let Some(database_id) = self.database_id {
5781 cx.background_spawn(persistence::DB.update_timestamp(database_id))
5782 .detach();
5783 }
5784 } else {
5785 for pane in &self.panes {
5786 pane.update(cx, |pane, cx| {
5787 if let Some(item) = pane.active_item() {
5788 item.workspace_deactivated(window, cx);
5789 }
5790 for item in pane.items() {
5791 if matches!(
5792 item.workspace_settings(cx).autosave,
5793 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
5794 ) {
5795 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
5796 .detach_and_log_err(cx);
5797 }
5798 }
5799 });
5800 }
5801 }
5802 }
5803
5804 pub fn active_call(&self) -> Option<&Entity<ActiveCall>> {
5805 self.active_call.as_ref().map(|(call, _)| call)
5806 }
5807
5808 fn on_active_call_event(
5809 &mut self,
5810 _: &Entity<ActiveCall>,
5811 event: &call::room::Event,
5812 window: &mut Window,
5813 cx: &mut Context<Self>,
5814 ) {
5815 match event {
5816 call::room::Event::ParticipantLocationChanged { participant_id }
5817 | call::room::Event::RemoteVideoTracksChanged { participant_id } => {
5818 self.leader_updated(participant_id, window, cx);
5819 }
5820 _ => {}
5821 }
5822 }
5823
5824 pub fn database_id(&self) -> Option<WorkspaceId> {
5825 self.database_id
5826 }
5827
5828 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
5829 self.database_id = Some(id);
5830 }
5831
5832 pub fn session_id(&self) -> Option<String> {
5833 self.session_id.clone()
5834 }
5835
5836 /// Bypass the 200ms serialization throttle and write workspace state to
5837 /// the DB immediately. Returns a task the caller can await to ensure the
5838 /// write completes. Used by the quit handler so the most recent state
5839 /// isn't lost to a pending throttle timer when the process exits.
5840 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
5841 self._schedule_serialize_workspace.take();
5842 self._serialize_workspace_task.take();
5843 self.serialize_workspace_internal(window, cx)
5844 }
5845
5846 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
5847 let project = self.project().read(cx);
5848 project
5849 .visible_worktrees(cx)
5850 .map(|worktree| worktree.read(cx).abs_path())
5851 .collect::<Vec<_>>()
5852 }
5853
5854 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
5855 match member {
5856 Member::Axis(PaneAxis { members, .. }) => {
5857 for child in members.iter() {
5858 self.remove_panes(child.clone(), window, cx)
5859 }
5860 }
5861 Member::Pane(pane) => {
5862 self.force_remove_pane(&pane, &None, window, cx);
5863 }
5864 }
5865 }
5866
5867 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
5868 self.session_id.take();
5869 self.serialize_workspace_internal(window, cx)
5870 }
5871
5872 fn force_remove_pane(
5873 &mut self,
5874 pane: &Entity<Pane>,
5875 focus_on: &Option<Entity<Pane>>,
5876 window: &mut Window,
5877 cx: &mut Context<Workspace>,
5878 ) {
5879 self.panes.retain(|p| p != pane);
5880 if let Some(focus_on) = focus_on {
5881 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
5882 } else if self.active_pane() == pane {
5883 self.panes
5884 .last()
5885 .unwrap()
5886 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
5887 }
5888 if self.last_active_center_pane == Some(pane.downgrade()) {
5889 self.last_active_center_pane = None;
5890 }
5891 cx.notify();
5892 }
5893
5894 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5895 if self._schedule_serialize_workspace.is_none() {
5896 self._schedule_serialize_workspace =
5897 Some(cx.spawn_in(window, async move |this, cx| {
5898 cx.background_executor()
5899 .timer(SERIALIZATION_THROTTLE_TIME)
5900 .await;
5901 this.update_in(cx, |this, window, cx| {
5902 this._serialize_workspace_task =
5903 Some(this.serialize_workspace_internal(window, cx));
5904 this._schedule_serialize_workspace.take();
5905 })
5906 .log_err();
5907 }));
5908 }
5909 }
5910
5911 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
5912 let Some(database_id) = self.database_id() else {
5913 return Task::ready(());
5914 };
5915
5916 fn serialize_pane_handle(
5917 pane_handle: &Entity<Pane>,
5918 window: &mut Window,
5919 cx: &mut App,
5920 ) -> SerializedPane {
5921 let (items, active, pinned_count) = {
5922 let pane = pane_handle.read(cx);
5923 let active_item_id = pane.active_item().map(|item| item.item_id());
5924 (
5925 pane.items()
5926 .filter_map(|handle| {
5927 let handle = handle.to_serializable_item_handle(cx)?;
5928
5929 Some(SerializedItem {
5930 kind: Arc::from(handle.serialized_item_kind()),
5931 item_id: handle.item_id().as_u64(),
5932 active: Some(handle.item_id()) == active_item_id,
5933 preview: pane.is_active_preview_item(handle.item_id()),
5934 })
5935 })
5936 .collect::<Vec<_>>(),
5937 pane.has_focus(window, cx),
5938 pane.pinned_count(),
5939 )
5940 };
5941
5942 SerializedPane::new(items, active, pinned_count)
5943 }
5944
5945 fn build_serialized_pane_group(
5946 pane_group: &Member,
5947 window: &mut Window,
5948 cx: &mut App,
5949 ) -> SerializedPaneGroup {
5950 match pane_group {
5951 Member::Axis(PaneAxis {
5952 axis,
5953 members,
5954 flexes,
5955 bounding_boxes: _,
5956 }) => SerializedPaneGroup::Group {
5957 axis: SerializedAxis(*axis),
5958 children: members
5959 .iter()
5960 .map(|member| build_serialized_pane_group(member, window, cx))
5961 .collect::<Vec<_>>(),
5962 flexes: Some(flexes.lock().clone()),
5963 },
5964 Member::Pane(pane_handle) => {
5965 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
5966 }
5967 }
5968 }
5969
5970 fn build_serialized_docks(
5971 this: &Workspace,
5972 window: &mut Window,
5973 cx: &mut App,
5974 ) -> DockStructure {
5975 let left_dock = this.left_dock.read(cx);
5976 let left_visible = left_dock.is_open();
5977 let left_active_panel = left_dock
5978 .active_panel()
5979 .map(|panel| panel.persistent_name().to_string());
5980 let left_dock_zoom = left_dock
5981 .active_panel()
5982 .map(|panel| panel.is_zoomed(window, cx))
5983 .unwrap_or(false);
5984
5985 let right_dock = this.right_dock.read(cx);
5986 let right_visible = right_dock.is_open();
5987 let right_active_panel = right_dock
5988 .active_panel()
5989 .map(|panel| panel.persistent_name().to_string());
5990 let right_dock_zoom = right_dock
5991 .active_panel()
5992 .map(|panel| panel.is_zoomed(window, cx))
5993 .unwrap_or(false);
5994
5995 let bottom_dock = this.bottom_dock.read(cx);
5996 let bottom_visible = bottom_dock.is_open();
5997 let bottom_active_panel = bottom_dock
5998 .active_panel()
5999 .map(|panel| panel.persistent_name().to_string());
6000 let bottom_dock_zoom = bottom_dock
6001 .active_panel()
6002 .map(|panel| panel.is_zoomed(window, cx))
6003 .unwrap_or(false);
6004
6005 DockStructure {
6006 left: DockData {
6007 visible: left_visible,
6008 active_panel: left_active_panel,
6009 zoom: left_dock_zoom,
6010 },
6011 right: DockData {
6012 visible: right_visible,
6013 active_panel: right_active_panel,
6014 zoom: right_dock_zoom,
6015 },
6016 bottom: DockData {
6017 visible: bottom_visible,
6018 active_panel: bottom_active_panel,
6019 zoom: bottom_dock_zoom,
6020 },
6021 }
6022 }
6023
6024 match self.workspace_location(cx) {
6025 WorkspaceLocation::Location(location, paths) => {
6026 let breakpoints = self.project.update(cx, |project, cx| {
6027 project
6028 .breakpoint_store()
6029 .read(cx)
6030 .all_source_breakpoints(cx)
6031 });
6032 let user_toolchains = self
6033 .project
6034 .read(cx)
6035 .user_toolchains(cx)
6036 .unwrap_or_default();
6037
6038 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6039 let docks = build_serialized_docks(self, window, cx);
6040 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6041
6042 let serialized_workspace = SerializedWorkspace {
6043 id: database_id,
6044 location,
6045 paths,
6046 center_group,
6047 window_bounds,
6048 display: Default::default(),
6049 docks,
6050 centered_layout: self.centered_layout,
6051 session_id: self.session_id.clone(),
6052 breakpoints,
6053 window_id: Some(window.window_handle().window_id().as_u64()),
6054 user_toolchains,
6055 };
6056
6057 window.spawn(cx, async move |_| {
6058 persistence::DB.save_workspace(serialized_workspace).await;
6059 })
6060 }
6061 WorkspaceLocation::DetachFromSession => {
6062 let window_bounds = SerializedWindowBounds(window.window_bounds());
6063 let display = window.display(cx).and_then(|d| d.uuid().ok());
6064 // Save dock state for empty local workspaces
6065 let docks = build_serialized_docks(self, window, cx);
6066 window.spawn(cx, async move |_| {
6067 persistence::DB
6068 .set_window_open_status(
6069 database_id,
6070 window_bounds,
6071 display.unwrap_or_default(),
6072 )
6073 .await
6074 .log_err();
6075 persistence::DB
6076 .set_session_id(database_id, None)
6077 .await
6078 .log_err();
6079 persistence::write_default_dock_state(docks).await.log_err();
6080 })
6081 }
6082 WorkspaceLocation::None => {
6083 // Save dock state for empty non-local workspaces
6084 let docks = build_serialized_docks(self, window, cx);
6085 window.spawn(cx, async move |_| {
6086 persistence::write_default_dock_state(docks).await.log_err();
6087 })
6088 }
6089 }
6090 }
6091
6092 fn has_any_items_open(&self, cx: &App) -> bool {
6093 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6094 }
6095
6096 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6097 let paths = PathList::new(&self.root_paths(cx));
6098 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6099 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6100 } else if self.project.read(cx).is_local() {
6101 if !paths.is_empty() || self.has_any_items_open(cx) {
6102 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6103 } else {
6104 WorkspaceLocation::DetachFromSession
6105 }
6106 } else {
6107 WorkspaceLocation::None
6108 }
6109 }
6110
6111 fn update_history(&self, cx: &mut App) {
6112 let Some(id) = self.database_id() else {
6113 return;
6114 };
6115 if !self.project.read(cx).is_local() {
6116 return;
6117 }
6118 if let Some(manager) = HistoryManager::global(cx) {
6119 let paths = PathList::new(&self.root_paths(cx));
6120 manager.update(cx, |this, cx| {
6121 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6122 });
6123 }
6124 }
6125
6126 async fn serialize_items(
6127 this: &WeakEntity<Self>,
6128 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6129 cx: &mut AsyncWindowContext,
6130 ) -> Result<()> {
6131 const CHUNK_SIZE: usize = 200;
6132
6133 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6134
6135 while let Some(items_received) = serializable_items.next().await {
6136 let unique_items =
6137 items_received
6138 .into_iter()
6139 .fold(HashMap::default(), |mut acc, item| {
6140 acc.entry(item.item_id()).or_insert(item);
6141 acc
6142 });
6143
6144 // We use into_iter() here so that the references to the items are moved into
6145 // the tasks and not kept alive while we're sleeping.
6146 for (_, item) in unique_items.into_iter() {
6147 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6148 item.serialize(workspace, false, window, cx)
6149 }) {
6150 cx.background_spawn(async move { task.await.log_err() })
6151 .detach();
6152 }
6153 }
6154
6155 cx.background_executor()
6156 .timer(SERIALIZATION_THROTTLE_TIME)
6157 .await;
6158 }
6159
6160 Ok(())
6161 }
6162
6163 pub(crate) fn enqueue_item_serialization(
6164 &mut self,
6165 item: Box<dyn SerializableItemHandle>,
6166 ) -> Result<()> {
6167 self.serializable_items_tx
6168 .unbounded_send(item)
6169 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6170 }
6171
6172 pub(crate) fn load_workspace(
6173 serialized_workspace: SerializedWorkspace,
6174 paths_to_open: Vec<Option<ProjectPath>>,
6175 window: &mut Window,
6176 cx: &mut Context<Workspace>,
6177 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6178 cx.spawn_in(window, async move |workspace, cx| {
6179 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6180
6181 let mut center_group = None;
6182 let mut center_items = None;
6183
6184 // Traverse the splits tree and add to things
6185 if let Some((group, active_pane, items)) = serialized_workspace
6186 .center_group
6187 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6188 .await
6189 {
6190 center_items = Some(items);
6191 center_group = Some((group, active_pane))
6192 }
6193
6194 let mut items_by_project_path = HashMap::default();
6195 let mut item_ids_by_kind = HashMap::default();
6196 let mut all_deserialized_items = Vec::default();
6197 cx.update(|_, cx| {
6198 for item in center_items.unwrap_or_default().into_iter().flatten() {
6199 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6200 item_ids_by_kind
6201 .entry(serializable_item_handle.serialized_item_kind())
6202 .or_insert(Vec::new())
6203 .push(item.item_id().as_u64() as ItemId);
6204 }
6205
6206 if let Some(project_path) = item.project_path(cx) {
6207 items_by_project_path.insert(project_path, item.clone());
6208 }
6209 all_deserialized_items.push(item);
6210 }
6211 })?;
6212
6213 let opened_items = paths_to_open
6214 .into_iter()
6215 .map(|path_to_open| {
6216 path_to_open
6217 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6218 })
6219 .collect::<Vec<_>>();
6220
6221 // Remove old panes from workspace panes list
6222 workspace.update_in(cx, |workspace, window, cx| {
6223 if let Some((center_group, active_pane)) = center_group {
6224 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6225
6226 // Swap workspace center group
6227 workspace.center = PaneGroup::with_root(center_group);
6228 workspace.center.set_is_center(true);
6229 workspace.center.mark_positions(cx);
6230
6231 if let Some(active_pane) = active_pane {
6232 workspace.set_active_pane(&active_pane, window, cx);
6233 cx.focus_self(window);
6234 } else {
6235 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6236 }
6237 }
6238
6239 let docks = serialized_workspace.docks;
6240
6241 for (dock, serialized_dock) in [
6242 (&mut workspace.right_dock, docks.right),
6243 (&mut workspace.left_dock, docks.left),
6244 (&mut workspace.bottom_dock, docks.bottom),
6245 ]
6246 .iter_mut()
6247 {
6248 dock.update(cx, |dock, cx| {
6249 dock.serialized_dock = Some(serialized_dock.clone());
6250 dock.restore_state(window, cx);
6251 });
6252 }
6253
6254 cx.notify();
6255 })?;
6256
6257 let _ = project
6258 .update(cx, |project, cx| {
6259 project
6260 .breakpoint_store()
6261 .update(cx, |breakpoint_store, cx| {
6262 breakpoint_store
6263 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6264 })
6265 })
6266 .await;
6267
6268 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6269 // after loading the items, we might have different items and in order to avoid
6270 // the database filling up, we delete items that haven't been loaded now.
6271 //
6272 // The items that have been loaded, have been saved after they've been added to the workspace.
6273 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6274 item_ids_by_kind
6275 .into_iter()
6276 .map(|(item_kind, loaded_items)| {
6277 SerializableItemRegistry::cleanup(
6278 item_kind,
6279 serialized_workspace.id,
6280 loaded_items,
6281 window,
6282 cx,
6283 )
6284 .log_err()
6285 })
6286 .collect::<Vec<_>>()
6287 })?;
6288
6289 futures::future::join_all(clean_up_tasks).await;
6290
6291 workspace
6292 .update_in(cx, |workspace, window, cx| {
6293 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6294 workspace.serialize_workspace_internal(window, cx).detach();
6295
6296 // Ensure that we mark the window as edited if we did load dirty items
6297 workspace.update_window_edited(window, cx);
6298 })
6299 .ok();
6300
6301 Ok(opened_items)
6302 })
6303 }
6304
6305 fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6306 self.add_workspace_actions_listeners(div, window, cx)
6307 .on_action(cx.listener(
6308 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6309 for action in &action_sequence.0 {
6310 window.dispatch_action(action.boxed_clone(), cx);
6311 }
6312 },
6313 ))
6314 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6315 .on_action(cx.listener(Self::close_all_items_and_panes))
6316 .on_action(cx.listener(Self::close_item_in_all_panes))
6317 .on_action(cx.listener(Self::save_all))
6318 .on_action(cx.listener(Self::send_keystrokes))
6319 .on_action(cx.listener(Self::add_folder_to_project))
6320 .on_action(cx.listener(Self::follow_next_collaborator))
6321 .on_action(cx.listener(Self::close_window))
6322 .on_action(cx.listener(Self::activate_pane_at_index))
6323 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6324 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6325 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6326 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6327 let pane = workspace.active_pane().clone();
6328 workspace.unfollow_in_pane(&pane, window, cx);
6329 }))
6330 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6331 workspace
6332 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6333 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6334 }))
6335 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6336 workspace
6337 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6338 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6339 }))
6340 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6341 workspace
6342 .save_active_item(SaveIntent::SaveAs, window, cx)
6343 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6344 }))
6345 .on_action(
6346 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6347 workspace.activate_previous_pane(window, cx)
6348 }),
6349 )
6350 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6351 workspace.activate_next_pane(window, cx)
6352 }))
6353 .on_action(
6354 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6355 workspace.activate_next_window(cx)
6356 }),
6357 )
6358 .on_action(
6359 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6360 workspace.activate_previous_window(cx)
6361 }),
6362 )
6363 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6364 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6365 }))
6366 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6367 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6368 }))
6369 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6370 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6371 }))
6372 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6373 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6374 }))
6375 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6376 workspace.activate_next_pane(window, cx)
6377 }))
6378 .on_action(cx.listener(
6379 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6380 workspace.move_item_to_pane_in_direction(action, window, cx)
6381 },
6382 ))
6383 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6384 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6385 }))
6386 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6387 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6388 }))
6389 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6390 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6391 }))
6392 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6393 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6394 }))
6395 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6396 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6397 SplitDirection::Down,
6398 SplitDirection::Up,
6399 SplitDirection::Right,
6400 SplitDirection::Left,
6401 ];
6402 for dir in DIRECTION_PRIORITY {
6403 if workspace.find_pane_in_direction(dir, cx).is_some() {
6404 workspace.swap_pane_in_direction(dir, cx);
6405 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6406 break;
6407 }
6408 }
6409 }))
6410 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6411 workspace.move_pane_to_border(SplitDirection::Left, cx)
6412 }))
6413 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6414 workspace.move_pane_to_border(SplitDirection::Right, cx)
6415 }))
6416 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6417 workspace.move_pane_to_border(SplitDirection::Up, cx)
6418 }))
6419 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6420 workspace.move_pane_to_border(SplitDirection::Down, cx)
6421 }))
6422 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6423 this.toggle_dock(DockPosition::Left, window, cx);
6424 }))
6425 .on_action(cx.listener(
6426 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6427 workspace.toggle_dock(DockPosition::Right, window, cx);
6428 },
6429 ))
6430 .on_action(cx.listener(
6431 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6432 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6433 },
6434 ))
6435 .on_action(cx.listener(
6436 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6437 if !workspace.close_active_dock(window, cx) {
6438 cx.propagate();
6439 }
6440 },
6441 ))
6442 .on_action(
6443 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6444 workspace.close_all_docks(window, cx);
6445 }),
6446 )
6447 .on_action(cx.listener(Self::toggle_all_docks))
6448 .on_action(cx.listener(
6449 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6450 workspace.clear_all_notifications(cx);
6451 },
6452 ))
6453 .on_action(cx.listener(
6454 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6455 workspace.clear_navigation_history(window, cx);
6456 },
6457 ))
6458 .on_action(cx.listener(
6459 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6460 if let Some((notification_id, _)) = workspace.notifications.pop() {
6461 workspace.suppress_notification(¬ification_id, cx);
6462 }
6463 },
6464 ))
6465 .on_action(cx.listener(
6466 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6467 workspace.show_worktree_trust_security_modal(true, window, cx);
6468 },
6469 ))
6470 .on_action(
6471 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6472 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6473 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6474 trusted_worktrees.clear_trusted_paths()
6475 });
6476 let clear_task = persistence::DB.clear_trusted_worktrees();
6477 cx.spawn(async move |_, cx| {
6478 if clear_task.await.log_err().is_some() {
6479 cx.update(|cx| reload(cx));
6480 }
6481 })
6482 .detach();
6483 }
6484 }),
6485 )
6486 .on_action(cx.listener(
6487 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
6488 workspace.reopen_closed_item(window, cx).detach();
6489 },
6490 ))
6491 .on_action(cx.listener(
6492 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
6493 for dock in workspace.all_docks() {
6494 if dock.focus_handle(cx).contains_focused(window, cx) {
6495 let Some(panel) = dock.read(cx).active_panel() else {
6496 return;
6497 };
6498
6499 // Set to `None`, then the size will fall back to the default.
6500 panel.clone().set_size(None, window, cx);
6501
6502 return;
6503 }
6504 }
6505 },
6506 ))
6507 .on_action(cx.listener(
6508 |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
6509 for dock in workspace.all_docks() {
6510 if let Some(panel) = dock.read(cx).visible_panel() {
6511 // Set to `None`, then the size will fall back to the default.
6512 panel.clone().set_size(None, window, cx);
6513 }
6514 }
6515 },
6516 ))
6517 .on_action(cx.listener(
6518 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
6519 adjust_active_dock_size_by_px(
6520 px_with_ui_font_fallback(act.px, cx),
6521 workspace,
6522 window,
6523 cx,
6524 );
6525 },
6526 ))
6527 .on_action(cx.listener(
6528 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
6529 adjust_active_dock_size_by_px(
6530 px_with_ui_font_fallback(act.px, cx) * -1.,
6531 workspace,
6532 window,
6533 cx,
6534 );
6535 },
6536 ))
6537 .on_action(cx.listener(
6538 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
6539 adjust_open_docks_size_by_px(
6540 px_with_ui_font_fallback(act.px, cx),
6541 workspace,
6542 window,
6543 cx,
6544 );
6545 },
6546 ))
6547 .on_action(cx.listener(
6548 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
6549 adjust_open_docks_size_by_px(
6550 px_with_ui_font_fallback(act.px, cx) * -1.,
6551 workspace,
6552 window,
6553 cx,
6554 );
6555 },
6556 ))
6557 .on_action(cx.listener(Workspace::toggle_centered_layout))
6558 .on_action(cx.listener(
6559 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
6560 if let Some(active_dock) = workspace.active_dock(window, cx) {
6561 let dock = active_dock.read(cx);
6562 if let Some(active_panel) = dock.active_panel() {
6563 if active_panel.pane(cx).is_none() {
6564 let mut recent_pane: Option<Entity<Pane>> = None;
6565 let mut recent_timestamp = 0;
6566 for pane_handle in workspace.panes() {
6567 let pane = pane_handle.read(cx);
6568 for entry in pane.activation_history() {
6569 if entry.timestamp > recent_timestamp {
6570 recent_timestamp = entry.timestamp;
6571 recent_pane = Some(pane_handle.clone());
6572 }
6573 }
6574 }
6575
6576 if let Some(pane) = recent_pane {
6577 pane.update(cx, |pane, cx| {
6578 let current_index = pane.active_item_index();
6579 let items_len = pane.items_len();
6580 if items_len > 0 {
6581 let next_index = if current_index + 1 < items_len {
6582 current_index + 1
6583 } else {
6584 0
6585 };
6586 pane.activate_item(
6587 next_index, false, false, window, cx,
6588 );
6589 }
6590 });
6591 return;
6592 }
6593 }
6594 }
6595 }
6596 cx.propagate();
6597 },
6598 ))
6599 .on_action(cx.listener(
6600 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
6601 if let Some(active_dock) = workspace.active_dock(window, cx) {
6602 let dock = active_dock.read(cx);
6603 if let Some(active_panel) = dock.active_panel() {
6604 if active_panel.pane(cx).is_none() {
6605 let mut recent_pane: Option<Entity<Pane>> = None;
6606 let mut recent_timestamp = 0;
6607 for pane_handle in workspace.panes() {
6608 let pane = pane_handle.read(cx);
6609 for entry in pane.activation_history() {
6610 if entry.timestamp > recent_timestamp {
6611 recent_timestamp = entry.timestamp;
6612 recent_pane = Some(pane_handle.clone());
6613 }
6614 }
6615 }
6616
6617 if let Some(pane) = recent_pane {
6618 pane.update(cx, |pane, cx| {
6619 let current_index = pane.active_item_index();
6620 let items_len = pane.items_len();
6621 if items_len > 0 {
6622 let prev_index = if current_index > 0 {
6623 current_index - 1
6624 } else {
6625 items_len.saturating_sub(1)
6626 };
6627 pane.activate_item(
6628 prev_index, false, false, window, cx,
6629 );
6630 }
6631 });
6632 return;
6633 }
6634 }
6635 }
6636 }
6637 cx.propagate();
6638 },
6639 ))
6640 .on_action(cx.listener(
6641 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
6642 if let Some(active_dock) = workspace.active_dock(window, cx) {
6643 let dock = active_dock.read(cx);
6644 if let Some(active_panel) = dock.active_panel() {
6645 if active_panel.pane(cx).is_none() {
6646 let active_pane = workspace.active_pane().clone();
6647 active_pane.update(cx, |pane, cx| {
6648 pane.close_active_item(action, window, cx)
6649 .detach_and_log_err(cx);
6650 });
6651 return;
6652 }
6653 }
6654 }
6655 cx.propagate();
6656 },
6657 ))
6658 .on_action(
6659 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
6660 let pane = workspace.active_pane().clone();
6661 if let Some(item) = pane.read(cx).active_item() {
6662 item.toggle_read_only(window, cx);
6663 }
6664 }),
6665 )
6666 .on_action(cx.listener(Workspace::cancel))
6667 }
6668
6669 #[cfg(any(test, feature = "test-support"))]
6670 pub fn set_random_database_id(&mut self) {
6671 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
6672 }
6673
6674 #[cfg(any(test, feature = "test-support"))]
6675 pub(crate) fn test_new(
6676 project: Entity<Project>,
6677 window: &mut Window,
6678 cx: &mut Context<Self>,
6679 ) -> Self {
6680 use node_runtime::NodeRuntime;
6681 use session::Session;
6682
6683 let client = project.read(cx).client();
6684 let user_store = project.read(cx).user_store();
6685 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
6686 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
6687 window.activate_window();
6688 let app_state = Arc::new(AppState {
6689 languages: project.read(cx).languages().clone(),
6690 workspace_store,
6691 client,
6692 user_store,
6693 fs: project.read(cx).fs().clone(),
6694 build_window_options: |_, _| Default::default(),
6695 node_runtime: NodeRuntime::unavailable(),
6696 session,
6697 });
6698 let workspace = Self::new(Default::default(), project, app_state, window, cx);
6699 workspace
6700 .active_pane
6701 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6702 workspace
6703 }
6704
6705 pub fn register_action<A: Action>(
6706 &mut self,
6707 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
6708 ) -> &mut Self {
6709 let callback = Arc::new(callback);
6710
6711 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
6712 let callback = callback.clone();
6713 div.on_action(cx.listener(move |workspace, event, window, cx| {
6714 (callback)(workspace, event, window, cx)
6715 }))
6716 }));
6717 self
6718 }
6719 pub fn register_action_renderer(
6720 &mut self,
6721 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
6722 ) -> &mut Self {
6723 self.workspace_actions.push(Box::new(callback));
6724 self
6725 }
6726
6727 fn add_workspace_actions_listeners(
6728 &self,
6729 mut div: Div,
6730 window: &mut Window,
6731 cx: &mut Context<Self>,
6732 ) -> Div {
6733 for action in self.workspace_actions.iter() {
6734 div = (action)(div, self, window, cx)
6735 }
6736 div
6737 }
6738
6739 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
6740 self.modal_layer.read(cx).has_active_modal()
6741 }
6742
6743 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
6744 self.modal_layer.read(cx).active_modal()
6745 }
6746
6747 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
6748 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
6749 /// If no modal is active, the new modal will be shown.
6750 ///
6751 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
6752 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
6753 /// will not be shown.
6754 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
6755 where
6756 B: FnOnce(&mut Window, &mut Context<V>) -> V,
6757 {
6758 self.modal_layer.update(cx, |modal_layer, cx| {
6759 modal_layer.toggle_modal(window, cx, build)
6760 })
6761 }
6762
6763 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
6764 self.modal_layer
6765 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
6766 }
6767
6768 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
6769 self.toast_layer
6770 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
6771 }
6772
6773 pub fn toggle_centered_layout(
6774 &mut self,
6775 _: &ToggleCenteredLayout,
6776 _: &mut Window,
6777 cx: &mut Context<Self>,
6778 ) {
6779 self.centered_layout = !self.centered_layout;
6780 if let Some(database_id) = self.database_id() {
6781 cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
6782 .detach_and_log_err(cx);
6783 }
6784 cx.notify();
6785 }
6786
6787 fn adjust_padding(padding: Option<f32>) -> f32 {
6788 padding
6789 .unwrap_or(CenteredPaddingSettings::default().0)
6790 .clamp(
6791 CenteredPaddingSettings::MIN_PADDING,
6792 CenteredPaddingSettings::MAX_PADDING,
6793 )
6794 }
6795
6796 fn render_dock(
6797 &self,
6798 position: DockPosition,
6799 dock: &Entity<Dock>,
6800 window: &mut Window,
6801 cx: &mut App,
6802 ) -> Option<Div> {
6803 if self.zoomed_position == Some(position) {
6804 return None;
6805 }
6806
6807 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
6808 let pane = panel.pane(cx)?;
6809 let follower_states = &self.follower_states;
6810 leader_border_for_pane(follower_states, &pane, window, cx)
6811 });
6812
6813 Some(
6814 div()
6815 .flex()
6816 .flex_none()
6817 .overflow_hidden()
6818 .child(dock.clone())
6819 .children(leader_border),
6820 )
6821 }
6822
6823 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
6824 window
6825 .root::<MultiWorkspace>()
6826 .flatten()
6827 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
6828 }
6829
6830 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
6831 self.zoomed.as_ref()
6832 }
6833
6834 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
6835 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
6836 return;
6837 };
6838 let windows = cx.windows();
6839 let next_window =
6840 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
6841 || {
6842 windows
6843 .iter()
6844 .cycle()
6845 .skip_while(|window| window.window_id() != current_window_id)
6846 .nth(1)
6847 },
6848 );
6849
6850 if let Some(window) = next_window {
6851 window
6852 .update(cx, |_, window, _| window.activate_window())
6853 .ok();
6854 }
6855 }
6856
6857 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
6858 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
6859 return;
6860 };
6861 let windows = cx.windows();
6862 let prev_window =
6863 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
6864 || {
6865 windows
6866 .iter()
6867 .rev()
6868 .cycle()
6869 .skip_while(|window| window.window_id() != current_window_id)
6870 .nth(1)
6871 },
6872 );
6873
6874 if let Some(window) = prev_window {
6875 window
6876 .update(cx, |_, window, _| window.activate_window())
6877 .ok();
6878 }
6879 }
6880
6881 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
6882 if cx.stop_active_drag(window) {
6883 } else if let Some((notification_id, _)) = self.notifications.pop() {
6884 dismiss_app_notification(¬ification_id, cx);
6885 } else {
6886 cx.propagate();
6887 }
6888 }
6889
6890 fn adjust_dock_size_by_px(
6891 &mut self,
6892 panel_size: Pixels,
6893 dock_pos: DockPosition,
6894 px: Pixels,
6895 window: &mut Window,
6896 cx: &mut Context<Self>,
6897 ) {
6898 match dock_pos {
6899 DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
6900 DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
6901 DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
6902 }
6903 }
6904
6905 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6906 let size = new_size.min(self.bounds.right() - RESIZE_HANDLE_SIZE);
6907
6908 self.left_dock.update(cx, |left_dock, cx| {
6909 if WorkspaceSettings::get_global(cx)
6910 .resize_all_panels_in_dock
6911 .contains(&DockPosition::Left)
6912 {
6913 left_dock.resize_all_panels(Some(size), window, cx);
6914 } else {
6915 left_dock.resize_active_panel(Some(size), window, cx);
6916 }
6917 });
6918 }
6919
6920 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6921 let mut size = new_size.max(self.bounds.left() - RESIZE_HANDLE_SIZE);
6922 self.left_dock.read_with(cx, |left_dock, cx| {
6923 let left_dock_size = left_dock
6924 .active_panel_size(window, cx)
6925 .unwrap_or(Pixels::ZERO);
6926 if left_dock_size + size > self.bounds.right() {
6927 size = self.bounds.right() - left_dock_size
6928 }
6929 });
6930 self.right_dock.update(cx, |right_dock, cx| {
6931 if WorkspaceSettings::get_global(cx)
6932 .resize_all_panels_in_dock
6933 .contains(&DockPosition::Right)
6934 {
6935 right_dock.resize_all_panels(Some(size), window, cx);
6936 } else {
6937 right_dock.resize_active_panel(Some(size), window, cx);
6938 }
6939 });
6940 }
6941
6942 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6943 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
6944 self.bottom_dock.update(cx, |bottom_dock, cx| {
6945 if WorkspaceSettings::get_global(cx)
6946 .resize_all_panels_in_dock
6947 .contains(&DockPosition::Bottom)
6948 {
6949 bottom_dock.resize_all_panels(Some(size), window, cx);
6950 } else {
6951 bottom_dock.resize_active_panel(Some(size), window, cx);
6952 }
6953 });
6954 }
6955
6956 fn toggle_edit_predictions_all_files(
6957 &mut self,
6958 _: &ToggleEditPrediction,
6959 _window: &mut Window,
6960 cx: &mut Context<Self>,
6961 ) {
6962 let fs = self.project().read(cx).fs().clone();
6963 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
6964 update_settings_file(fs, cx, move |file, _| {
6965 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
6966 });
6967 }
6968
6969 pub fn show_worktree_trust_security_modal(
6970 &mut self,
6971 toggle: bool,
6972 window: &mut Window,
6973 cx: &mut Context<Self>,
6974 ) {
6975 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
6976 if toggle {
6977 security_modal.update(cx, |security_modal, cx| {
6978 security_modal.dismiss(cx);
6979 })
6980 } else {
6981 security_modal.update(cx, |security_modal, cx| {
6982 security_modal.refresh_restricted_paths(cx);
6983 });
6984 }
6985 } else {
6986 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
6987 .map(|trusted_worktrees| {
6988 trusted_worktrees
6989 .read(cx)
6990 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
6991 })
6992 .unwrap_or(false);
6993 if has_restricted_worktrees {
6994 let project = self.project().read(cx);
6995 let remote_host = project
6996 .remote_connection_options(cx)
6997 .map(RemoteHostLocation::from);
6998 let worktree_store = project.worktree_store().downgrade();
6999 self.toggle_modal(window, cx, |_, cx| {
7000 SecurityModal::new(worktree_store, remote_host, cx)
7001 });
7002 }
7003 }
7004 }
7005}
7006
7007fn leader_border_for_pane(
7008 follower_states: &HashMap<CollaboratorId, FollowerState>,
7009 pane: &Entity<Pane>,
7010 _: &Window,
7011 cx: &App,
7012) -> Option<Div> {
7013 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7014 if state.pane() == pane {
7015 Some((*leader_id, state))
7016 } else {
7017 None
7018 }
7019 })?;
7020
7021 let mut leader_color = match leader_id {
7022 CollaboratorId::PeerId(leader_peer_id) => {
7023 let room = ActiveCall::try_global(cx)?.read(cx).room()?.read(cx);
7024 let leader = room.remote_participant_for_peer_id(leader_peer_id)?;
7025
7026 cx.theme()
7027 .players()
7028 .color_for_participant(leader.participant_index.0)
7029 .cursor
7030 }
7031 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7032 };
7033 leader_color.fade_out(0.3);
7034 Some(
7035 div()
7036 .absolute()
7037 .size_full()
7038 .left_0()
7039 .top_0()
7040 .border_2()
7041 .border_color(leader_color),
7042 )
7043}
7044
7045fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7046 ZED_WINDOW_POSITION
7047 .zip(*ZED_WINDOW_SIZE)
7048 .map(|(position, size)| Bounds {
7049 origin: position,
7050 size,
7051 })
7052}
7053
7054fn open_items(
7055 serialized_workspace: Option<SerializedWorkspace>,
7056 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7057 window: &mut Window,
7058 cx: &mut Context<Workspace>,
7059) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7060 let restored_items = serialized_workspace.map(|serialized_workspace| {
7061 Workspace::load_workspace(
7062 serialized_workspace,
7063 project_paths_to_open
7064 .iter()
7065 .map(|(_, project_path)| project_path)
7066 .cloned()
7067 .collect(),
7068 window,
7069 cx,
7070 )
7071 });
7072
7073 cx.spawn_in(window, async move |workspace, cx| {
7074 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7075
7076 if let Some(restored_items) = restored_items {
7077 let restored_items = restored_items.await?;
7078
7079 let restored_project_paths = restored_items
7080 .iter()
7081 .filter_map(|item| {
7082 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7083 .ok()
7084 .flatten()
7085 })
7086 .collect::<HashSet<_>>();
7087
7088 for restored_item in restored_items {
7089 opened_items.push(restored_item.map(Ok));
7090 }
7091
7092 project_paths_to_open
7093 .iter_mut()
7094 .for_each(|(_, project_path)| {
7095 if let Some(project_path_to_open) = project_path
7096 && restored_project_paths.contains(project_path_to_open)
7097 {
7098 *project_path = None;
7099 }
7100 });
7101 } else {
7102 for _ in 0..project_paths_to_open.len() {
7103 opened_items.push(None);
7104 }
7105 }
7106 assert!(opened_items.len() == project_paths_to_open.len());
7107
7108 let tasks =
7109 project_paths_to_open
7110 .into_iter()
7111 .enumerate()
7112 .map(|(ix, (abs_path, project_path))| {
7113 let workspace = workspace.clone();
7114 cx.spawn(async move |cx| {
7115 let file_project_path = project_path?;
7116 let abs_path_task = workspace.update(cx, |workspace, cx| {
7117 workspace.project().update(cx, |project, cx| {
7118 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7119 })
7120 });
7121
7122 // We only want to open file paths here. If one of the items
7123 // here is a directory, it was already opened further above
7124 // with a `find_or_create_worktree`.
7125 if let Ok(task) = abs_path_task
7126 && task.await.is_none_or(|p| p.is_file())
7127 {
7128 return Some((
7129 ix,
7130 workspace
7131 .update_in(cx, |workspace, window, cx| {
7132 workspace.open_path(
7133 file_project_path,
7134 None,
7135 true,
7136 window,
7137 cx,
7138 )
7139 })
7140 .log_err()?
7141 .await,
7142 ));
7143 }
7144 None
7145 })
7146 });
7147
7148 let tasks = tasks.collect::<Vec<_>>();
7149
7150 let tasks = futures::future::join_all(tasks);
7151 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7152 opened_items[ix] = Some(path_open_result);
7153 }
7154
7155 Ok(opened_items)
7156 })
7157}
7158
7159enum ActivateInDirectionTarget {
7160 Pane(Entity<Pane>),
7161 Dock(Entity<Dock>),
7162}
7163
7164fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7165 window
7166 .update(cx, |multi_workspace, _, cx| {
7167 let workspace = multi_workspace.workspace().clone();
7168 workspace.update(cx, |workspace, cx| {
7169 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7170 struct DatabaseFailedNotification;
7171
7172 workspace.show_notification(
7173 NotificationId::unique::<DatabaseFailedNotification>(),
7174 cx,
7175 |cx| {
7176 cx.new(|cx| {
7177 MessageNotification::new("Failed to load the database file.", cx)
7178 .primary_message("File an Issue")
7179 .primary_icon(IconName::Plus)
7180 .primary_on_click(|window, cx| {
7181 window.dispatch_action(Box::new(FileBugReport), cx)
7182 })
7183 })
7184 },
7185 );
7186 }
7187 });
7188 })
7189 .log_err();
7190}
7191
7192fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7193 if val == 0 {
7194 ThemeSettings::get_global(cx).ui_font_size(cx)
7195 } else {
7196 px(val as f32)
7197 }
7198}
7199
7200fn adjust_active_dock_size_by_px(
7201 px: Pixels,
7202 workspace: &mut Workspace,
7203 window: &mut Window,
7204 cx: &mut Context<Workspace>,
7205) {
7206 let Some(active_dock) = workspace
7207 .all_docks()
7208 .into_iter()
7209 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7210 else {
7211 return;
7212 };
7213 let dock = active_dock.read(cx);
7214 let Some(panel_size) = dock.active_panel_size(window, cx) else {
7215 return;
7216 };
7217 let dock_pos = dock.position();
7218 workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
7219}
7220
7221fn adjust_open_docks_size_by_px(
7222 px: Pixels,
7223 workspace: &mut Workspace,
7224 window: &mut Window,
7225 cx: &mut Context<Workspace>,
7226) {
7227 let docks = workspace
7228 .all_docks()
7229 .into_iter()
7230 .filter_map(|dock| {
7231 if dock.read(cx).is_open() {
7232 let dock = dock.read(cx);
7233 let panel_size = dock.active_panel_size(window, cx)?;
7234 let dock_pos = dock.position();
7235 Some((panel_size, dock_pos, px))
7236 } else {
7237 None
7238 }
7239 })
7240 .collect::<Vec<_>>();
7241
7242 docks
7243 .into_iter()
7244 .for_each(|(panel_size, dock_pos, offset)| {
7245 workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
7246 });
7247}
7248
7249impl Focusable for Workspace {
7250 fn focus_handle(&self, cx: &App) -> FocusHandle {
7251 self.active_pane.focus_handle(cx)
7252 }
7253}
7254
7255#[derive(Clone)]
7256struct DraggedDock(DockPosition);
7257
7258impl Render for DraggedDock {
7259 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7260 gpui::Empty
7261 }
7262}
7263
7264impl Render for Workspace {
7265 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7266 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7267 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7268 log::info!("Rendered first frame");
7269 }
7270 let mut context = KeyContext::new_with_defaults();
7271 context.add("Workspace");
7272 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
7273 if let Some(status) = self
7274 .debugger_provider
7275 .as_ref()
7276 .and_then(|provider| provider.active_thread_state(cx))
7277 {
7278 match status {
7279 ThreadStatus::Running | ThreadStatus::Stepping => {
7280 context.add("debugger_running");
7281 }
7282 ThreadStatus::Stopped => context.add("debugger_stopped"),
7283 ThreadStatus::Exited | ThreadStatus::Ended => {}
7284 }
7285 }
7286
7287 if self.left_dock.read(cx).is_open() {
7288 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
7289 context.set("left_dock", active_panel.panel_key());
7290 }
7291 }
7292
7293 if self.right_dock.read(cx).is_open() {
7294 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
7295 context.set("right_dock", active_panel.panel_key());
7296 }
7297 }
7298
7299 if self.bottom_dock.read(cx).is_open() {
7300 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
7301 context.set("bottom_dock", active_panel.panel_key());
7302 }
7303 }
7304
7305 let centered_layout = self.centered_layout
7306 && self.center.panes().len() == 1
7307 && self.active_item(cx).is_some();
7308 let render_padding = |size| {
7309 (size > 0.0).then(|| {
7310 div()
7311 .h_full()
7312 .w(relative(size))
7313 .bg(cx.theme().colors().editor_background)
7314 .border_color(cx.theme().colors().pane_group_border)
7315 })
7316 };
7317 let paddings = if centered_layout {
7318 let settings = WorkspaceSettings::get_global(cx).centered_layout;
7319 (
7320 render_padding(Self::adjust_padding(
7321 settings.left_padding.map(|padding| padding.0),
7322 )),
7323 render_padding(Self::adjust_padding(
7324 settings.right_padding.map(|padding| padding.0),
7325 )),
7326 )
7327 } else {
7328 (None, None)
7329 };
7330 let ui_font = theme::setup_ui_font(window, cx);
7331
7332 let theme = cx.theme().clone();
7333 let colors = theme.colors();
7334 let notification_entities = self
7335 .notifications
7336 .iter()
7337 .map(|(_, notification)| notification.entity_id())
7338 .collect::<Vec<_>>();
7339 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
7340
7341 self.actions(div(), window, cx)
7342 .key_context(context)
7343 .relative()
7344 .size_full()
7345 .flex()
7346 .flex_col()
7347 .font(ui_font)
7348 .gap_0()
7349 .justify_start()
7350 .items_start()
7351 .text_color(colors.text)
7352 .overflow_hidden()
7353 .children(self.titlebar_item.clone())
7354 .on_modifiers_changed(move |_, _, cx| {
7355 for &id in ¬ification_entities {
7356 cx.notify(id);
7357 }
7358 })
7359 .child(
7360 div()
7361 .size_full()
7362 .relative()
7363 .flex_1()
7364 .flex()
7365 .flex_col()
7366 .child(
7367 div()
7368 .id("workspace")
7369 .bg(colors.background)
7370 .relative()
7371 .flex_1()
7372 .w_full()
7373 .flex()
7374 .flex_col()
7375 .overflow_hidden()
7376 .border_t_1()
7377 .border_b_1()
7378 .border_color(colors.border)
7379 .child({
7380 let this = cx.entity();
7381 canvas(
7382 move |bounds, window, cx| {
7383 this.update(cx, |this, cx| {
7384 let bounds_changed = this.bounds != bounds;
7385 this.bounds = bounds;
7386
7387 if bounds_changed {
7388 this.left_dock.update(cx, |dock, cx| {
7389 dock.clamp_panel_size(
7390 bounds.size.width,
7391 window,
7392 cx,
7393 )
7394 });
7395
7396 this.right_dock.update(cx, |dock, cx| {
7397 dock.clamp_panel_size(
7398 bounds.size.width,
7399 window,
7400 cx,
7401 )
7402 });
7403
7404 this.bottom_dock.update(cx, |dock, cx| {
7405 dock.clamp_panel_size(
7406 bounds.size.height,
7407 window,
7408 cx,
7409 )
7410 });
7411 }
7412 })
7413 },
7414 |_, _, _, _| {},
7415 )
7416 .absolute()
7417 .size_full()
7418 })
7419 .when(self.zoomed.is_none(), |this| {
7420 this.on_drag_move(cx.listener(
7421 move |workspace,
7422 e: &DragMoveEvent<DraggedDock>,
7423 window,
7424 cx| {
7425 if workspace.previous_dock_drag_coordinates
7426 != Some(e.event.position)
7427 {
7428 workspace.previous_dock_drag_coordinates =
7429 Some(e.event.position);
7430 match e.drag(cx).0 {
7431 DockPosition::Left => {
7432 workspace.resize_left_dock(
7433 e.event.position.x
7434 - workspace.bounds.left(),
7435 window,
7436 cx,
7437 );
7438 }
7439 DockPosition::Right => {
7440 workspace.resize_right_dock(
7441 workspace.bounds.right()
7442 - e.event.position.x,
7443 window,
7444 cx,
7445 );
7446 }
7447 DockPosition::Bottom => {
7448 workspace.resize_bottom_dock(
7449 workspace.bounds.bottom()
7450 - e.event.position.y,
7451 window,
7452 cx,
7453 );
7454 }
7455 };
7456 workspace.serialize_workspace(window, cx);
7457 }
7458 },
7459 ))
7460
7461 })
7462 .child({
7463 match bottom_dock_layout {
7464 BottomDockLayout::Full => div()
7465 .flex()
7466 .flex_col()
7467 .h_full()
7468 .child(
7469 div()
7470 .flex()
7471 .flex_row()
7472 .flex_1()
7473 .overflow_hidden()
7474 .children(self.render_dock(
7475 DockPosition::Left,
7476 &self.left_dock,
7477 window,
7478 cx,
7479 ))
7480
7481 .child(
7482 div()
7483 .flex()
7484 .flex_col()
7485 .flex_1()
7486 .overflow_hidden()
7487 .child(
7488 h_flex()
7489 .flex_1()
7490 .when_some(
7491 paddings.0,
7492 |this, p| {
7493 this.child(
7494 p.border_r_1(),
7495 )
7496 },
7497 )
7498 .child(self.center.render(
7499 self.zoomed.as_ref(),
7500 &PaneRenderContext {
7501 follower_states:
7502 &self.follower_states,
7503 active_call: self.active_call(),
7504 active_pane: &self.active_pane,
7505 app_state: &self.app_state,
7506 project: &self.project,
7507 workspace: &self.weak_self,
7508 },
7509 window,
7510 cx,
7511 ))
7512 .when_some(
7513 paddings.1,
7514 |this, p| {
7515 this.child(
7516 p.border_l_1(),
7517 )
7518 },
7519 ),
7520 ),
7521 )
7522
7523 .children(self.render_dock(
7524 DockPosition::Right,
7525 &self.right_dock,
7526 window,
7527 cx,
7528 )),
7529 )
7530 .child(div().w_full().children(self.render_dock(
7531 DockPosition::Bottom,
7532 &self.bottom_dock,
7533 window,
7534 cx
7535 ))),
7536
7537 BottomDockLayout::LeftAligned => div()
7538 .flex()
7539 .flex_row()
7540 .h_full()
7541 .child(
7542 div()
7543 .flex()
7544 .flex_col()
7545 .flex_1()
7546 .h_full()
7547 .child(
7548 div()
7549 .flex()
7550 .flex_row()
7551 .flex_1()
7552 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
7553
7554 .child(
7555 div()
7556 .flex()
7557 .flex_col()
7558 .flex_1()
7559 .overflow_hidden()
7560 .child(
7561 h_flex()
7562 .flex_1()
7563 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7564 .child(self.center.render(
7565 self.zoomed.as_ref(),
7566 &PaneRenderContext {
7567 follower_states:
7568 &self.follower_states,
7569 active_call: self.active_call(),
7570 active_pane: &self.active_pane,
7571 app_state: &self.app_state,
7572 project: &self.project,
7573 workspace: &self.weak_self,
7574 },
7575 window,
7576 cx,
7577 ))
7578 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7579 )
7580 )
7581
7582 )
7583 .child(
7584 div()
7585 .w_full()
7586 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7587 ),
7588 )
7589 .children(self.render_dock(
7590 DockPosition::Right,
7591 &self.right_dock,
7592 window,
7593 cx,
7594 )),
7595
7596 BottomDockLayout::RightAligned => div()
7597 .flex()
7598 .flex_row()
7599 .h_full()
7600 .children(self.render_dock(
7601 DockPosition::Left,
7602 &self.left_dock,
7603 window,
7604 cx,
7605 ))
7606
7607 .child(
7608 div()
7609 .flex()
7610 .flex_col()
7611 .flex_1()
7612 .h_full()
7613 .child(
7614 div()
7615 .flex()
7616 .flex_row()
7617 .flex_1()
7618 .child(
7619 div()
7620 .flex()
7621 .flex_col()
7622 .flex_1()
7623 .overflow_hidden()
7624 .child(
7625 h_flex()
7626 .flex_1()
7627 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7628 .child(self.center.render(
7629 self.zoomed.as_ref(),
7630 &PaneRenderContext {
7631 follower_states:
7632 &self.follower_states,
7633 active_call: self.active_call(),
7634 active_pane: &self.active_pane,
7635 app_state: &self.app_state,
7636 project: &self.project,
7637 workspace: &self.weak_self,
7638 },
7639 window,
7640 cx,
7641 ))
7642 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7643 )
7644 )
7645
7646 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
7647 )
7648 .child(
7649 div()
7650 .w_full()
7651 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7652 ),
7653 ),
7654
7655 BottomDockLayout::Contained => div()
7656 .flex()
7657 .flex_row()
7658 .h_full()
7659 .children(self.render_dock(
7660 DockPosition::Left,
7661 &self.left_dock,
7662 window,
7663 cx,
7664 ))
7665
7666 .child(
7667 div()
7668 .flex()
7669 .flex_col()
7670 .flex_1()
7671 .overflow_hidden()
7672 .child(
7673 h_flex()
7674 .flex_1()
7675 .when_some(paddings.0, |this, p| {
7676 this.child(p.border_r_1())
7677 })
7678 .child(self.center.render(
7679 self.zoomed.as_ref(),
7680 &PaneRenderContext {
7681 follower_states:
7682 &self.follower_states,
7683 active_call: self.active_call(),
7684 active_pane: &self.active_pane,
7685 app_state: &self.app_state,
7686 project: &self.project,
7687 workspace: &self.weak_self,
7688 },
7689 window,
7690 cx,
7691 ))
7692 .when_some(paddings.1, |this, p| {
7693 this.child(p.border_l_1())
7694 }),
7695 )
7696 .children(self.render_dock(
7697 DockPosition::Bottom,
7698 &self.bottom_dock,
7699 window,
7700 cx,
7701 )),
7702 )
7703
7704 .children(self.render_dock(
7705 DockPosition::Right,
7706 &self.right_dock,
7707 window,
7708 cx,
7709 )),
7710 }
7711 })
7712 .children(self.zoomed.as_ref().and_then(|view| {
7713 let zoomed_view = view.upgrade()?;
7714 let div = div()
7715 .occlude()
7716 .absolute()
7717 .overflow_hidden()
7718 .border_color(colors.border)
7719 .bg(colors.background)
7720 .child(zoomed_view)
7721 .inset_0()
7722 .shadow_lg();
7723
7724 if !WorkspaceSettings::get_global(cx).zoomed_padding {
7725 return Some(div);
7726 }
7727
7728 Some(match self.zoomed_position {
7729 Some(DockPosition::Left) => div.right_2().border_r_1(),
7730 Some(DockPosition::Right) => div.left_2().border_l_1(),
7731 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
7732 None => {
7733 div.top_2().bottom_2().left_2().right_2().border_1()
7734 }
7735 })
7736 }))
7737 .children(self.render_notifications(window, cx)),
7738 )
7739 .when(self.status_bar_visible(cx), |parent| {
7740 parent.child(self.status_bar.clone())
7741 })
7742 .child(self.modal_layer.clone())
7743 .child(self.toast_layer.clone()),
7744 )
7745 }
7746}
7747
7748impl WorkspaceStore {
7749 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
7750 Self {
7751 workspaces: Default::default(),
7752 _subscriptions: vec![
7753 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
7754 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
7755 ],
7756 client,
7757 }
7758 }
7759
7760 pub fn update_followers(
7761 &self,
7762 project_id: Option<u64>,
7763 update: proto::update_followers::Variant,
7764 cx: &App,
7765 ) -> Option<()> {
7766 let active_call = ActiveCall::try_global(cx)?;
7767 let room_id = active_call.read(cx).room()?.read(cx).id();
7768 self.client
7769 .send(proto::UpdateFollowers {
7770 room_id,
7771 project_id,
7772 variant: Some(update),
7773 })
7774 .log_err()
7775 }
7776
7777 pub async fn handle_follow(
7778 this: Entity<Self>,
7779 envelope: TypedEnvelope<proto::Follow>,
7780 mut cx: AsyncApp,
7781 ) -> Result<proto::FollowResponse> {
7782 this.update(&mut cx, |this, cx| {
7783 let follower = Follower {
7784 project_id: envelope.payload.project_id,
7785 peer_id: envelope.original_sender_id()?,
7786 };
7787
7788 let mut response = proto::FollowResponse::default();
7789
7790 this.workspaces.retain(|(window_handle, weak_workspace)| {
7791 let Some(workspace) = weak_workspace.upgrade() else {
7792 return false;
7793 };
7794 window_handle
7795 .update(cx, |_, window, cx| {
7796 workspace.update(cx, |workspace, cx| {
7797 let handler_response =
7798 workspace.handle_follow(follower.project_id, window, cx);
7799 if let Some(active_view) = handler_response.active_view
7800 && workspace.project.read(cx).remote_id() == follower.project_id
7801 {
7802 response.active_view = Some(active_view)
7803 }
7804 });
7805 })
7806 .is_ok()
7807 });
7808
7809 Ok(response)
7810 })
7811 }
7812
7813 async fn handle_update_followers(
7814 this: Entity<Self>,
7815 envelope: TypedEnvelope<proto::UpdateFollowers>,
7816 mut cx: AsyncApp,
7817 ) -> Result<()> {
7818 let leader_id = envelope.original_sender_id()?;
7819 let update = envelope.payload;
7820
7821 this.update(&mut cx, |this, cx| {
7822 this.workspaces.retain(|(window_handle, weak_workspace)| {
7823 let Some(workspace) = weak_workspace.upgrade() else {
7824 return false;
7825 };
7826 window_handle
7827 .update(cx, |_, window, cx| {
7828 workspace.update(cx, |workspace, cx| {
7829 let project_id = workspace.project.read(cx).remote_id();
7830 if update.project_id != project_id && update.project_id.is_some() {
7831 return;
7832 }
7833 workspace.handle_update_followers(
7834 leader_id,
7835 update.clone(),
7836 window,
7837 cx,
7838 );
7839 });
7840 })
7841 .is_ok()
7842 });
7843 Ok(())
7844 })
7845 }
7846
7847 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
7848 self.workspaces.iter().map(|(_, weak)| weak)
7849 }
7850
7851 pub fn workspaces_with_windows(
7852 &self,
7853 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
7854 self.workspaces.iter().map(|(window, weak)| (*window, weak))
7855 }
7856}
7857
7858impl ViewId {
7859 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
7860 Ok(Self {
7861 creator: message
7862 .creator
7863 .map(CollaboratorId::PeerId)
7864 .context("creator is missing")?,
7865 id: message.id,
7866 })
7867 }
7868
7869 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
7870 if let CollaboratorId::PeerId(peer_id) = self.creator {
7871 Some(proto::ViewId {
7872 creator: Some(peer_id),
7873 id: self.id,
7874 })
7875 } else {
7876 None
7877 }
7878 }
7879}
7880
7881impl FollowerState {
7882 fn pane(&self) -> &Entity<Pane> {
7883 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
7884 }
7885}
7886
7887pub trait WorkspaceHandle {
7888 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
7889}
7890
7891impl WorkspaceHandle for Entity<Workspace> {
7892 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
7893 self.read(cx)
7894 .worktrees(cx)
7895 .flat_map(|worktree| {
7896 let worktree_id = worktree.read(cx).id();
7897 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
7898 worktree_id,
7899 path: f.path.clone(),
7900 })
7901 })
7902 .collect::<Vec<_>>()
7903 }
7904}
7905
7906pub async fn last_opened_workspace_location(
7907 fs: &dyn fs::Fs,
7908) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
7909 DB.last_workspace(fs)
7910 .await
7911 .log_err()
7912 .flatten()
7913 .map(|(id, location, paths, _timestamp)| (id, location, paths))
7914}
7915
7916pub async fn last_session_workspace_locations(
7917 last_session_id: &str,
7918 last_session_window_stack: Option<Vec<WindowId>>,
7919 fs: &dyn fs::Fs,
7920) -> Option<Vec<SessionWorkspace>> {
7921 DB.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
7922 .await
7923 .log_err()
7924}
7925
7926pub struct MultiWorkspaceRestoreResult {
7927 pub window_handle: WindowHandle<MultiWorkspace>,
7928 pub errors: Vec<anyhow::Error>,
7929}
7930
7931pub async fn restore_multiworkspace(
7932 multi_workspace: SerializedMultiWorkspace,
7933 app_state: Arc<AppState>,
7934 cx: &mut AsyncApp,
7935) -> anyhow::Result<MultiWorkspaceRestoreResult> {
7936 let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
7937 let mut group_iter = workspaces.into_iter();
7938 let first = group_iter
7939 .next()
7940 .context("window group must not be empty")?;
7941
7942 let window_handle = if first.paths.is_empty() {
7943 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
7944 .await?
7945 } else {
7946 let (window, _items) = cx
7947 .update(|cx| {
7948 Workspace::new_local(
7949 first.paths.paths().to_vec(),
7950 app_state.clone(),
7951 None,
7952 None,
7953 None,
7954 cx,
7955 )
7956 })
7957 .await?;
7958 window
7959 };
7960
7961 let mut errors = Vec::new();
7962
7963 for session_workspace in group_iter {
7964 let error = if session_workspace.paths.is_empty() {
7965 cx.update(|cx| {
7966 open_workspace_by_id(
7967 session_workspace.workspace_id,
7968 app_state.clone(),
7969 Some(window_handle),
7970 cx,
7971 )
7972 })
7973 .await
7974 .err()
7975 } else {
7976 cx.update(|cx| {
7977 Workspace::new_local(
7978 session_workspace.paths.paths().to_vec(),
7979 app_state.clone(),
7980 Some(window_handle),
7981 None,
7982 None,
7983 cx,
7984 )
7985 })
7986 .await
7987 .err()
7988 };
7989
7990 if let Some(error) = error {
7991 errors.push(error);
7992 }
7993 }
7994
7995 if let Some(target_id) = state.active_workspace_id {
7996 window_handle
7997 .update(cx, |multi_workspace, window, cx| {
7998 let target_index = multi_workspace
7999 .workspaces()
8000 .iter()
8001 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8002 if let Some(index) = target_index {
8003 multi_workspace.activate_index(index, window, cx);
8004 } else if !multi_workspace.workspaces().is_empty() {
8005 multi_workspace.activate_index(0, window, cx);
8006 }
8007 })
8008 .ok();
8009 } else {
8010 window_handle
8011 .update(cx, |multi_workspace, window, cx| {
8012 if !multi_workspace.workspaces().is_empty() {
8013 multi_workspace.activate_index(0, window, cx);
8014 }
8015 })
8016 .ok();
8017 }
8018
8019 if state.sidebar_open {
8020 window_handle
8021 .update(cx, |multi_workspace, _, cx| {
8022 multi_workspace.open_sidebar(cx);
8023 })
8024 .ok();
8025 }
8026
8027 window_handle
8028 .update(cx, |_, window, _cx| {
8029 window.activate_window();
8030 })
8031 .ok();
8032
8033 Ok(MultiWorkspaceRestoreResult {
8034 window_handle,
8035 errors,
8036 })
8037}
8038
8039actions!(
8040 collab,
8041 [
8042 /// Opens the channel notes for the current call.
8043 ///
8044 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8045 /// channel in the collab panel.
8046 ///
8047 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8048 /// can be copied via "Copy link to section" in the context menu of the channel notes
8049 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8050 OpenChannelNotes,
8051 /// Mutes your microphone.
8052 Mute,
8053 /// Deafens yourself (mute both microphone and speakers).
8054 Deafen,
8055 /// Leaves the current call.
8056 LeaveCall,
8057 /// Shares the current project with collaborators.
8058 ShareProject,
8059 /// Shares your screen with collaborators.
8060 ScreenShare,
8061 /// Copies the current room name and session id for debugging purposes.
8062 CopyRoomId,
8063 ]
8064);
8065actions!(
8066 zed,
8067 [
8068 /// Opens the Zed log file.
8069 OpenLog,
8070 /// Reveals the Zed log file in the system file manager.
8071 RevealLogInFileManager
8072 ]
8073);
8074
8075async fn join_channel_internal(
8076 channel_id: ChannelId,
8077 app_state: &Arc<AppState>,
8078 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8079 requesting_workspace: Option<WeakEntity<Workspace>>,
8080 active_call: &Entity<ActiveCall>,
8081 cx: &mut AsyncApp,
8082) -> Result<bool> {
8083 let (should_prompt, open_room) = active_call.update(cx, |active_call, cx| {
8084 let Some(room) = active_call.room().map(|room| room.read(cx)) else {
8085 return (false, None);
8086 };
8087
8088 let already_in_channel = room.channel_id() == Some(channel_id);
8089 let should_prompt = room.is_sharing_project()
8090 && !room.remote_participants().is_empty()
8091 && !already_in_channel;
8092 let open_room = if already_in_channel {
8093 active_call.room().cloned()
8094 } else {
8095 None
8096 };
8097 (should_prompt, open_room)
8098 });
8099
8100 if let Some(room) = open_room {
8101 let task = room.update(cx, |room, cx| {
8102 if let Some((project, host)) = room.most_active_project(cx) {
8103 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8104 }
8105
8106 None
8107 });
8108 if let Some(task) = task {
8109 task.await?;
8110 }
8111 return anyhow::Ok(true);
8112 }
8113
8114 if should_prompt {
8115 if let Some(multi_workspace) = requesting_window {
8116 let answer = multi_workspace
8117 .update(cx, |_, window, cx| {
8118 window.prompt(
8119 PromptLevel::Warning,
8120 "Do you want to switch channels?",
8121 Some("Leaving this call will unshare your current project."),
8122 &["Yes, Join Channel", "Cancel"],
8123 cx,
8124 )
8125 })?
8126 .await;
8127
8128 if answer == Ok(1) {
8129 return Ok(false);
8130 }
8131 } else {
8132 return Ok(false); // unreachable!() hopefully
8133 }
8134 }
8135
8136 let client = cx.update(|cx| active_call.read(cx).client());
8137
8138 let mut client_status = client.status();
8139
8140 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8141 'outer: loop {
8142 let Some(status) = client_status.recv().await else {
8143 anyhow::bail!("error connecting");
8144 };
8145
8146 match status {
8147 Status::Connecting
8148 | Status::Authenticating
8149 | Status::Authenticated
8150 | Status::Reconnecting
8151 | Status::Reauthenticating
8152 | Status::Reauthenticated => continue,
8153 Status::Connected { .. } => break 'outer,
8154 Status::SignedOut | Status::AuthenticationError => {
8155 return Err(ErrorCode::SignedOut.into());
8156 }
8157 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8158 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8159 return Err(ErrorCode::Disconnected.into());
8160 }
8161 }
8162 }
8163
8164 let room = active_call
8165 .update(cx, |active_call, cx| {
8166 active_call.join_channel(channel_id, cx)
8167 })
8168 .await?;
8169
8170 let Some(room) = room else {
8171 return anyhow::Ok(true);
8172 };
8173
8174 room.update(cx, |room, _| room.room_update_completed())
8175 .await;
8176
8177 let task = room.update(cx, |room, cx| {
8178 if let Some((project, host)) = room.most_active_project(cx) {
8179 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8180 }
8181
8182 // If you are the first to join a channel, see if you should share your project.
8183 if room.remote_participants().is_empty()
8184 && !room.local_participant_is_guest()
8185 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8186 {
8187 let project = workspace.update(cx, |workspace, cx| {
8188 let project = workspace.project.read(cx);
8189
8190 if !CallSettings::get_global(cx).share_on_join {
8191 return None;
8192 }
8193
8194 if (project.is_local() || project.is_via_remote_server())
8195 && project.visible_worktrees(cx).any(|tree| {
8196 tree.read(cx)
8197 .root_entry()
8198 .is_some_and(|entry| entry.is_dir())
8199 })
8200 {
8201 Some(workspace.project.clone())
8202 } else {
8203 None
8204 }
8205 });
8206 if let Some(project) = project {
8207 return Some(cx.spawn(async move |room, cx| {
8208 room.update(cx, |room, cx| room.share_project(project, cx))?
8209 .await?;
8210 Ok(())
8211 }));
8212 }
8213 }
8214
8215 None
8216 });
8217 if let Some(task) = task {
8218 task.await?;
8219 return anyhow::Ok(true);
8220 }
8221 anyhow::Ok(false)
8222}
8223
8224pub fn join_channel(
8225 channel_id: ChannelId,
8226 app_state: Arc<AppState>,
8227 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8228 requesting_workspace: Option<WeakEntity<Workspace>>,
8229 cx: &mut App,
8230) -> Task<Result<()>> {
8231 let active_call = ActiveCall::global(cx);
8232 cx.spawn(async move |cx| {
8233 let result = join_channel_internal(
8234 channel_id,
8235 &app_state,
8236 requesting_window,
8237 requesting_workspace,
8238 &active_call,
8239 cx,
8240 )
8241 .await;
8242
8243 // join channel succeeded, and opened a window
8244 if matches!(result, Ok(true)) {
8245 return anyhow::Ok(());
8246 }
8247
8248 // find an existing workspace to focus and show call controls
8249 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8250 if active_window.is_none() {
8251 // no open workspaces, make one to show the error in (blergh)
8252 let (window_handle, _) = cx
8253 .update(|cx| {
8254 Workspace::new_local(
8255 vec![],
8256 app_state.clone(),
8257 requesting_window,
8258 None,
8259 None,
8260 cx,
8261 )
8262 })
8263 .await?;
8264
8265 window_handle
8266 .update(cx, |_, window, _cx| {
8267 window.activate_window();
8268 })
8269 .ok();
8270
8271 if result.is_ok() {
8272 cx.update(|cx| {
8273 cx.dispatch_action(&OpenChannelNotes);
8274 });
8275 }
8276
8277 active_window = Some(window_handle);
8278 }
8279
8280 if let Err(err) = result {
8281 log::error!("failed to join channel: {}", err);
8282 if let Some(active_window) = active_window {
8283 active_window
8284 .update(cx, |_, window, cx| {
8285 let detail: SharedString = match err.error_code() {
8286 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8287 ErrorCode::UpgradeRequired => concat!(
8288 "Your are running an unsupported version of Zed. ",
8289 "Please update to continue."
8290 )
8291 .into(),
8292 ErrorCode::NoSuchChannel => concat!(
8293 "No matching channel was found. ",
8294 "Please check the link and try again."
8295 )
8296 .into(),
8297 ErrorCode::Forbidden => concat!(
8298 "This channel is private, and you do not have access. ",
8299 "Please ask someone to add you and try again."
8300 )
8301 .into(),
8302 ErrorCode::Disconnected => {
8303 "Please check your internet connection and try again.".into()
8304 }
8305 _ => format!("{}\n\nPlease try again.", err).into(),
8306 };
8307 window.prompt(
8308 PromptLevel::Critical,
8309 "Failed to join channel",
8310 Some(&detail),
8311 &["Ok"],
8312 cx,
8313 )
8314 })?
8315 .await
8316 .ok();
8317 }
8318 }
8319
8320 // return ok, we showed the error to the user.
8321 anyhow::Ok(())
8322 })
8323}
8324
8325pub async fn get_any_active_multi_workspace(
8326 app_state: Arc<AppState>,
8327 mut cx: AsyncApp,
8328) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8329 // find an existing workspace to focus and show call controls
8330 let active_window = activate_any_workspace_window(&mut cx);
8331 if active_window.is_none() {
8332 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, cx))
8333 .await?;
8334 }
8335 activate_any_workspace_window(&mut cx).context("could not open zed")
8336}
8337
8338fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
8339 cx.update(|cx| {
8340 if let Some(workspace_window) = cx
8341 .active_window()
8342 .and_then(|window| window.downcast::<MultiWorkspace>())
8343 {
8344 return Some(workspace_window);
8345 }
8346
8347 for window in cx.windows() {
8348 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
8349 workspace_window
8350 .update(cx, |_, window, _| window.activate_window())
8351 .ok();
8352 return Some(workspace_window);
8353 }
8354 }
8355 None
8356 })
8357}
8358
8359pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
8360 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
8361}
8362
8363pub fn workspace_windows_for_location(
8364 serialized_location: &SerializedWorkspaceLocation,
8365 cx: &App,
8366) -> Vec<WindowHandle<MultiWorkspace>> {
8367 cx.windows()
8368 .into_iter()
8369 .filter_map(|window| window.downcast::<MultiWorkspace>())
8370 .filter(|multi_workspace| {
8371 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
8372 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
8373 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
8374 }
8375 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
8376 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
8377 a.distro_name == b.distro_name
8378 }
8379 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
8380 a.container_id == b.container_id
8381 }
8382 #[cfg(any(test, feature = "test-support"))]
8383 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
8384 a.id == b.id
8385 }
8386 _ => false,
8387 };
8388
8389 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
8390 multi_workspace.workspaces().iter().any(|workspace| {
8391 match workspace.read(cx).workspace_location(cx) {
8392 WorkspaceLocation::Location(location, _) => {
8393 match (&location, serialized_location) {
8394 (
8395 SerializedWorkspaceLocation::Local,
8396 SerializedWorkspaceLocation::Local,
8397 ) => true,
8398 (
8399 SerializedWorkspaceLocation::Remote(a),
8400 SerializedWorkspaceLocation::Remote(b),
8401 ) => same_host(a, b),
8402 _ => false,
8403 }
8404 }
8405 _ => false,
8406 }
8407 })
8408 })
8409 })
8410 .collect()
8411}
8412
8413pub async fn find_existing_workspace(
8414 abs_paths: &[PathBuf],
8415 open_options: &OpenOptions,
8416 location: &SerializedWorkspaceLocation,
8417 cx: &mut AsyncApp,
8418) -> (
8419 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
8420 OpenVisible,
8421) {
8422 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
8423 let mut open_visible = OpenVisible::All;
8424 let mut best_match = None;
8425
8426 if open_options.open_new_workspace != Some(true) {
8427 cx.update(|cx| {
8428 for window in workspace_windows_for_location(location, cx) {
8429 if let Ok(multi_workspace) = window.read(cx) {
8430 for workspace in multi_workspace.workspaces() {
8431 let project = workspace.read(cx).project.read(cx);
8432 let m = project.visibility_for_paths(
8433 abs_paths,
8434 open_options.open_new_workspace == None,
8435 cx,
8436 );
8437 if m > best_match {
8438 existing = Some((window, workspace.clone()));
8439 best_match = m;
8440 } else if best_match.is_none()
8441 && open_options.open_new_workspace == Some(false)
8442 {
8443 existing = Some((window, workspace.clone()))
8444 }
8445 }
8446 }
8447 }
8448 });
8449
8450 let all_paths_are_files = existing
8451 .as_ref()
8452 .and_then(|(_, target_workspace)| {
8453 cx.update(|cx| {
8454 let workspace = target_workspace.read(cx);
8455 let project = workspace.project.read(cx);
8456 let path_style = workspace.path_style(cx);
8457 Some(!abs_paths.iter().any(|path| {
8458 let path = util::paths::SanitizedPath::new(path);
8459 project.worktrees(cx).any(|worktree| {
8460 let worktree = worktree.read(cx);
8461 let abs_path = worktree.abs_path();
8462 path_style
8463 .strip_prefix(path.as_ref(), abs_path.as_ref())
8464 .and_then(|rel| worktree.entry_for_path(&rel))
8465 .is_some_and(|e| e.is_dir())
8466 })
8467 }))
8468 })
8469 })
8470 .unwrap_or(false);
8471
8472 if open_options.open_new_workspace.is_none()
8473 && existing.is_some()
8474 && open_options.wait
8475 && all_paths_are_files
8476 {
8477 cx.update(|cx| {
8478 let windows = workspace_windows_for_location(location, cx);
8479 let window = cx
8480 .active_window()
8481 .and_then(|window| window.downcast::<MultiWorkspace>())
8482 .filter(|window| windows.contains(window))
8483 .or_else(|| windows.into_iter().next());
8484 if let Some(window) = window {
8485 if let Ok(multi_workspace) = window.read(cx) {
8486 let active_workspace = multi_workspace.workspace().clone();
8487 existing = Some((window, active_workspace));
8488 open_visible = OpenVisible::None;
8489 }
8490 }
8491 });
8492 }
8493 }
8494 (existing, open_visible)
8495}
8496
8497#[derive(Default, Clone)]
8498pub struct OpenOptions {
8499 pub visible: Option<OpenVisible>,
8500 pub focus: Option<bool>,
8501 pub open_new_workspace: Option<bool>,
8502 pub wait: bool,
8503 pub replace_window: Option<WindowHandle<MultiWorkspace>>,
8504 pub env: Option<HashMap<String, String>>,
8505}
8506
8507/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
8508pub fn open_workspace_by_id(
8509 workspace_id: WorkspaceId,
8510 app_state: Arc<AppState>,
8511 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8512 cx: &mut App,
8513) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
8514 let project_handle = Project::local(
8515 app_state.client.clone(),
8516 app_state.node_runtime.clone(),
8517 app_state.user_store.clone(),
8518 app_state.languages.clone(),
8519 app_state.fs.clone(),
8520 None,
8521 project::LocalProjectFlags {
8522 init_worktree_trust: true,
8523 ..project::LocalProjectFlags::default()
8524 },
8525 cx,
8526 );
8527
8528 cx.spawn(async move |cx| {
8529 let serialized_workspace = persistence::DB
8530 .workspace_for_id(workspace_id)
8531 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
8532
8533 let centered_layout = serialized_workspace.centered_layout;
8534
8535 let (window, workspace) = if let Some(window) = requesting_window {
8536 let workspace = window.update(cx, |multi_workspace, window, cx| {
8537 let workspace = cx.new(|cx| {
8538 let mut workspace = Workspace::new(
8539 Some(workspace_id),
8540 project_handle.clone(),
8541 app_state.clone(),
8542 window,
8543 cx,
8544 );
8545 workspace.centered_layout = centered_layout;
8546 workspace
8547 });
8548 multi_workspace.add_workspace(workspace.clone(), cx);
8549 workspace
8550 })?;
8551 (window, workspace)
8552 } else {
8553 let window_bounds_override = window_bounds_env_override();
8554
8555 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
8556 (Some(WindowBounds::Windowed(bounds)), None)
8557 } else if let Some(display) = serialized_workspace.display
8558 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
8559 {
8560 (Some(bounds.0), Some(display))
8561 } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
8562 (Some(bounds), Some(display))
8563 } else {
8564 (None, None)
8565 };
8566
8567 let options = cx.update(|cx| {
8568 let mut options = (app_state.build_window_options)(display, cx);
8569 options.window_bounds = window_bounds;
8570 options
8571 });
8572
8573 let window = cx.open_window(options, {
8574 let app_state = app_state.clone();
8575 let project_handle = project_handle.clone();
8576 move |window, cx| {
8577 let workspace = cx.new(|cx| {
8578 let mut workspace = Workspace::new(
8579 Some(workspace_id),
8580 project_handle,
8581 app_state,
8582 window,
8583 cx,
8584 );
8585 workspace.centered_layout = centered_layout;
8586 workspace
8587 });
8588 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
8589 }
8590 })?;
8591
8592 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
8593 multi_workspace.workspace().clone()
8594 })?;
8595
8596 (window, workspace)
8597 };
8598
8599 notify_if_database_failed(window, cx);
8600
8601 // Restore items from the serialized workspace
8602 window
8603 .update(cx, |_, window, cx| {
8604 workspace.update(cx, |_workspace, cx| {
8605 open_items(Some(serialized_workspace), vec![], window, cx)
8606 })
8607 })?
8608 .await?;
8609
8610 window.update(cx, |_, window, cx| {
8611 workspace.update(cx, |workspace, cx| {
8612 workspace.serialize_workspace(window, cx);
8613 });
8614 })?;
8615
8616 Ok(window)
8617 })
8618}
8619
8620#[allow(clippy::type_complexity)]
8621pub fn open_paths(
8622 abs_paths: &[PathBuf],
8623 app_state: Arc<AppState>,
8624 open_options: OpenOptions,
8625 cx: &mut App,
8626) -> Task<
8627 anyhow::Result<(
8628 WindowHandle<MultiWorkspace>,
8629 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
8630 )>,
8631> {
8632 let abs_paths = abs_paths.to_vec();
8633 #[cfg(target_os = "windows")]
8634 let wsl_path = abs_paths
8635 .iter()
8636 .find_map(|p| util::paths::WslPath::from_path(p));
8637
8638 cx.spawn(async move |cx| {
8639 let (mut existing, mut open_visible) = find_existing_workspace(
8640 &abs_paths,
8641 &open_options,
8642 &SerializedWorkspaceLocation::Local,
8643 cx,
8644 )
8645 .await;
8646
8647 // Fallback: if no workspace contains the paths and all paths are files,
8648 // prefer an existing local workspace window (active window first).
8649 if open_options.open_new_workspace.is_none() && existing.is_none() {
8650 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
8651 let all_metadatas = futures::future::join_all(all_paths)
8652 .await
8653 .into_iter()
8654 .filter_map(|result| result.ok().flatten())
8655 .collect::<Vec<_>>();
8656
8657 if all_metadatas.iter().all(|file| !file.is_dir) {
8658 cx.update(|cx| {
8659 let windows = workspace_windows_for_location(
8660 &SerializedWorkspaceLocation::Local,
8661 cx,
8662 );
8663 let window = cx
8664 .active_window()
8665 .and_then(|window| window.downcast::<MultiWorkspace>())
8666 .filter(|window| windows.contains(window))
8667 .or_else(|| windows.into_iter().next());
8668 if let Some(window) = window {
8669 if let Ok(multi_workspace) = window.read(cx) {
8670 let active_workspace = multi_workspace.workspace().clone();
8671 existing = Some((window, active_workspace));
8672 open_visible = OpenVisible::None;
8673 }
8674 }
8675 });
8676 }
8677 }
8678
8679 let result = if let Some((existing, target_workspace)) = existing {
8680 let open_task = existing
8681 .update(cx, |multi_workspace, window, cx| {
8682 window.activate_window();
8683 multi_workspace.activate(target_workspace.clone(), cx);
8684 target_workspace.update(cx, |workspace, cx| {
8685 workspace.open_paths(
8686 abs_paths,
8687 OpenOptions {
8688 visible: Some(open_visible),
8689 ..Default::default()
8690 },
8691 None,
8692 window,
8693 cx,
8694 )
8695 })
8696 })?
8697 .await;
8698
8699 _ = existing.update(cx, |multi_workspace, _, cx| {
8700 let workspace = multi_workspace.workspace().clone();
8701 workspace.update(cx, |workspace, cx| {
8702 for item in open_task.iter().flatten() {
8703 if let Err(e) = item {
8704 workspace.show_error(&e, cx);
8705 }
8706 }
8707 });
8708 });
8709
8710 Ok((existing, open_task))
8711 } else {
8712 let result = cx
8713 .update(move |cx| {
8714 Workspace::new_local(
8715 abs_paths,
8716 app_state.clone(),
8717 open_options.replace_window,
8718 open_options.env,
8719 None,
8720 cx,
8721 )
8722 })
8723 .await;
8724
8725 if let Ok((ref window_handle, _)) = result {
8726 window_handle
8727 .update(cx, |_, window, _cx| {
8728 window.activate_window();
8729 })
8730 .log_err();
8731 }
8732
8733 result
8734 };
8735
8736 #[cfg(target_os = "windows")]
8737 if let Some(util::paths::WslPath{distro, path}) = wsl_path
8738 && let Ok((multi_workspace_window, _)) = &result
8739 {
8740 multi_workspace_window
8741 .update(cx, move |multi_workspace, _window, cx| {
8742 struct OpenInWsl;
8743 let workspace = multi_workspace.workspace().clone();
8744 workspace.update(cx, |workspace, cx| {
8745 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
8746 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
8747 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
8748 cx.new(move |cx| {
8749 MessageNotification::new(msg, cx)
8750 .primary_message("Open in WSL")
8751 .primary_icon(IconName::FolderOpen)
8752 .primary_on_click(move |window, cx| {
8753 window.dispatch_action(Box::new(remote::OpenWslPath {
8754 distro: remote::WslConnectionOptions {
8755 distro_name: distro.clone(),
8756 user: None,
8757 },
8758 paths: vec![path.clone().into()],
8759 }), cx)
8760 })
8761 })
8762 });
8763 });
8764 })
8765 .unwrap();
8766 };
8767 result
8768 })
8769}
8770
8771pub fn open_new(
8772 open_options: OpenOptions,
8773 app_state: Arc<AppState>,
8774 cx: &mut App,
8775 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
8776) -> Task<anyhow::Result<()>> {
8777 let task = Workspace::new_local(
8778 Vec::new(),
8779 app_state,
8780 open_options.replace_window,
8781 open_options.env,
8782 Some(Box::new(init)),
8783 cx,
8784 );
8785 cx.spawn(async move |cx| {
8786 let (window, _opened_paths) = task.await?;
8787 window
8788 .update(cx, |_, window, _cx| {
8789 window.activate_window();
8790 })
8791 .ok();
8792 Ok(())
8793 })
8794}
8795
8796pub fn create_and_open_local_file(
8797 path: &'static Path,
8798 window: &mut Window,
8799 cx: &mut Context<Workspace>,
8800 default_content: impl 'static + Send + FnOnce() -> Rope,
8801) -> Task<Result<Box<dyn ItemHandle>>> {
8802 cx.spawn_in(window, async move |workspace, cx| {
8803 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
8804 if !fs.is_file(path).await {
8805 fs.create_file(path, Default::default()).await?;
8806 fs.save(path, &default_content(), Default::default())
8807 .await?;
8808 }
8809
8810 workspace
8811 .update_in(cx, |workspace, window, cx| {
8812 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
8813 let path = workspace
8814 .project
8815 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
8816 cx.spawn_in(window, async move |workspace, cx| {
8817 let path = path.await?;
8818 let mut items = workspace
8819 .update_in(cx, |workspace, window, cx| {
8820 workspace.open_paths(
8821 vec![path.to_path_buf()],
8822 OpenOptions {
8823 visible: Some(OpenVisible::None),
8824 ..Default::default()
8825 },
8826 None,
8827 window,
8828 cx,
8829 )
8830 })?
8831 .await;
8832 let item = items.pop().flatten();
8833 item.with_context(|| format!("path {path:?} is not a file"))?
8834 })
8835 })
8836 })?
8837 .await?
8838 .await
8839 })
8840}
8841
8842pub fn open_remote_project_with_new_connection(
8843 window: WindowHandle<MultiWorkspace>,
8844 remote_connection: Arc<dyn RemoteConnection>,
8845 cancel_rx: oneshot::Receiver<()>,
8846 delegate: Arc<dyn RemoteClientDelegate>,
8847 app_state: Arc<AppState>,
8848 paths: Vec<PathBuf>,
8849 cx: &mut App,
8850) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
8851 cx.spawn(async move |cx| {
8852 let (workspace_id, serialized_workspace) =
8853 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
8854 .await?;
8855
8856 let session = match cx
8857 .update(|cx| {
8858 remote::RemoteClient::new(
8859 ConnectionIdentifier::Workspace(workspace_id.0),
8860 remote_connection,
8861 cancel_rx,
8862 delegate,
8863 cx,
8864 )
8865 })
8866 .await?
8867 {
8868 Some(result) => result,
8869 None => return Ok(Vec::new()),
8870 };
8871
8872 let project = cx.update(|cx| {
8873 project::Project::remote(
8874 session,
8875 app_state.client.clone(),
8876 app_state.node_runtime.clone(),
8877 app_state.user_store.clone(),
8878 app_state.languages.clone(),
8879 app_state.fs.clone(),
8880 true,
8881 cx,
8882 )
8883 });
8884
8885 open_remote_project_inner(
8886 project,
8887 paths,
8888 workspace_id,
8889 serialized_workspace,
8890 app_state,
8891 window,
8892 cx,
8893 )
8894 .await
8895 })
8896}
8897
8898pub fn open_remote_project_with_existing_connection(
8899 connection_options: RemoteConnectionOptions,
8900 project: Entity<Project>,
8901 paths: Vec<PathBuf>,
8902 app_state: Arc<AppState>,
8903 window: WindowHandle<MultiWorkspace>,
8904 cx: &mut AsyncApp,
8905) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
8906 cx.spawn(async move |cx| {
8907 let (workspace_id, serialized_workspace) =
8908 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
8909
8910 open_remote_project_inner(
8911 project,
8912 paths,
8913 workspace_id,
8914 serialized_workspace,
8915 app_state,
8916 window,
8917 cx,
8918 )
8919 .await
8920 })
8921}
8922
8923async fn open_remote_project_inner(
8924 project: Entity<Project>,
8925 paths: Vec<PathBuf>,
8926 workspace_id: WorkspaceId,
8927 serialized_workspace: Option<SerializedWorkspace>,
8928 app_state: Arc<AppState>,
8929 window: WindowHandle<MultiWorkspace>,
8930 cx: &mut AsyncApp,
8931) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
8932 let toolchains = DB.toolchains(workspace_id).await?;
8933 for (toolchain, worktree_path, path) in toolchains {
8934 project
8935 .update(cx, |this, cx| {
8936 let Some(worktree_id) =
8937 this.find_worktree(&worktree_path, cx)
8938 .and_then(|(worktree, rel_path)| {
8939 if rel_path.is_empty() {
8940 Some(worktree.read(cx).id())
8941 } else {
8942 None
8943 }
8944 })
8945 else {
8946 return Task::ready(None);
8947 };
8948
8949 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
8950 })
8951 .await;
8952 }
8953 let mut project_paths_to_open = vec![];
8954 let mut project_path_errors = vec![];
8955
8956 for path in paths {
8957 let result = cx
8958 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
8959 .await;
8960 match result {
8961 Ok((_, project_path)) => {
8962 project_paths_to_open.push((path.clone(), Some(project_path)));
8963 }
8964 Err(error) => {
8965 project_path_errors.push(error);
8966 }
8967 };
8968 }
8969
8970 if project_paths_to_open.is_empty() {
8971 return Err(project_path_errors.pop().context("no paths given")?);
8972 }
8973
8974 let workspace = window.update(cx, |multi_workspace, window, cx| {
8975 telemetry::event!("SSH Project Opened");
8976
8977 let new_workspace = cx.new(|cx| {
8978 let mut workspace =
8979 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
8980 workspace.update_history(cx);
8981
8982 if let Some(ref serialized) = serialized_workspace {
8983 workspace.centered_layout = serialized.centered_layout;
8984 }
8985
8986 workspace
8987 });
8988
8989 multi_workspace.activate(new_workspace.clone(), cx);
8990 new_workspace
8991 })?;
8992
8993 let items = window
8994 .update(cx, |_, window, cx| {
8995 window.activate_window();
8996 workspace.update(cx, |_workspace, cx| {
8997 open_items(serialized_workspace, project_paths_to_open, window, cx)
8998 })
8999 })?
9000 .await?;
9001
9002 workspace.update(cx, |workspace, cx| {
9003 for error in project_path_errors {
9004 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9005 if let Some(path) = error.error_tag("path") {
9006 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9007 }
9008 } else {
9009 workspace.show_error(&error, cx)
9010 }
9011 }
9012 });
9013
9014 Ok(items.into_iter().map(|item| item?.ok()).collect())
9015}
9016
9017fn deserialize_remote_project(
9018 connection_options: RemoteConnectionOptions,
9019 paths: Vec<PathBuf>,
9020 cx: &AsyncApp,
9021) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9022 cx.background_spawn(async move {
9023 let remote_connection_id = persistence::DB
9024 .get_or_create_remote_connection(connection_options)
9025 .await?;
9026
9027 let serialized_workspace =
9028 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
9029
9030 let workspace_id = if let Some(workspace_id) =
9031 serialized_workspace.as_ref().map(|workspace| workspace.id)
9032 {
9033 workspace_id
9034 } else {
9035 persistence::DB.next_id().await?
9036 };
9037
9038 Ok((workspace_id, serialized_workspace))
9039 })
9040}
9041
9042pub fn join_in_room_project(
9043 project_id: u64,
9044 follow_user_id: u64,
9045 app_state: Arc<AppState>,
9046 cx: &mut App,
9047) -> Task<Result<()>> {
9048 let windows = cx.windows();
9049 cx.spawn(async move |cx| {
9050 let existing_window_and_workspace: Option<(
9051 WindowHandle<MultiWorkspace>,
9052 Entity<Workspace>,
9053 )> = windows.into_iter().find_map(|window_handle| {
9054 window_handle
9055 .downcast::<MultiWorkspace>()
9056 .and_then(|window_handle| {
9057 window_handle
9058 .update(cx, |multi_workspace, _window, cx| {
9059 for workspace in multi_workspace.workspaces() {
9060 if workspace.read(cx).project().read(cx).remote_id()
9061 == Some(project_id)
9062 {
9063 return Some((window_handle, workspace.clone()));
9064 }
9065 }
9066 None
9067 })
9068 .unwrap_or(None)
9069 })
9070 });
9071
9072 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9073 existing_window_and_workspace
9074 {
9075 existing_window
9076 .update(cx, |multi_workspace, _, cx| {
9077 multi_workspace.activate(target_workspace, cx);
9078 })
9079 .ok();
9080 existing_window
9081 } else {
9082 let active_call = cx.update(|cx| ActiveCall::global(cx));
9083 let room = active_call
9084 .read_with(cx, |call, _| call.room().cloned())
9085 .context("not in a call")?;
9086 let project = room
9087 .update(cx, |room, cx| {
9088 room.join_project(
9089 project_id,
9090 app_state.languages.clone(),
9091 app_state.fs.clone(),
9092 cx,
9093 )
9094 })
9095 .await?;
9096
9097 let window_bounds_override = window_bounds_env_override();
9098 cx.update(|cx| {
9099 let mut options = (app_state.build_window_options)(None, cx);
9100 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9101 cx.open_window(options, |window, cx| {
9102 let workspace = cx.new(|cx| {
9103 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9104 });
9105 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9106 })
9107 })?
9108 };
9109
9110 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9111 cx.activate(true);
9112 window.activate_window();
9113
9114 // We set the active workspace above, so this is the correct workspace.
9115 let workspace = multi_workspace.workspace().clone();
9116 workspace.update(cx, |workspace, cx| {
9117 if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
9118 let follow_peer_id = room
9119 .read(cx)
9120 .remote_participants()
9121 .iter()
9122 .find(|(_, participant)| participant.user.id == follow_user_id)
9123 .map(|(_, p)| p.peer_id)
9124 .or_else(|| {
9125 // If we couldn't follow the given user, follow the host instead.
9126 let collaborator = workspace
9127 .project()
9128 .read(cx)
9129 .collaborators()
9130 .values()
9131 .find(|collaborator| collaborator.is_host)?;
9132 Some(collaborator.peer_id)
9133 });
9134
9135 if let Some(follow_peer_id) = follow_peer_id {
9136 workspace.follow(follow_peer_id, window, cx);
9137 }
9138 }
9139 });
9140 })?;
9141
9142 anyhow::Ok(())
9143 })
9144}
9145
9146pub fn reload(cx: &mut App) {
9147 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9148 let mut workspace_windows = cx
9149 .windows()
9150 .into_iter()
9151 .filter_map(|window| window.downcast::<MultiWorkspace>())
9152 .collect::<Vec<_>>();
9153
9154 // If multiple windows have unsaved changes, and need a save prompt,
9155 // prompt in the active window before switching to a different window.
9156 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9157
9158 let mut prompt = None;
9159 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9160 prompt = window
9161 .update(cx, |_, window, cx| {
9162 window.prompt(
9163 PromptLevel::Info,
9164 "Are you sure you want to restart?",
9165 None,
9166 &["Restart", "Cancel"],
9167 cx,
9168 )
9169 })
9170 .ok();
9171 }
9172
9173 cx.spawn(async move |cx| {
9174 if let Some(prompt) = prompt {
9175 let answer = prompt.await?;
9176 if answer != 0 {
9177 return anyhow::Ok(());
9178 }
9179 }
9180
9181 // If the user cancels any save prompt, then keep the app open.
9182 for window in workspace_windows {
9183 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9184 let workspace = multi_workspace.workspace().clone();
9185 workspace.update(cx, |workspace, cx| {
9186 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9187 })
9188 }) && !should_close.await?
9189 {
9190 return anyhow::Ok(());
9191 }
9192 }
9193 cx.update(|cx| cx.restart());
9194 anyhow::Ok(())
9195 })
9196 .detach_and_log_err(cx);
9197}
9198
9199fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9200 let mut parts = value.split(',');
9201 let x: usize = parts.next()?.parse().ok()?;
9202 let y: usize = parts.next()?.parse().ok()?;
9203 Some(point(px(x as f32), px(y as f32)))
9204}
9205
9206fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9207 let mut parts = value.split(',');
9208 let width: usize = parts.next()?.parse().ok()?;
9209 let height: usize = parts.next()?.parse().ok()?;
9210 Some(size(px(width as f32), px(height as f32)))
9211}
9212
9213/// Add client-side decorations (rounded corners, shadows, resize handling) when
9214/// appropriate.
9215///
9216/// The `border_radius_tiling` parameter allows overriding which corners get
9217/// rounded, independently of the actual window tiling state. This is used
9218/// specifically for the workspace switcher sidebar: when the sidebar is open,
9219/// we want square corners on the left (so the sidebar appears flush with the
9220/// window edge) but we still need the shadow padding for proper visual
9221/// appearance. Unlike actual window tiling, this only affects border radius -
9222/// not padding or shadows.
9223pub fn client_side_decorations(
9224 element: impl IntoElement,
9225 window: &mut Window,
9226 cx: &mut App,
9227 border_radius_tiling: Tiling,
9228) -> Stateful<Div> {
9229 const BORDER_SIZE: Pixels = px(1.0);
9230 let decorations = window.window_decorations();
9231 let tiling = match decorations {
9232 Decorations::Server => Tiling::default(),
9233 Decorations::Client { tiling } => tiling,
9234 };
9235
9236 match decorations {
9237 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9238 Decorations::Server => window.set_client_inset(px(0.0)),
9239 }
9240
9241 struct GlobalResizeEdge(ResizeEdge);
9242 impl Global for GlobalResizeEdge {}
9243
9244 div()
9245 .id("window-backdrop")
9246 .bg(transparent_black())
9247 .map(|div| match decorations {
9248 Decorations::Server => div,
9249 Decorations::Client { .. } => div
9250 .when(
9251 !(tiling.top
9252 || tiling.right
9253 || border_radius_tiling.top
9254 || border_radius_tiling.right),
9255 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9256 )
9257 .when(
9258 !(tiling.top
9259 || tiling.left
9260 || border_radius_tiling.top
9261 || border_radius_tiling.left),
9262 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9263 )
9264 .when(
9265 !(tiling.bottom
9266 || tiling.right
9267 || border_radius_tiling.bottom
9268 || border_radius_tiling.right),
9269 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9270 )
9271 .when(
9272 !(tiling.bottom
9273 || tiling.left
9274 || border_radius_tiling.bottom
9275 || border_radius_tiling.left),
9276 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9277 )
9278 .when(!tiling.top, |div| {
9279 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9280 })
9281 .when(!tiling.bottom, |div| {
9282 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9283 })
9284 .when(!tiling.left, |div| {
9285 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9286 })
9287 .when(!tiling.right, |div| {
9288 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9289 })
9290 .on_mouse_move(move |e, window, cx| {
9291 let size = window.window_bounds().get_bounds().size;
9292 let pos = e.position;
9293
9294 let new_edge =
9295 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9296
9297 let edge = cx.try_global::<GlobalResizeEdge>();
9298 if new_edge != edge.map(|edge| edge.0) {
9299 window
9300 .window_handle()
9301 .update(cx, |workspace, _, cx| {
9302 cx.notify(workspace.entity_id());
9303 })
9304 .ok();
9305 }
9306 })
9307 .on_mouse_down(MouseButton::Left, move |e, window, _| {
9308 let size = window.window_bounds().get_bounds().size;
9309 let pos = e.position;
9310
9311 let edge = match resize_edge(
9312 pos,
9313 theme::CLIENT_SIDE_DECORATION_SHADOW,
9314 size,
9315 tiling,
9316 ) {
9317 Some(value) => value,
9318 None => return,
9319 };
9320
9321 window.start_window_resize(edge);
9322 }),
9323 })
9324 .size_full()
9325 .child(
9326 div()
9327 .cursor(CursorStyle::Arrow)
9328 .map(|div| match decorations {
9329 Decorations::Server => div,
9330 Decorations::Client { .. } => div
9331 .border_color(cx.theme().colors().border)
9332 .when(
9333 !(tiling.top
9334 || tiling.right
9335 || border_radius_tiling.top
9336 || border_radius_tiling.right),
9337 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9338 )
9339 .when(
9340 !(tiling.top
9341 || tiling.left
9342 || border_radius_tiling.top
9343 || border_radius_tiling.left),
9344 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9345 )
9346 .when(
9347 !(tiling.bottom
9348 || tiling.right
9349 || border_radius_tiling.bottom
9350 || border_radius_tiling.right),
9351 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9352 )
9353 .when(
9354 !(tiling.bottom
9355 || tiling.left
9356 || border_radius_tiling.bottom
9357 || border_radius_tiling.left),
9358 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9359 )
9360 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
9361 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
9362 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
9363 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
9364 .when(!tiling.is_tiled(), |div| {
9365 div.shadow(vec![gpui::BoxShadow {
9366 color: Hsla {
9367 h: 0.,
9368 s: 0.,
9369 l: 0.,
9370 a: 0.4,
9371 },
9372 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
9373 spread_radius: px(0.),
9374 offset: point(px(0.0), px(0.0)),
9375 }])
9376 }),
9377 })
9378 .on_mouse_move(|_e, _, cx| {
9379 cx.stop_propagation();
9380 })
9381 .size_full()
9382 .child(element),
9383 )
9384 .map(|div| match decorations {
9385 Decorations::Server => div,
9386 Decorations::Client { tiling, .. } => div.child(
9387 canvas(
9388 |_bounds, window, _| {
9389 window.insert_hitbox(
9390 Bounds::new(
9391 point(px(0.0), px(0.0)),
9392 window.window_bounds().get_bounds().size,
9393 ),
9394 HitboxBehavior::Normal,
9395 )
9396 },
9397 move |_bounds, hitbox, window, cx| {
9398 let mouse = window.mouse_position();
9399 let size = window.window_bounds().get_bounds().size;
9400 let Some(edge) =
9401 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
9402 else {
9403 return;
9404 };
9405 cx.set_global(GlobalResizeEdge(edge));
9406 window.set_cursor_style(
9407 match edge {
9408 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
9409 ResizeEdge::Left | ResizeEdge::Right => {
9410 CursorStyle::ResizeLeftRight
9411 }
9412 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
9413 CursorStyle::ResizeUpLeftDownRight
9414 }
9415 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
9416 CursorStyle::ResizeUpRightDownLeft
9417 }
9418 },
9419 &hitbox,
9420 );
9421 },
9422 )
9423 .size_full()
9424 .absolute(),
9425 ),
9426 })
9427}
9428
9429fn resize_edge(
9430 pos: Point<Pixels>,
9431 shadow_size: Pixels,
9432 window_size: Size<Pixels>,
9433 tiling: Tiling,
9434) -> Option<ResizeEdge> {
9435 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
9436 if bounds.contains(&pos) {
9437 return None;
9438 }
9439
9440 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
9441 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
9442 if !tiling.top && top_left_bounds.contains(&pos) {
9443 return Some(ResizeEdge::TopLeft);
9444 }
9445
9446 let top_right_bounds = Bounds::new(
9447 Point::new(window_size.width - corner_size.width, px(0.)),
9448 corner_size,
9449 );
9450 if !tiling.top && top_right_bounds.contains(&pos) {
9451 return Some(ResizeEdge::TopRight);
9452 }
9453
9454 let bottom_left_bounds = Bounds::new(
9455 Point::new(px(0.), window_size.height - corner_size.height),
9456 corner_size,
9457 );
9458 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
9459 return Some(ResizeEdge::BottomLeft);
9460 }
9461
9462 let bottom_right_bounds = Bounds::new(
9463 Point::new(
9464 window_size.width - corner_size.width,
9465 window_size.height - corner_size.height,
9466 ),
9467 corner_size,
9468 );
9469 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
9470 return Some(ResizeEdge::BottomRight);
9471 }
9472
9473 if !tiling.top && pos.y < shadow_size {
9474 Some(ResizeEdge::Top)
9475 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
9476 Some(ResizeEdge::Bottom)
9477 } else if !tiling.left && pos.x < shadow_size {
9478 Some(ResizeEdge::Left)
9479 } else if !tiling.right && pos.x > window_size.width - shadow_size {
9480 Some(ResizeEdge::Right)
9481 } else {
9482 None
9483 }
9484}
9485
9486fn join_pane_into_active(
9487 active_pane: &Entity<Pane>,
9488 pane: &Entity<Pane>,
9489 window: &mut Window,
9490 cx: &mut App,
9491) {
9492 if pane == active_pane {
9493 } else if pane.read(cx).items_len() == 0 {
9494 pane.update(cx, |_, cx| {
9495 cx.emit(pane::Event::Remove {
9496 focus_on_pane: None,
9497 });
9498 })
9499 } else {
9500 move_all_items(pane, active_pane, window, cx);
9501 }
9502}
9503
9504fn move_all_items(
9505 from_pane: &Entity<Pane>,
9506 to_pane: &Entity<Pane>,
9507 window: &mut Window,
9508 cx: &mut App,
9509) {
9510 let destination_is_different = from_pane != to_pane;
9511 let mut moved_items = 0;
9512 for (item_ix, item_handle) in from_pane
9513 .read(cx)
9514 .items()
9515 .enumerate()
9516 .map(|(ix, item)| (ix, item.clone()))
9517 .collect::<Vec<_>>()
9518 {
9519 let ix = item_ix - moved_items;
9520 if destination_is_different {
9521 // Close item from previous pane
9522 from_pane.update(cx, |source, cx| {
9523 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
9524 });
9525 moved_items += 1;
9526 }
9527
9528 // This automatically removes duplicate items in the pane
9529 to_pane.update(cx, |destination, cx| {
9530 destination.add_item(item_handle, true, true, None, window, cx);
9531 window.focus(&destination.focus_handle(cx), cx)
9532 });
9533 }
9534}
9535
9536pub fn move_item(
9537 source: &Entity<Pane>,
9538 destination: &Entity<Pane>,
9539 item_id_to_move: EntityId,
9540 destination_index: usize,
9541 activate: bool,
9542 window: &mut Window,
9543 cx: &mut App,
9544) {
9545 let Some((item_ix, item_handle)) = source
9546 .read(cx)
9547 .items()
9548 .enumerate()
9549 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
9550 .map(|(ix, item)| (ix, item.clone()))
9551 else {
9552 // Tab was closed during drag
9553 return;
9554 };
9555
9556 if source != destination {
9557 // Close item from previous pane
9558 source.update(cx, |source, cx| {
9559 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
9560 });
9561 }
9562
9563 // This automatically removes duplicate items in the pane
9564 destination.update(cx, |destination, cx| {
9565 destination.add_item_inner(
9566 item_handle,
9567 activate,
9568 activate,
9569 activate,
9570 Some(destination_index),
9571 window,
9572 cx,
9573 );
9574 if activate {
9575 window.focus(&destination.focus_handle(cx), cx)
9576 }
9577 });
9578}
9579
9580pub fn move_active_item(
9581 source: &Entity<Pane>,
9582 destination: &Entity<Pane>,
9583 focus_destination: bool,
9584 close_if_empty: bool,
9585 window: &mut Window,
9586 cx: &mut App,
9587) {
9588 if source == destination {
9589 return;
9590 }
9591 let Some(active_item) = source.read(cx).active_item() else {
9592 return;
9593 };
9594 source.update(cx, |source_pane, cx| {
9595 let item_id = active_item.item_id();
9596 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
9597 destination.update(cx, |target_pane, cx| {
9598 target_pane.add_item(
9599 active_item,
9600 focus_destination,
9601 focus_destination,
9602 Some(target_pane.items_len()),
9603 window,
9604 cx,
9605 );
9606 });
9607 });
9608}
9609
9610pub fn clone_active_item(
9611 workspace_id: Option<WorkspaceId>,
9612 source: &Entity<Pane>,
9613 destination: &Entity<Pane>,
9614 focus_destination: bool,
9615 window: &mut Window,
9616 cx: &mut App,
9617) {
9618 if source == destination {
9619 return;
9620 }
9621 let Some(active_item) = source.read(cx).active_item() else {
9622 return;
9623 };
9624 if !active_item.can_split(cx) {
9625 return;
9626 }
9627 let destination = destination.downgrade();
9628 let task = active_item.clone_on_split(workspace_id, window, cx);
9629 window
9630 .spawn(cx, async move |cx| {
9631 let Some(clone) = task.await else {
9632 return;
9633 };
9634 destination
9635 .update_in(cx, |target_pane, window, cx| {
9636 target_pane.add_item(
9637 clone,
9638 focus_destination,
9639 focus_destination,
9640 Some(target_pane.items_len()),
9641 window,
9642 cx,
9643 );
9644 })
9645 .log_err();
9646 })
9647 .detach();
9648}
9649
9650#[derive(Debug)]
9651pub struct WorkspacePosition {
9652 pub window_bounds: Option<WindowBounds>,
9653 pub display: Option<Uuid>,
9654 pub centered_layout: bool,
9655}
9656
9657pub fn remote_workspace_position_from_db(
9658 connection_options: RemoteConnectionOptions,
9659 paths_to_open: &[PathBuf],
9660 cx: &App,
9661) -> Task<Result<WorkspacePosition>> {
9662 let paths = paths_to_open.to_vec();
9663
9664 cx.background_spawn(async move {
9665 let remote_connection_id = persistence::DB
9666 .get_or_create_remote_connection(connection_options)
9667 .await
9668 .context("fetching serialized ssh project")?;
9669 let serialized_workspace =
9670 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
9671
9672 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
9673 (Some(WindowBounds::Windowed(bounds)), None)
9674 } else {
9675 let restorable_bounds = serialized_workspace
9676 .as_ref()
9677 .and_then(|workspace| {
9678 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
9679 })
9680 .or_else(|| persistence::read_default_window_bounds());
9681
9682 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
9683 (Some(serialized_bounds), Some(serialized_display))
9684 } else {
9685 (None, None)
9686 }
9687 };
9688
9689 let centered_layout = serialized_workspace
9690 .as_ref()
9691 .map(|w| w.centered_layout)
9692 .unwrap_or(false);
9693
9694 Ok(WorkspacePosition {
9695 window_bounds,
9696 display,
9697 centered_layout,
9698 })
9699 })
9700}
9701
9702pub fn with_active_or_new_workspace(
9703 cx: &mut App,
9704 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
9705) {
9706 match cx
9707 .active_window()
9708 .and_then(|w| w.downcast::<MultiWorkspace>())
9709 {
9710 Some(multi_workspace) => {
9711 cx.defer(move |cx| {
9712 multi_workspace
9713 .update(cx, |multi_workspace, window, cx| {
9714 let workspace = multi_workspace.workspace().clone();
9715 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
9716 })
9717 .log_err();
9718 });
9719 }
9720 None => {
9721 let app_state = AppState::global(cx);
9722 if let Some(app_state) = app_state.upgrade() {
9723 open_new(
9724 OpenOptions::default(),
9725 app_state,
9726 cx,
9727 move |workspace, window, cx| f(workspace, window, cx),
9728 )
9729 .detach_and_log_err(cx);
9730 }
9731 }
9732 }
9733}
9734
9735#[cfg(test)]
9736mod tests {
9737 use std::{cell::RefCell, rc::Rc};
9738
9739 use super::*;
9740 use crate::{
9741 dock::{PanelEvent, test::TestPanel},
9742 item::{
9743 ItemBufferKind, ItemEvent,
9744 test::{TestItem, TestProjectItem},
9745 },
9746 };
9747 use fs::FakeFs;
9748 use gpui::{
9749 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
9750 UpdateGlobal, VisualTestContext, px,
9751 };
9752 use project::{Project, ProjectEntryId};
9753 use serde_json::json;
9754 use settings::SettingsStore;
9755 use util::rel_path::rel_path;
9756
9757 #[gpui::test]
9758 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
9759 init_test(cx);
9760
9761 let fs = FakeFs::new(cx.executor());
9762 let project = Project::test(fs, [], cx).await;
9763 let (workspace, cx) =
9764 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9765
9766 // Adding an item with no ambiguity renders the tab without detail.
9767 let item1 = cx.new(|cx| {
9768 let mut item = TestItem::new(cx);
9769 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
9770 item
9771 });
9772 workspace.update_in(cx, |workspace, window, cx| {
9773 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
9774 });
9775 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
9776
9777 // Adding an item that creates ambiguity increases the level of detail on
9778 // both tabs.
9779 let item2 = cx.new_window_entity(|_window, cx| {
9780 let mut item = TestItem::new(cx);
9781 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
9782 item
9783 });
9784 workspace.update_in(cx, |workspace, window, cx| {
9785 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9786 });
9787 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
9788 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
9789
9790 // Adding an item that creates ambiguity increases the level of detail only
9791 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
9792 // we stop at the highest detail available.
9793 let item3 = cx.new(|cx| {
9794 let mut item = TestItem::new(cx);
9795 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
9796 item
9797 });
9798 workspace.update_in(cx, |workspace, window, cx| {
9799 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
9800 });
9801 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
9802 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
9803 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
9804 }
9805
9806 #[gpui::test]
9807 async fn test_tracking_active_path(cx: &mut TestAppContext) {
9808 init_test(cx);
9809
9810 let fs = FakeFs::new(cx.executor());
9811 fs.insert_tree(
9812 "/root1",
9813 json!({
9814 "one.txt": "",
9815 "two.txt": "",
9816 }),
9817 )
9818 .await;
9819 fs.insert_tree(
9820 "/root2",
9821 json!({
9822 "three.txt": "",
9823 }),
9824 )
9825 .await;
9826
9827 let project = Project::test(fs, ["root1".as_ref()], cx).await;
9828 let (workspace, cx) =
9829 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9830 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9831 let worktree_id = project.update(cx, |project, cx| {
9832 project.worktrees(cx).next().unwrap().read(cx).id()
9833 });
9834
9835 let item1 = cx.new(|cx| {
9836 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
9837 });
9838 let item2 = cx.new(|cx| {
9839 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
9840 });
9841
9842 // Add an item to an empty pane
9843 workspace.update_in(cx, |workspace, window, cx| {
9844 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
9845 });
9846 project.update(cx, |project, cx| {
9847 assert_eq!(
9848 project.active_entry(),
9849 project
9850 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
9851 .map(|e| e.id)
9852 );
9853 });
9854 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
9855
9856 // Add a second item to a non-empty pane
9857 workspace.update_in(cx, |workspace, window, cx| {
9858 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
9859 });
9860 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
9861 project.update(cx, |project, cx| {
9862 assert_eq!(
9863 project.active_entry(),
9864 project
9865 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
9866 .map(|e| e.id)
9867 );
9868 });
9869
9870 // Close the active item
9871 pane.update_in(cx, |pane, window, cx| {
9872 pane.close_active_item(&Default::default(), window, cx)
9873 })
9874 .await
9875 .unwrap();
9876 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
9877 project.update(cx, |project, cx| {
9878 assert_eq!(
9879 project.active_entry(),
9880 project
9881 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
9882 .map(|e| e.id)
9883 );
9884 });
9885
9886 // Add a project folder
9887 project
9888 .update(cx, |project, cx| {
9889 project.find_or_create_worktree("root2", true, cx)
9890 })
9891 .await
9892 .unwrap();
9893 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
9894
9895 // Remove a project folder
9896 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
9897 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
9898 }
9899
9900 #[gpui::test]
9901 async fn test_close_window(cx: &mut TestAppContext) {
9902 init_test(cx);
9903
9904 let fs = FakeFs::new(cx.executor());
9905 fs.insert_tree("/root", json!({ "one": "" })).await;
9906
9907 let project = Project::test(fs, ["root".as_ref()], cx).await;
9908 let (workspace, cx) =
9909 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9910
9911 // When there are no dirty items, there's nothing to do.
9912 let item1 = cx.new(TestItem::new);
9913 workspace.update_in(cx, |w, window, cx| {
9914 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
9915 });
9916 let task = workspace.update_in(cx, |w, window, cx| {
9917 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
9918 });
9919 assert!(task.await.unwrap());
9920
9921 // When there are dirty untitled items, prompt to save each one. If the user
9922 // cancels any prompt, then abort.
9923 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
9924 let item3 = cx.new(|cx| {
9925 TestItem::new(cx)
9926 .with_dirty(true)
9927 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
9928 });
9929 workspace.update_in(cx, |w, window, cx| {
9930 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9931 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
9932 });
9933 let task = workspace.update_in(cx, |w, window, cx| {
9934 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
9935 });
9936 cx.executor().run_until_parked();
9937 cx.simulate_prompt_answer("Cancel"); // cancel save all
9938 cx.executor().run_until_parked();
9939 assert!(!cx.has_pending_prompt());
9940 assert!(!task.await.unwrap());
9941 }
9942
9943 #[gpui::test]
9944 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
9945 init_test(cx);
9946
9947 // Register TestItem as a serializable item
9948 cx.update(|cx| {
9949 register_serializable_item::<TestItem>(cx);
9950 });
9951
9952 let fs = FakeFs::new(cx.executor());
9953 fs.insert_tree("/root", json!({ "one": "" })).await;
9954
9955 let project = Project::test(fs, ["root".as_ref()], cx).await;
9956 let (workspace, cx) =
9957 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9958
9959 // When there are dirty untitled items, but they can serialize, then there is no prompt.
9960 let item1 = cx.new(|cx| {
9961 TestItem::new(cx)
9962 .with_dirty(true)
9963 .with_serialize(|| Some(Task::ready(Ok(()))))
9964 });
9965 let item2 = cx.new(|cx| {
9966 TestItem::new(cx)
9967 .with_dirty(true)
9968 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
9969 .with_serialize(|| Some(Task::ready(Ok(()))))
9970 });
9971 workspace.update_in(cx, |w, window, cx| {
9972 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
9973 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9974 });
9975 let task = workspace.update_in(cx, |w, window, cx| {
9976 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
9977 });
9978 assert!(task.await.unwrap());
9979 }
9980
9981 #[gpui::test]
9982 async fn test_close_pane_items(cx: &mut TestAppContext) {
9983 init_test(cx);
9984
9985 let fs = FakeFs::new(cx.executor());
9986
9987 let project = Project::test(fs, None, cx).await;
9988 let (workspace, cx) =
9989 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9990
9991 let item1 = cx.new(|cx| {
9992 TestItem::new(cx)
9993 .with_dirty(true)
9994 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
9995 });
9996 let item2 = cx.new(|cx| {
9997 TestItem::new(cx)
9998 .with_dirty(true)
9999 .with_conflict(true)
10000 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10001 });
10002 let item3 = cx.new(|cx| {
10003 TestItem::new(cx)
10004 .with_dirty(true)
10005 .with_conflict(true)
10006 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10007 });
10008 let item4 = cx.new(|cx| {
10009 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10010 let project_item = TestProjectItem::new_untitled(cx);
10011 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10012 project_item
10013 }])
10014 });
10015 let pane = workspace.update_in(cx, |workspace, window, cx| {
10016 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10017 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10018 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10019 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10020 workspace.active_pane().clone()
10021 });
10022
10023 let close_items = pane.update_in(cx, |pane, window, cx| {
10024 pane.activate_item(1, true, true, window, cx);
10025 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10026 let item1_id = item1.item_id();
10027 let item3_id = item3.item_id();
10028 let item4_id = item4.item_id();
10029 pane.close_items(window, cx, SaveIntent::Close, move |id| {
10030 [item1_id, item3_id, item4_id].contains(&id)
10031 })
10032 });
10033 cx.executor().run_until_parked();
10034
10035 assert!(cx.has_pending_prompt());
10036 cx.simulate_prompt_answer("Save all");
10037
10038 cx.executor().run_until_parked();
10039
10040 // Item 1 is saved. There's a prompt to save item 3.
10041 pane.update(cx, |pane, cx| {
10042 assert_eq!(item1.read(cx).save_count, 1);
10043 assert_eq!(item1.read(cx).save_as_count, 0);
10044 assert_eq!(item1.read(cx).reload_count, 0);
10045 assert_eq!(pane.items_len(), 3);
10046 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10047 });
10048 assert!(cx.has_pending_prompt());
10049
10050 // Cancel saving item 3.
10051 cx.simulate_prompt_answer("Discard");
10052 cx.executor().run_until_parked();
10053
10054 // Item 3 is reloaded. There's a prompt to save item 4.
10055 pane.update(cx, |pane, cx| {
10056 assert_eq!(item3.read(cx).save_count, 0);
10057 assert_eq!(item3.read(cx).save_as_count, 0);
10058 assert_eq!(item3.read(cx).reload_count, 1);
10059 assert_eq!(pane.items_len(), 2);
10060 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10061 });
10062
10063 // There's a prompt for a path for item 4.
10064 cx.simulate_new_path_selection(|_| Some(Default::default()));
10065 close_items.await.unwrap();
10066
10067 // The requested items are closed.
10068 pane.update(cx, |pane, cx| {
10069 assert_eq!(item4.read(cx).save_count, 0);
10070 assert_eq!(item4.read(cx).save_as_count, 1);
10071 assert_eq!(item4.read(cx).reload_count, 0);
10072 assert_eq!(pane.items_len(), 1);
10073 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10074 });
10075 }
10076
10077 #[gpui::test]
10078 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10079 init_test(cx);
10080
10081 let fs = FakeFs::new(cx.executor());
10082 let project = Project::test(fs, [], cx).await;
10083 let (workspace, cx) =
10084 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10085
10086 // Create several workspace items with single project entries, and two
10087 // workspace items with multiple project entries.
10088 let single_entry_items = (0..=4)
10089 .map(|project_entry_id| {
10090 cx.new(|cx| {
10091 TestItem::new(cx)
10092 .with_dirty(true)
10093 .with_project_items(&[dirty_project_item(
10094 project_entry_id,
10095 &format!("{project_entry_id}.txt"),
10096 cx,
10097 )])
10098 })
10099 })
10100 .collect::<Vec<_>>();
10101 let item_2_3 = cx.new(|cx| {
10102 TestItem::new(cx)
10103 .with_dirty(true)
10104 .with_buffer_kind(ItemBufferKind::Multibuffer)
10105 .with_project_items(&[
10106 single_entry_items[2].read(cx).project_items[0].clone(),
10107 single_entry_items[3].read(cx).project_items[0].clone(),
10108 ])
10109 });
10110 let item_3_4 = cx.new(|cx| {
10111 TestItem::new(cx)
10112 .with_dirty(true)
10113 .with_buffer_kind(ItemBufferKind::Multibuffer)
10114 .with_project_items(&[
10115 single_entry_items[3].read(cx).project_items[0].clone(),
10116 single_entry_items[4].read(cx).project_items[0].clone(),
10117 ])
10118 });
10119
10120 // Create two panes that contain the following project entries:
10121 // left pane:
10122 // multi-entry items: (2, 3)
10123 // single-entry items: 0, 2, 3, 4
10124 // right pane:
10125 // single-entry items: 4, 1
10126 // multi-entry items: (3, 4)
10127 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10128 let left_pane = workspace.active_pane().clone();
10129 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10130 workspace.add_item_to_active_pane(
10131 single_entry_items[0].boxed_clone(),
10132 None,
10133 true,
10134 window,
10135 cx,
10136 );
10137 workspace.add_item_to_active_pane(
10138 single_entry_items[2].boxed_clone(),
10139 None,
10140 true,
10141 window,
10142 cx,
10143 );
10144 workspace.add_item_to_active_pane(
10145 single_entry_items[3].boxed_clone(),
10146 None,
10147 true,
10148 window,
10149 cx,
10150 );
10151 workspace.add_item_to_active_pane(
10152 single_entry_items[4].boxed_clone(),
10153 None,
10154 true,
10155 window,
10156 cx,
10157 );
10158
10159 let right_pane =
10160 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10161
10162 let boxed_clone = single_entry_items[1].boxed_clone();
10163 let right_pane = window.spawn(cx, async move |cx| {
10164 right_pane.await.inspect(|right_pane| {
10165 right_pane
10166 .update_in(cx, |pane, window, cx| {
10167 pane.add_item(boxed_clone, true, true, None, window, cx);
10168 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10169 })
10170 .unwrap();
10171 })
10172 });
10173
10174 (left_pane, right_pane)
10175 });
10176 let right_pane = right_pane.await.unwrap();
10177 cx.focus(&right_pane);
10178
10179 let close = right_pane.update_in(cx, |pane, window, cx| {
10180 pane.close_all_items(&CloseAllItems::default(), window, cx)
10181 .unwrap()
10182 });
10183 cx.executor().run_until_parked();
10184
10185 let msg = cx.pending_prompt().unwrap().0;
10186 assert!(msg.contains("1.txt"));
10187 assert!(!msg.contains("2.txt"));
10188 assert!(!msg.contains("3.txt"));
10189 assert!(!msg.contains("4.txt"));
10190
10191 // With best-effort close, cancelling item 1 keeps it open but items 4
10192 // and (3,4) still close since their entries exist in left pane.
10193 cx.simulate_prompt_answer("Cancel");
10194 close.await;
10195
10196 right_pane.read_with(cx, |pane, _| {
10197 assert_eq!(pane.items_len(), 1);
10198 });
10199
10200 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10201 left_pane
10202 .update_in(cx, |left_pane, window, cx| {
10203 left_pane.close_item_by_id(
10204 single_entry_items[3].entity_id(),
10205 SaveIntent::Skip,
10206 window,
10207 cx,
10208 )
10209 })
10210 .await
10211 .unwrap();
10212
10213 let close = left_pane.update_in(cx, |pane, window, cx| {
10214 pane.close_all_items(&CloseAllItems::default(), window, cx)
10215 .unwrap()
10216 });
10217 cx.executor().run_until_parked();
10218
10219 let details = cx.pending_prompt().unwrap().1;
10220 assert!(details.contains("0.txt"));
10221 assert!(details.contains("3.txt"));
10222 assert!(details.contains("4.txt"));
10223 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10224 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10225 // assert!(!details.contains("2.txt"));
10226
10227 cx.simulate_prompt_answer("Save all");
10228 cx.executor().run_until_parked();
10229 close.await;
10230
10231 left_pane.read_with(cx, |pane, _| {
10232 assert_eq!(pane.items_len(), 0);
10233 });
10234 }
10235
10236 #[gpui::test]
10237 async fn test_autosave(cx: &mut gpui::TestAppContext) {
10238 init_test(cx);
10239
10240 let fs = FakeFs::new(cx.executor());
10241 let project = Project::test(fs, [], cx).await;
10242 let (workspace, cx) =
10243 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10244 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10245
10246 let item = cx.new(|cx| {
10247 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10248 });
10249 let item_id = item.entity_id();
10250 workspace.update_in(cx, |workspace, window, cx| {
10251 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10252 });
10253
10254 // Autosave on window change.
10255 item.update(cx, |item, cx| {
10256 SettingsStore::update_global(cx, |settings, cx| {
10257 settings.update_user_settings(cx, |settings| {
10258 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10259 })
10260 });
10261 item.is_dirty = true;
10262 });
10263
10264 // Deactivating the window saves the file.
10265 cx.deactivate_window();
10266 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10267
10268 // Re-activating the window doesn't save the file.
10269 cx.update(|window, _| window.activate_window());
10270 cx.executor().run_until_parked();
10271 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10272
10273 // Autosave on focus change.
10274 item.update_in(cx, |item, window, cx| {
10275 cx.focus_self(window);
10276 SettingsStore::update_global(cx, |settings, cx| {
10277 settings.update_user_settings(cx, |settings| {
10278 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10279 })
10280 });
10281 item.is_dirty = true;
10282 });
10283 // Blurring the item saves the file.
10284 item.update_in(cx, |_, window, _| window.blur());
10285 cx.executor().run_until_parked();
10286 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10287
10288 // Deactivating the window still saves the file.
10289 item.update_in(cx, |item, window, cx| {
10290 cx.focus_self(window);
10291 item.is_dirty = true;
10292 });
10293 cx.deactivate_window();
10294 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10295
10296 // Autosave after delay.
10297 item.update(cx, |item, cx| {
10298 SettingsStore::update_global(cx, |settings, cx| {
10299 settings.update_user_settings(cx, |settings| {
10300 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10301 milliseconds: 500.into(),
10302 });
10303 })
10304 });
10305 item.is_dirty = true;
10306 cx.emit(ItemEvent::Edit);
10307 });
10308
10309 // Delay hasn't fully expired, so the file is still dirty and unsaved.
10310 cx.executor().advance_clock(Duration::from_millis(250));
10311 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10312
10313 // After delay expires, the file is saved.
10314 cx.executor().advance_clock(Duration::from_millis(250));
10315 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10316
10317 // Autosave after delay, should save earlier than delay if tab is closed
10318 item.update(cx, |item, cx| {
10319 item.is_dirty = true;
10320 cx.emit(ItemEvent::Edit);
10321 });
10322 cx.executor().advance_clock(Duration::from_millis(250));
10323 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10324
10325 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10326 pane.update_in(cx, |pane, window, cx| {
10327 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
10328 })
10329 .await
10330 .unwrap();
10331 assert!(!cx.has_pending_prompt());
10332 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10333
10334 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10335 workspace.update_in(cx, |workspace, window, cx| {
10336 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10337 });
10338 item.update_in(cx, |item, _window, cx| {
10339 item.is_dirty = true;
10340 for project_item in &mut item.project_items {
10341 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10342 }
10343 });
10344 cx.run_until_parked();
10345 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10346
10347 // Autosave on focus change, ensuring closing the tab counts as such.
10348 item.update(cx, |item, cx| {
10349 SettingsStore::update_global(cx, |settings, cx| {
10350 settings.update_user_settings(cx, |settings| {
10351 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10352 })
10353 });
10354 item.is_dirty = true;
10355 for project_item in &mut item.project_items {
10356 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10357 }
10358 });
10359
10360 pane.update_in(cx, |pane, window, cx| {
10361 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
10362 })
10363 .await
10364 .unwrap();
10365 assert!(!cx.has_pending_prompt());
10366 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10367
10368 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10369 workspace.update_in(cx, |workspace, window, cx| {
10370 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10371 });
10372 item.update_in(cx, |item, window, cx| {
10373 item.project_items[0].update(cx, |item, _| {
10374 item.entry_id = None;
10375 });
10376 item.is_dirty = true;
10377 window.blur();
10378 });
10379 cx.run_until_parked();
10380 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10381
10382 // Ensure autosave is prevented for deleted files also when closing the buffer.
10383 let _close_items = pane.update_in(cx, |pane, window, cx| {
10384 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
10385 });
10386 cx.run_until_parked();
10387 assert!(cx.has_pending_prompt());
10388 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10389 }
10390
10391 #[gpui::test]
10392 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10393 init_test(cx);
10394
10395 let fs = FakeFs::new(cx.executor());
10396
10397 let project = Project::test(fs, [], cx).await;
10398 let (workspace, cx) =
10399 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10400
10401 let item = cx.new(|cx| {
10402 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10403 });
10404 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10405 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10406 let toolbar_notify_count = Rc::new(RefCell::new(0));
10407
10408 workspace.update_in(cx, |workspace, window, cx| {
10409 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10410 let toolbar_notification_count = toolbar_notify_count.clone();
10411 cx.observe_in(&toolbar, window, move |_, _, _, _| {
10412 *toolbar_notification_count.borrow_mut() += 1
10413 })
10414 .detach();
10415 });
10416
10417 pane.read_with(cx, |pane, _| {
10418 assert!(!pane.can_navigate_backward());
10419 assert!(!pane.can_navigate_forward());
10420 });
10421
10422 item.update_in(cx, |item, _, cx| {
10423 item.set_state("one".to_string(), cx);
10424 });
10425
10426 // Toolbar must be notified to re-render the navigation buttons
10427 assert_eq!(*toolbar_notify_count.borrow(), 1);
10428
10429 pane.read_with(cx, |pane, _| {
10430 assert!(pane.can_navigate_backward());
10431 assert!(!pane.can_navigate_forward());
10432 });
10433
10434 workspace
10435 .update_in(cx, |workspace, window, cx| {
10436 workspace.go_back(pane.downgrade(), window, cx)
10437 })
10438 .await
10439 .unwrap();
10440
10441 assert_eq!(*toolbar_notify_count.borrow(), 2);
10442 pane.read_with(cx, |pane, _| {
10443 assert!(!pane.can_navigate_backward());
10444 assert!(pane.can_navigate_forward());
10445 });
10446 }
10447
10448 #[gpui::test]
10449 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
10450 init_test(cx);
10451 let fs = FakeFs::new(cx.executor());
10452
10453 let project = Project::test(fs, [], cx).await;
10454 let (workspace, cx) =
10455 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10456
10457 let panel = workspace.update_in(cx, |workspace, window, cx| {
10458 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10459 workspace.add_panel(panel.clone(), window, cx);
10460
10461 workspace
10462 .right_dock()
10463 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10464
10465 panel
10466 });
10467
10468 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10469 pane.update_in(cx, |pane, window, cx| {
10470 let item = cx.new(TestItem::new);
10471 pane.add_item(Box::new(item), true, true, None, window, cx);
10472 });
10473
10474 // Transfer focus from center to panel
10475 workspace.update_in(cx, |workspace, window, cx| {
10476 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10477 });
10478
10479 workspace.update_in(cx, |workspace, window, cx| {
10480 assert!(workspace.right_dock().read(cx).is_open());
10481 assert!(!panel.is_zoomed(window, cx));
10482 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10483 });
10484
10485 // Transfer focus from panel to center
10486 workspace.update_in(cx, |workspace, window, cx| {
10487 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10488 });
10489
10490 workspace.update_in(cx, |workspace, window, cx| {
10491 assert!(workspace.right_dock().read(cx).is_open());
10492 assert!(!panel.is_zoomed(window, cx));
10493 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10494 });
10495
10496 // Close the dock
10497 workspace.update_in(cx, |workspace, window, cx| {
10498 workspace.toggle_dock(DockPosition::Right, window, cx);
10499 });
10500
10501 workspace.update_in(cx, |workspace, window, cx| {
10502 assert!(!workspace.right_dock().read(cx).is_open());
10503 assert!(!panel.is_zoomed(window, cx));
10504 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10505 });
10506
10507 // Open the dock
10508 workspace.update_in(cx, |workspace, window, cx| {
10509 workspace.toggle_dock(DockPosition::Right, window, cx);
10510 });
10511
10512 workspace.update_in(cx, |workspace, window, cx| {
10513 assert!(workspace.right_dock().read(cx).is_open());
10514 assert!(!panel.is_zoomed(window, cx));
10515 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10516 });
10517
10518 // Focus and zoom panel
10519 panel.update_in(cx, |panel, window, cx| {
10520 cx.focus_self(window);
10521 panel.set_zoomed(true, window, cx)
10522 });
10523
10524 workspace.update_in(cx, |workspace, window, cx| {
10525 assert!(workspace.right_dock().read(cx).is_open());
10526 assert!(panel.is_zoomed(window, cx));
10527 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10528 });
10529
10530 // Transfer focus to the center closes the dock
10531 workspace.update_in(cx, |workspace, window, cx| {
10532 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10533 });
10534
10535 workspace.update_in(cx, |workspace, window, cx| {
10536 assert!(!workspace.right_dock().read(cx).is_open());
10537 assert!(panel.is_zoomed(window, cx));
10538 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10539 });
10540
10541 // Transferring focus back to the panel keeps it zoomed
10542 workspace.update_in(cx, |workspace, window, cx| {
10543 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10544 });
10545
10546 workspace.update_in(cx, |workspace, window, cx| {
10547 assert!(workspace.right_dock().read(cx).is_open());
10548 assert!(panel.is_zoomed(window, cx));
10549 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10550 });
10551
10552 // Close the dock while it is zoomed
10553 workspace.update_in(cx, |workspace, window, cx| {
10554 workspace.toggle_dock(DockPosition::Right, window, cx)
10555 });
10556
10557 workspace.update_in(cx, |workspace, window, cx| {
10558 assert!(!workspace.right_dock().read(cx).is_open());
10559 assert!(panel.is_zoomed(window, cx));
10560 assert!(workspace.zoomed.is_none());
10561 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10562 });
10563
10564 // Opening the dock, when it's zoomed, retains focus
10565 workspace.update_in(cx, |workspace, window, cx| {
10566 workspace.toggle_dock(DockPosition::Right, window, cx)
10567 });
10568
10569 workspace.update_in(cx, |workspace, window, cx| {
10570 assert!(workspace.right_dock().read(cx).is_open());
10571 assert!(panel.is_zoomed(window, cx));
10572 assert!(workspace.zoomed.is_some());
10573 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10574 });
10575
10576 // Unzoom and close the panel, zoom the active pane.
10577 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
10578 workspace.update_in(cx, |workspace, window, cx| {
10579 workspace.toggle_dock(DockPosition::Right, window, cx)
10580 });
10581 pane.update_in(cx, |pane, window, cx| {
10582 pane.toggle_zoom(&Default::default(), window, cx)
10583 });
10584
10585 // Opening a dock unzooms the pane.
10586 workspace.update_in(cx, |workspace, window, cx| {
10587 workspace.toggle_dock(DockPosition::Right, window, cx)
10588 });
10589 workspace.update_in(cx, |workspace, window, cx| {
10590 let pane = pane.read(cx);
10591 assert!(!pane.is_zoomed());
10592 assert!(!pane.focus_handle(cx).is_focused(window));
10593 assert!(workspace.right_dock().read(cx).is_open());
10594 assert!(workspace.zoomed.is_none());
10595 });
10596 }
10597
10598 #[gpui::test]
10599 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
10600 init_test(cx);
10601 let fs = FakeFs::new(cx.executor());
10602
10603 let project = Project::test(fs, [], cx).await;
10604 let (workspace, cx) =
10605 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10606
10607 let panel = workspace.update_in(cx, |workspace, window, cx| {
10608 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10609 workspace.add_panel(panel.clone(), window, cx);
10610 panel
10611 });
10612
10613 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10614 pane.update_in(cx, |pane, window, cx| {
10615 let item = cx.new(TestItem::new);
10616 pane.add_item(Box::new(item), true, true, None, window, cx);
10617 });
10618
10619 // Enable close_panel_on_toggle
10620 cx.update_global(|store: &mut SettingsStore, cx| {
10621 store.update_user_settings(cx, |settings| {
10622 settings.workspace.close_panel_on_toggle = Some(true);
10623 });
10624 });
10625
10626 // Panel starts closed. Toggling should open and focus it.
10627 workspace.update_in(cx, |workspace, window, cx| {
10628 assert!(!workspace.right_dock().read(cx).is_open());
10629 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10630 });
10631
10632 workspace.update_in(cx, |workspace, window, cx| {
10633 assert!(
10634 workspace.right_dock().read(cx).is_open(),
10635 "Dock should be open after toggling from center"
10636 );
10637 assert!(
10638 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10639 "Panel should be focused after toggling from center"
10640 );
10641 });
10642
10643 // Panel is open and focused. Toggling should close the panel and
10644 // return focus to the center.
10645 workspace.update_in(cx, |workspace, window, cx| {
10646 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10647 });
10648
10649 workspace.update_in(cx, |workspace, window, cx| {
10650 assert!(
10651 !workspace.right_dock().read(cx).is_open(),
10652 "Dock should be closed after toggling from focused panel"
10653 );
10654 assert!(
10655 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10656 "Panel should not be focused after toggling from focused panel"
10657 );
10658 });
10659
10660 // Open the dock and focus something else so the panel is open but not
10661 // focused. Toggling should focus the panel (not close it).
10662 workspace.update_in(cx, |workspace, window, cx| {
10663 workspace
10664 .right_dock()
10665 .update(cx, |dock, cx| dock.set_open(true, window, cx));
10666 window.focus(&pane.read(cx).focus_handle(cx), cx);
10667 });
10668
10669 workspace.update_in(cx, |workspace, window, cx| {
10670 assert!(workspace.right_dock().read(cx).is_open());
10671 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10672 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10673 });
10674
10675 workspace.update_in(cx, |workspace, window, cx| {
10676 assert!(
10677 workspace.right_dock().read(cx).is_open(),
10678 "Dock should remain open when toggling focuses an open-but-unfocused panel"
10679 );
10680 assert!(
10681 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10682 "Panel should be focused after toggling an open-but-unfocused panel"
10683 );
10684 });
10685
10686 // Now disable the setting and verify the original behavior: toggling
10687 // from a focused panel moves focus to center but leaves the dock open.
10688 cx.update_global(|store: &mut SettingsStore, cx| {
10689 store.update_user_settings(cx, |settings| {
10690 settings.workspace.close_panel_on_toggle = Some(false);
10691 });
10692 });
10693
10694 workspace.update_in(cx, |workspace, window, cx| {
10695 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10696 });
10697
10698 workspace.update_in(cx, |workspace, window, cx| {
10699 assert!(
10700 workspace.right_dock().read(cx).is_open(),
10701 "Dock should remain open when setting is disabled"
10702 );
10703 assert!(
10704 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10705 "Panel should not be focused after toggling with setting disabled"
10706 );
10707 });
10708 }
10709
10710 #[gpui::test]
10711 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
10712 init_test(cx);
10713 let fs = FakeFs::new(cx.executor());
10714
10715 let project = Project::test(fs, [], cx).await;
10716 let (workspace, cx) =
10717 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10718
10719 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
10720 workspace.active_pane().clone()
10721 });
10722
10723 // Add an item to the pane so it can be zoomed
10724 workspace.update_in(cx, |workspace, window, cx| {
10725 let item = cx.new(TestItem::new);
10726 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
10727 });
10728
10729 // Initially not zoomed
10730 workspace.update_in(cx, |workspace, _window, cx| {
10731 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
10732 assert!(
10733 workspace.zoomed.is_none(),
10734 "Workspace should track no zoomed pane"
10735 );
10736 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
10737 });
10738
10739 // Zoom In
10740 pane.update_in(cx, |pane, window, cx| {
10741 pane.zoom_in(&crate::ZoomIn, window, cx);
10742 });
10743
10744 workspace.update_in(cx, |workspace, window, cx| {
10745 assert!(
10746 pane.read(cx).is_zoomed(),
10747 "Pane should be zoomed after ZoomIn"
10748 );
10749 assert!(
10750 workspace.zoomed.is_some(),
10751 "Workspace should track the zoomed pane"
10752 );
10753 assert!(
10754 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
10755 "ZoomIn should focus the pane"
10756 );
10757 });
10758
10759 // Zoom In again is a no-op
10760 pane.update_in(cx, |pane, window, cx| {
10761 pane.zoom_in(&crate::ZoomIn, window, cx);
10762 });
10763
10764 workspace.update_in(cx, |workspace, window, cx| {
10765 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
10766 assert!(
10767 workspace.zoomed.is_some(),
10768 "Workspace still tracks zoomed pane"
10769 );
10770 assert!(
10771 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
10772 "Pane remains focused after repeated ZoomIn"
10773 );
10774 });
10775
10776 // Zoom Out
10777 pane.update_in(cx, |pane, window, cx| {
10778 pane.zoom_out(&crate::ZoomOut, window, cx);
10779 });
10780
10781 workspace.update_in(cx, |workspace, _window, cx| {
10782 assert!(
10783 !pane.read(cx).is_zoomed(),
10784 "Pane should unzoom after ZoomOut"
10785 );
10786 assert!(
10787 workspace.zoomed.is_none(),
10788 "Workspace clears zoom tracking after ZoomOut"
10789 );
10790 });
10791
10792 // Zoom Out again is a no-op
10793 pane.update_in(cx, |pane, window, cx| {
10794 pane.zoom_out(&crate::ZoomOut, window, cx);
10795 });
10796
10797 workspace.update_in(cx, |workspace, _window, cx| {
10798 assert!(
10799 !pane.read(cx).is_zoomed(),
10800 "Second ZoomOut keeps pane unzoomed"
10801 );
10802 assert!(
10803 workspace.zoomed.is_none(),
10804 "Workspace remains without zoomed pane"
10805 );
10806 });
10807 }
10808
10809 #[gpui::test]
10810 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
10811 init_test(cx);
10812 let fs = FakeFs::new(cx.executor());
10813
10814 let project = Project::test(fs, [], cx).await;
10815 let (workspace, cx) =
10816 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10817 workspace.update_in(cx, |workspace, window, cx| {
10818 // Open two docks
10819 let left_dock = workspace.dock_at_position(DockPosition::Left);
10820 let right_dock = workspace.dock_at_position(DockPosition::Right);
10821
10822 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10823 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10824
10825 assert!(left_dock.read(cx).is_open());
10826 assert!(right_dock.read(cx).is_open());
10827 });
10828
10829 workspace.update_in(cx, |workspace, window, cx| {
10830 // Toggle all docks - should close both
10831 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10832
10833 let left_dock = workspace.dock_at_position(DockPosition::Left);
10834 let right_dock = workspace.dock_at_position(DockPosition::Right);
10835 assert!(!left_dock.read(cx).is_open());
10836 assert!(!right_dock.read(cx).is_open());
10837 });
10838
10839 workspace.update_in(cx, |workspace, window, cx| {
10840 // Toggle again - should reopen both
10841 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10842
10843 let left_dock = workspace.dock_at_position(DockPosition::Left);
10844 let right_dock = workspace.dock_at_position(DockPosition::Right);
10845 assert!(left_dock.read(cx).is_open());
10846 assert!(right_dock.read(cx).is_open());
10847 });
10848 }
10849
10850 #[gpui::test]
10851 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
10852 init_test(cx);
10853 let fs = FakeFs::new(cx.executor());
10854
10855 let project = Project::test(fs, [], cx).await;
10856 let (workspace, cx) =
10857 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10858 workspace.update_in(cx, |workspace, window, cx| {
10859 // Open two docks
10860 let left_dock = workspace.dock_at_position(DockPosition::Left);
10861 let right_dock = workspace.dock_at_position(DockPosition::Right);
10862
10863 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10864 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10865
10866 assert!(left_dock.read(cx).is_open());
10867 assert!(right_dock.read(cx).is_open());
10868 });
10869
10870 workspace.update_in(cx, |workspace, window, cx| {
10871 // Close them manually
10872 workspace.toggle_dock(DockPosition::Left, window, cx);
10873 workspace.toggle_dock(DockPosition::Right, window, cx);
10874
10875 let left_dock = workspace.dock_at_position(DockPosition::Left);
10876 let right_dock = workspace.dock_at_position(DockPosition::Right);
10877 assert!(!left_dock.read(cx).is_open());
10878 assert!(!right_dock.read(cx).is_open());
10879 });
10880
10881 workspace.update_in(cx, |workspace, window, cx| {
10882 // Toggle all docks - only last closed (right dock) should reopen
10883 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10884
10885 let left_dock = workspace.dock_at_position(DockPosition::Left);
10886 let right_dock = workspace.dock_at_position(DockPosition::Right);
10887 assert!(!left_dock.read(cx).is_open());
10888 assert!(right_dock.read(cx).is_open());
10889 });
10890 }
10891
10892 #[gpui::test]
10893 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
10894 init_test(cx);
10895 let fs = FakeFs::new(cx.executor());
10896 let project = Project::test(fs, [], cx).await;
10897 let (workspace, cx) =
10898 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10899
10900 // Open two docks (left and right) with one panel each
10901 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
10902 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
10903 workspace.add_panel(left_panel.clone(), window, cx);
10904
10905 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
10906 workspace.add_panel(right_panel.clone(), window, cx);
10907
10908 workspace.toggle_dock(DockPosition::Left, window, cx);
10909 workspace.toggle_dock(DockPosition::Right, window, cx);
10910
10911 // Verify initial state
10912 assert!(
10913 workspace.left_dock().read(cx).is_open(),
10914 "Left dock should be open"
10915 );
10916 assert_eq!(
10917 workspace
10918 .left_dock()
10919 .read(cx)
10920 .visible_panel()
10921 .unwrap()
10922 .panel_id(),
10923 left_panel.panel_id(),
10924 "Left panel should be visible in left dock"
10925 );
10926 assert!(
10927 workspace.right_dock().read(cx).is_open(),
10928 "Right dock should be open"
10929 );
10930 assert_eq!(
10931 workspace
10932 .right_dock()
10933 .read(cx)
10934 .visible_panel()
10935 .unwrap()
10936 .panel_id(),
10937 right_panel.panel_id(),
10938 "Right panel should be visible in right dock"
10939 );
10940 assert!(
10941 !workspace.bottom_dock().read(cx).is_open(),
10942 "Bottom dock should be closed"
10943 );
10944
10945 (left_panel, right_panel)
10946 });
10947
10948 // Focus the left panel and move it to the next position (bottom dock)
10949 workspace.update_in(cx, |workspace, window, cx| {
10950 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
10951 assert!(
10952 left_panel.read(cx).focus_handle(cx).is_focused(window),
10953 "Left panel should be focused"
10954 );
10955 });
10956
10957 cx.dispatch_action(MoveFocusedPanelToNextPosition);
10958
10959 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
10960 workspace.update(cx, |workspace, cx| {
10961 assert!(
10962 !workspace.left_dock().read(cx).is_open(),
10963 "Left dock should be closed"
10964 );
10965 assert!(
10966 workspace.bottom_dock().read(cx).is_open(),
10967 "Bottom dock should now be open"
10968 );
10969 assert_eq!(
10970 left_panel.read(cx).position,
10971 DockPosition::Bottom,
10972 "Left panel should now be in the bottom dock"
10973 );
10974 assert_eq!(
10975 workspace
10976 .bottom_dock()
10977 .read(cx)
10978 .visible_panel()
10979 .unwrap()
10980 .panel_id(),
10981 left_panel.panel_id(),
10982 "Left panel should be the visible panel in the bottom dock"
10983 );
10984 });
10985
10986 // Toggle all docks off
10987 workspace.update_in(cx, |workspace, window, cx| {
10988 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10989 assert!(
10990 !workspace.left_dock().read(cx).is_open(),
10991 "Left dock should be closed"
10992 );
10993 assert!(
10994 !workspace.right_dock().read(cx).is_open(),
10995 "Right dock should be closed"
10996 );
10997 assert!(
10998 !workspace.bottom_dock().read(cx).is_open(),
10999 "Bottom dock should be closed"
11000 );
11001 });
11002
11003 // Toggle all docks back on and verify positions are restored
11004 workspace.update_in(cx, |workspace, window, cx| {
11005 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11006 assert!(
11007 !workspace.left_dock().read(cx).is_open(),
11008 "Left dock should remain closed"
11009 );
11010 assert!(
11011 workspace.right_dock().read(cx).is_open(),
11012 "Right dock should remain open"
11013 );
11014 assert!(
11015 workspace.bottom_dock().read(cx).is_open(),
11016 "Bottom dock should remain open"
11017 );
11018 assert_eq!(
11019 left_panel.read(cx).position,
11020 DockPosition::Bottom,
11021 "Left panel should remain in the bottom dock"
11022 );
11023 assert_eq!(
11024 right_panel.read(cx).position,
11025 DockPosition::Right,
11026 "Right panel should remain in the right dock"
11027 );
11028 assert_eq!(
11029 workspace
11030 .bottom_dock()
11031 .read(cx)
11032 .visible_panel()
11033 .unwrap()
11034 .panel_id(),
11035 left_panel.panel_id(),
11036 "Left panel should be the visible panel in the right dock"
11037 );
11038 });
11039 }
11040
11041 #[gpui::test]
11042 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11043 init_test(cx);
11044
11045 let fs = FakeFs::new(cx.executor());
11046
11047 let project = Project::test(fs, None, cx).await;
11048 let (workspace, cx) =
11049 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11050
11051 // Let's arrange the panes like this:
11052 //
11053 // +-----------------------+
11054 // | top |
11055 // +------+--------+-------+
11056 // | left | center | right |
11057 // +------+--------+-------+
11058 // | bottom |
11059 // +-----------------------+
11060
11061 let top_item = cx.new(|cx| {
11062 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11063 });
11064 let bottom_item = cx.new(|cx| {
11065 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11066 });
11067 let left_item = cx.new(|cx| {
11068 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11069 });
11070 let right_item = cx.new(|cx| {
11071 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11072 });
11073 let center_item = cx.new(|cx| {
11074 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11075 });
11076
11077 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11078 let top_pane_id = workspace.active_pane().entity_id();
11079 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11080 workspace.split_pane(
11081 workspace.active_pane().clone(),
11082 SplitDirection::Down,
11083 window,
11084 cx,
11085 );
11086 top_pane_id
11087 });
11088 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11089 let bottom_pane_id = workspace.active_pane().entity_id();
11090 workspace.add_item_to_active_pane(
11091 Box::new(bottom_item.clone()),
11092 None,
11093 false,
11094 window,
11095 cx,
11096 );
11097 workspace.split_pane(
11098 workspace.active_pane().clone(),
11099 SplitDirection::Up,
11100 window,
11101 cx,
11102 );
11103 bottom_pane_id
11104 });
11105 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11106 let left_pane_id = workspace.active_pane().entity_id();
11107 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11108 workspace.split_pane(
11109 workspace.active_pane().clone(),
11110 SplitDirection::Right,
11111 window,
11112 cx,
11113 );
11114 left_pane_id
11115 });
11116 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11117 let right_pane_id = workspace.active_pane().entity_id();
11118 workspace.add_item_to_active_pane(
11119 Box::new(right_item.clone()),
11120 None,
11121 false,
11122 window,
11123 cx,
11124 );
11125 workspace.split_pane(
11126 workspace.active_pane().clone(),
11127 SplitDirection::Left,
11128 window,
11129 cx,
11130 );
11131 right_pane_id
11132 });
11133 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11134 let center_pane_id = workspace.active_pane().entity_id();
11135 workspace.add_item_to_active_pane(
11136 Box::new(center_item.clone()),
11137 None,
11138 false,
11139 window,
11140 cx,
11141 );
11142 center_pane_id
11143 });
11144 cx.executor().run_until_parked();
11145
11146 workspace.update_in(cx, |workspace, window, cx| {
11147 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11148
11149 // Join into next from center pane into right
11150 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11151 });
11152
11153 workspace.update_in(cx, |workspace, window, cx| {
11154 let active_pane = workspace.active_pane();
11155 assert_eq!(right_pane_id, active_pane.entity_id());
11156 assert_eq!(2, active_pane.read(cx).items_len());
11157 let item_ids_in_pane =
11158 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11159 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11160 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11161
11162 // Join into next from right pane into bottom
11163 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11164 });
11165
11166 workspace.update_in(cx, |workspace, window, cx| {
11167 let active_pane = workspace.active_pane();
11168 assert_eq!(bottom_pane_id, active_pane.entity_id());
11169 assert_eq!(3, active_pane.read(cx).items_len());
11170 let item_ids_in_pane =
11171 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11172 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11173 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11174 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11175
11176 // Join into next from bottom pane into left
11177 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11178 });
11179
11180 workspace.update_in(cx, |workspace, window, cx| {
11181 let active_pane = workspace.active_pane();
11182 assert_eq!(left_pane_id, active_pane.entity_id());
11183 assert_eq!(4, active_pane.read(cx).items_len());
11184 let item_ids_in_pane =
11185 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11186 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11187 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11188 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11189 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11190
11191 // Join into next from left pane into top
11192 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11193 });
11194
11195 workspace.update_in(cx, |workspace, window, cx| {
11196 let active_pane = workspace.active_pane();
11197 assert_eq!(top_pane_id, active_pane.entity_id());
11198 assert_eq!(5, active_pane.read(cx).items_len());
11199 let item_ids_in_pane =
11200 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11201 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11202 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11203 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11204 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11205 assert!(item_ids_in_pane.contains(&top_item.item_id()));
11206
11207 // Single pane left: no-op
11208 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11209 });
11210
11211 workspace.update(cx, |workspace, _cx| {
11212 let active_pane = workspace.active_pane();
11213 assert_eq!(top_pane_id, active_pane.entity_id());
11214 });
11215 }
11216
11217 fn add_an_item_to_active_pane(
11218 cx: &mut VisualTestContext,
11219 workspace: &Entity<Workspace>,
11220 item_id: u64,
11221 ) -> Entity<TestItem> {
11222 let item = cx.new(|cx| {
11223 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11224 item_id,
11225 "item{item_id}.txt",
11226 cx,
11227 )])
11228 });
11229 workspace.update_in(cx, |workspace, window, cx| {
11230 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11231 });
11232 item
11233 }
11234
11235 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11236 workspace.update_in(cx, |workspace, window, cx| {
11237 workspace.split_pane(
11238 workspace.active_pane().clone(),
11239 SplitDirection::Right,
11240 window,
11241 cx,
11242 )
11243 })
11244 }
11245
11246 #[gpui::test]
11247 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11248 init_test(cx);
11249 let fs = FakeFs::new(cx.executor());
11250 let project = Project::test(fs, None, cx).await;
11251 let (workspace, cx) =
11252 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11253
11254 add_an_item_to_active_pane(cx, &workspace, 1);
11255 split_pane(cx, &workspace);
11256 add_an_item_to_active_pane(cx, &workspace, 2);
11257 split_pane(cx, &workspace); // empty pane
11258 split_pane(cx, &workspace);
11259 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11260
11261 cx.executor().run_until_parked();
11262
11263 workspace.update(cx, |workspace, cx| {
11264 let num_panes = workspace.panes().len();
11265 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11266 let active_item = workspace
11267 .active_pane()
11268 .read(cx)
11269 .active_item()
11270 .expect("item is in focus");
11271
11272 assert_eq!(num_panes, 4);
11273 assert_eq!(num_items_in_current_pane, 1);
11274 assert_eq!(active_item.item_id(), last_item.item_id());
11275 });
11276
11277 workspace.update_in(cx, |workspace, window, cx| {
11278 workspace.join_all_panes(window, cx);
11279 });
11280
11281 workspace.update(cx, |workspace, cx| {
11282 let num_panes = workspace.panes().len();
11283 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11284 let active_item = workspace
11285 .active_pane()
11286 .read(cx)
11287 .active_item()
11288 .expect("item is in focus");
11289
11290 assert_eq!(num_panes, 1);
11291 assert_eq!(num_items_in_current_pane, 3);
11292 assert_eq!(active_item.item_id(), last_item.item_id());
11293 });
11294 }
11295 struct TestModal(FocusHandle);
11296
11297 impl TestModal {
11298 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11299 Self(cx.focus_handle())
11300 }
11301 }
11302
11303 impl EventEmitter<DismissEvent> for TestModal {}
11304
11305 impl Focusable for TestModal {
11306 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11307 self.0.clone()
11308 }
11309 }
11310
11311 impl ModalView for TestModal {}
11312
11313 impl Render for TestModal {
11314 fn render(
11315 &mut self,
11316 _window: &mut Window,
11317 _cx: &mut Context<TestModal>,
11318 ) -> impl IntoElement {
11319 div().track_focus(&self.0)
11320 }
11321 }
11322
11323 #[gpui::test]
11324 async fn test_panels(cx: &mut gpui::TestAppContext) {
11325 init_test(cx);
11326 let fs = FakeFs::new(cx.executor());
11327
11328 let project = Project::test(fs, [], cx).await;
11329 let (workspace, cx) =
11330 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11331
11332 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11333 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11334 workspace.add_panel(panel_1.clone(), window, cx);
11335 workspace.toggle_dock(DockPosition::Left, window, cx);
11336 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11337 workspace.add_panel(panel_2.clone(), window, cx);
11338 workspace.toggle_dock(DockPosition::Right, window, cx);
11339
11340 let left_dock = workspace.left_dock();
11341 assert_eq!(
11342 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11343 panel_1.panel_id()
11344 );
11345 assert_eq!(
11346 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11347 panel_1.size(window, cx)
11348 );
11349
11350 left_dock.update(cx, |left_dock, cx| {
11351 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11352 });
11353 assert_eq!(
11354 workspace
11355 .right_dock()
11356 .read(cx)
11357 .visible_panel()
11358 .unwrap()
11359 .panel_id(),
11360 panel_2.panel_id(),
11361 );
11362
11363 (panel_1, panel_2)
11364 });
11365
11366 // Move panel_1 to the right
11367 panel_1.update_in(cx, |panel_1, window, cx| {
11368 panel_1.set_position(DockPosition::Right, window, cx)
11369 });
11370
11371 workspace.update_in(cx, |workspace, window, cx| {
11372 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11373 // Since it was the only panel on the left, the left dock should now be closed.
11374 assert!(!workspace.left_dock().read(cx).is_open());
11375 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11376 let right_dock = workspace.right_dock();
11377 assert_eq!(
11378 right_dock.read(cx).visible_panel().unwrap().panel_id(),
11379 panel_1.panel_id()
11380 );
11381 assert_eq!(
11382 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11383 px(1337.)
11384 );
11385
11386 // Now we move panel_2 to the left
11387 panel_2.set_position(DockPosition::Left, window, cx);
11388 });
11389
11390 workspace.update(cx, |workspace, cx| {
11391 // Since panel_2 was not visible on the right, we don't open the left dock.
11392 assert!(!workspace.left_dock().read(cx).is_open());
11393 // And the right dock is unaffected in its displaying of panel_1
11394 assert!(workspace.right_dock().read(cx).is_open());
11395 assert_eq!(
11396 workspace
11397 .right_dock()
11398 .read(cx)
11399 .visible_panel()
11400 .unwrap()
11401 .panel_id(),
11402 panel_1.panel_id(),
11403 );
11404 });
11405
11406 // Move panel_1 back to the left
11407 panel_1.update_in(cx, |panel_1, window, cx| {
11408 panel_1.set_position(DockPosition::Left, window, cx)
11409 });
11410
11411 workspace.update_in(cx, |workspace, window, cx| {
11412 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11413 let left_dock = workspace.left_dock();
11414 assert!(left_dock.read(cx).is_open());
11415 assert_eq!(
11416 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11417 panel_1.panel_id()
11418 );
11419 assert_eq!(
11420 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11421 px(1337.)
11422 );
11423 // And the right dock should be closed as it no longer has any panels.
11424 assert!(!workspace.right_dock().read(cx).is_open());
11425
11426 // Now we move panel_1 to the bottom
11427 panel_1.set_position(DockPosition::Bottom, window, cx);
11428 });
11429
11430 workspace.update_in(cx, |workspace, window, cx| {
11431 // Since panel_1 was visible on the left, we close the left dock.
11432 assert!(!workspace.left_dock().read(cx).is_open());
11433 // The bottom dock is sized based on the panel's default size,
11434 // since the panel orientation changed from vertical to horizontal.
11435 let bottom_dock = workspace.bottom_dock();
11436 assert_eq!(
11437 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
11438 panel_1.size(window, cx),
11439 );
11440 // Close bottom dock and move panel_1 back to the left.
11441 bottom_dock.update(cx, |bottom_dock, cx| {
11442 bottom_dock.set_open(false, window, cx)
11443 });
11444 panel_1.set_position(DockPosition::Left, window, cx);
11445 });
11446
11447 // Emit activated event on panel 1
11448 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
11449
11450 // Now the left dock is open and panel_1 is active and focused.
11451 workspace.update_in(cx, |workspace, window, cx| {
11452 let left_dock = workspace.left_dock();
11453 assert!(left_dock.read(cx).is_open());
11454 assert_eq!(
11455 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11456 panel_1.panel_id(),
11457 );
11458 assert!(panel_1.focus_handle(cx).is_focused(window));
11459 });
11460
11461 // Emit closed event on panel 2, which is not active
11462 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11463
11464 // Wo don't close the left dock, because panel_2 wasn't the active panel
11465 workspace.update(cx, |workspace, cx| {
11466 let left_dock = workspace.left_dock();
11467 assert!(left_dock.read(cx).is_open());
11468 assert_eq!(
11469 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11470 panel_1.panel_id(),
11471 );
11472 });
11473
11474 // Emitting a ZoomIn event shows the panel as zoomed.
11475 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
11476 workspace.read_with(cx, |workspace, _| {
11477 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11478 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
11479 });
11480
11481 // Move panel to another dock while it is zoomed
11482 panel_1.update_in(cx, |panel, window, cx| {
11483 panel.set_position(DockPosition::Right, window, cx)
11484 });
11485 workspace.read_with(cx, |workspace, _| {
11486 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11487
11488 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11489 });
11490
11491 // This is a helper for getting a:
11492 // - valid focus on an element,
11493 // - that isn't a part of the panes and panels system of the Workspace,
11494 // - and doesn't trigger the 'on_focus_lost' API.
11495 let focus_other_view = {
11496 let workspace = workspace.clone();
11497 move |cx: &mut VisualTestContext| {
11498 workspace.update_in(cx, |workspace, window, cx| {
11499 if workspace.active_modal::<TestModal>(cx).is_some() {
11500 workspace.toggle_modal(window, cx, TestModal::new);
11501 workspace.toggle_modal(window, cx, TestModal::new);
11502 } else {
11503 workspace.toggle_modal(window, cx, TestModal::new);
11504 }
11505 })
11506 }
11507 };
11508
11509 // If focus is transferred to another view that's not a panel or another pane, we still show
11510 // the panel as zoomed.
11511 focus_other_view(cx);
11512 workspace.read_with(cx, |workspace, _| {
11513 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11514 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11515 });
11516
11517 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
11518 workspace.update_in(cx, |_workspace, window, cx| {
11519 cx.focus_self(window);
11520 });
11521 workspace.read_with(cx, |workspace, _| {
11522 assert_eq!(workspace.zoomed, None);
11523 assert_eq!(workspace.zoomed_position, None);
11524 });
11525
11526 // If focus is transferred again to another view that's not a panel or a pane, we won't
11527 // show the panel as zoomed because it wasn't zoomed before.
11528 focus_other_view(cx);
11529 workspace.read_with(cx, |workspace, _| {
11530 assert_eq!(workspace.zoomed, None);
11531 assert_eq!(workspace.zoomed_position, None);
11532 });
11533
11534 // When the panel is activated, it is zoomed again.
11535 cx.dispatch_action(ToggleRightDock);
11536 workspace.read_with(cx, |workspace, _| {
11537 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11538 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11539 });
11540
11541 // Emitting a ZoomOut event unzooms the panel.
11542 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
11543 workspace.read_with(cx, |workspace, _| {
11544 assert_eq!(workspace.zoomed, None);
11545 assert_eq!(workspace.zoomed_position, None);
11546 });
11547
11548 // Emit closed event on panel 1, which is active
11549 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11550
11551 // Now the left dock is closed, because panel_1 was the active panel
11552 workspace.update(cx, |workspace, cx| {
11553 let right_dock = workspace.right_dock();
11554 assert!(!right_dock.read(cx).is_open());
11555 });
11556 }
11557
11558 #[gpui::test]
11559 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
11560 init_test(cx);
11561
11562 let fs = FakeFs::new(cx.background_executor.clone());
11563 let project = Project::test(fs, [], cx).await;
11564 let (workspace, cx) =
11565 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11566 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11567
11568 let dirty_regular_buffer = cx.new(|cx| {
11569 TestItem::new(cx)
11570 .with_dirty(true)
11571 .with_label("1.txt")
11572 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11573 });
11574 let dirty_regular_buffer_2 = cx.new(|cx| {
11575 TestItem::new(cx)
11576 .with_dirty(true)
11577 .with_label("2.txt")
11578 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11579 });
11580 let dirty_multi_buffer_with_both = cx.new(|cx| {
11581 TestItem::new(cx)
11582 .with_dirty(true)
11583 .with_buffer_kind(ItemBufferKind::Multibuffer)
11584 .with_label("Fake Project Search")
11585 .with_project_items(&[
11586 dirty_regular_buffer.read(cx).project_items[0].clone(),
11587 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11588 ])
11589 });
11590 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11591 workspace.update_in(cx, |workspace, window, cx| {
11592 workspace.add_item(
11593 pane.clone(),
11594 Box::new(dirty_regular_buffer.clone()),
11595 None,
11596 false,
11597 false,
11598 window,
11599 cx,
11600 );
11601 workspace.add_item(
11602 pane.clone(),
11603 Box::new(dirty_regular_buffer_2.clone()),
11604 None,
11605 false,
11606 false,
11607 window,
11608 cx,
11609 );
11610 workspace.add_item(
11611 pane.clone(),
11612 Box::new(dirty_multi_buffer_with_both.clone()),
11613 None,
11614 false,
11615 false,
11616 window,
11617 cx,
11618 );
11619 });
11620
11621 pane.update_in(cx, |pane, window, cx| {
11622 pane.activate_item(2, true, true, window, cx);
11623 assert_eq!(
11624 pane.active_item().unwrap().item_id(),
11625 multi_buffer_with_both_files_id,
11626 "Should select the multi buffer in the pane"
11627 );
11628 });
11629 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11630 pane.close_other_items(
11631 &CloseOtherItems {
11632 save_intent: Some(SaveIntent::Save),
11633 close_pinned: true,
11634 },
11635 None,
11636 window,
11637 cx,
11638 )
11639 });
11640 cx.background_executor.run_until_parked();
11641 assert!(!cx.has_pending_prompt());
11642 close_all_but_multi_buffer_task
11643 .await
11644 .expect("Closing all buffers but the multi buffer failed");
11645 pane.update(cx, |pane, cx| {
11646 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
11647 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
11648 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
11649 assert_eq!(pane.items_len(), 1);
11650 assert_eq!(
11651 pane.active_item().unwrap().item_id(),
11652 multi_buffer_with_both_files_id,
11653 "Should have only the multi buffer left in the pane"
11654 );
11655 assert!(
11656 dirty_multi_buffer_with_both.read(cx).is_dirty,
11657 "The multi buffer containing the unsaved buffer should still be dirty"
11658 );
11659 });
11660
11661 dirty_regular_buffer.update(cx, |buffer, cx| {
11662 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
11663 });
11664
11665 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11666 pane.close_active_item(
11667 &CloseActiveItem {
11668 save_intent: Some(SaveIntent::Close),
11669 close_pinned: false,
11670 },
11671 window,
11672 cx,
11673 )
11674 });
11675 cx.background_executor.run_until_parked();
11676 assert!(
11677 cx.has_pending_prompt(),
11678 "Dirty multi buffer should prompt a save dialog"
11679 );
11680 cx.simulate_prompt_answer("Save");
11681 cx.background_executor.run_until_parked();
11682 close_multi_buffer_task
11683 .await
11684 .expect("Closing the multi buffer failed");
11685 pane.update(cx, |pane, cx| {
11686 assert_eq!(
11687 dirty_multi_buffer_with_both.read(cx).save_count,
11688 1,
11689 "Multi buffer item should get be saved"
11690 );
11691 // Test impl does not save inner items, so we do not assert them
11692 assert_eq!(
11693 pane.items_len(),
11694 0,
11695 "No more items should be left in the pane"
11696 );
11697 assert!(pane.active_item().is_none());
11698 });
11699 }
11700
11701 #[gpui::test]
11702 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
11703 cx: &mut TestAppContext,
11704 ) {
11705 init_test(cx);
11706
11707 let fs = FakeFs::new(cx.background_executor.clone());
11708 let project = Project::test(fs, [], cx).await;
11709 let (workspace, cx) =
11710 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11711 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11712
11713 let dirty_regular_buffer = cx.new(|cx| {
11714 TestItem::new(cx)
11715 .with_dirty(true)
11716 .with_label("1.txt")
11717 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11718 });
11719 let dirty_regular_buffer_2 = cx.new(|cx| {
11720 TestItem::new(cx)
11721 .with_dirty(true)
11722 .with_label("2.txt")
11723 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11724 });
11725 let clear_regular_buffer = cx.new(|cx| {
11726 TestItem::new(cx)
11727 .with_label("3.txt")
11728 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
11729 });
11730
11731 let dirty_multi_buffer_with_both = cx.new(|cx| {
11732 TestItem::new(cx)
11733 .with_dirty(true)
11734 .with_buffer_kind(ItemBufferKind::Multibuffer)
11735 .with_label("Fake Project Search")
11736 .with_project_items(&[
11737 dirty_regular_buffer.read(cx).project_items[0].clone(),
11738 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11739 clear_regular_buffer.read(cx).project_items[0].clone(),
11740 ])
11741 });
11742 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11743 workspace.update_in(cx, |workspace, window, cx| {
11744 workspace.add_item(
11745 pane.clone(),
11746 Box::new(dirty_regular_buffer.clone()),
11747 None,
11748 false,
11749 false,
11750 window,
11751 cx,
11752 );
11753 workspace.add_item(
11754 pane.clone(),
11755 Box::new(dirty_multi_buffer_with_both.clone()),
11756 None,
11757 false,
11758 false,
11759 window,
11760 cx,
11761 );
11762 });
11763
11764 pane.update_in(cx, |pane, window, cx| {
11765 pane.activate_item(1, true, true, window, cx);
11766 assert_eq!(
11767 pane.active_item().unwrap().item_id(),
11768 multi_buffer_with_both_files_id,
11769 "Should select the multi buffer in the pane"
11770 );
11771 });
11772 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11773 pane.close_active_item(
11774 &CloseActiveItem {
11775 save_intent: None,
11776 close_pinned: false,
11777 },
11778 window,
11779 cx,
11780 )
11781 });
11782 cx.background_executor.run_until_parked();
11783 assert!(
11784 cx.has_pending_prompt(),
11785 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
11786 );
11787 }
11788
11789 /// Tests that when `close_on_file_delete` is enabled, files are automatically
11790 /// closed when they are deleted from disk.
11791 #[gpui::test]
11792 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
11793 init_test(cx);
11794
11795 // Enable the close_on_disk_deletion setting
11796 cx.update_global(|store: &mut SettingsStore, cx| {
11797 store.update_user_settings(cx, |settings| {
11798 settings.workspace.close_on_file_delete = Some(true);
11799 });
11800 });
11801
11802 let fs = FakeFs::new(cx.background_executor.clone());
11803 let project = Project::test(fs, [], cx).await;
11804 let (workspace, cx) =
11805 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11806 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11807
11808 // Create a test item that simulates a file
11809 let item = cx.new(|cx| {
11810 TestItem::new(cx)
11811 .with_label("test.txt")
11812 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11813 });
11814
11815 // Add item to workspace
11816 workspace.update_in(cx, |workspace, window, cx| {
11817 workspace.add_item(
11818 pane.clone(),
11819 Box::new(item.clone()),
11820 None,
11821 false,
11822 false,
11823 window,
11824 cx,
11825 );
11826 });
11827
11828 // Verify the item is in the pane
11829 pane.read_with(cx, |pane, _| {
11830 assert_eq!(pane.items().count(), 1);
11831 });
11832
11833 // Simulate file deletion by setting the item's deleted state
11834 item.update(cx, |item, _| {
11835 item.set_has_deleted_file(true);
11836 });
11837
11838 // Emit UpdateTab event to trigger the close behavior
11839 cx.run_until_parked();
11840 item.update(cx, |_, cx| {
11841 cx.emit(ItemEvent::UpdateTab);
11842 });
11843
11844 // Allow the close operation to complete
11845 cx.run_until_parked();
11846
11847 // Verify the item was automatically closed
11848 pane.read_with(cx, |pane, _| {
11849 assert_eq!(
11850 pane.items().count(),
11851 0,
11852 "Item should be automatically closed when file is deleted"
11853 );
11854 });
11855 }
11856
11857 /// Tests that when `close_on_file_delete` is disabled (default), files remain
11858 /// open with a strikethrough when they are deleted from disk.
11859 #[gpui::test]
11860 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
11861 init_test(cx);
11862
11863 // Ensure close_on_disk_deletion is disabled (default)
11864 cx.update_global(|store: &mut SettingsStore, cx| {
11865 store.update_user_settings(cx, |settings| {
11866 settings.workspace.close_on_file_delete = Some(false);
11867 });
11868 });
11869
11870 let fs = FakeFs::new(cx.background_executor.clone());
11871 let project = Project::test(fs, [], cx).await;
11872 let (workspace, cx) =
11873 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11874 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11875
11876 // Create a test item that simulates a file
11877 let item = cx.new(|cx| {
11878 TestItem::new(cx)
11879 .with_label("test.txt")
11880 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11881 });
11882
11883 // Add item to workspace
11884 workspace.update_in(cx, |workspace, window, cx| {
11885 workspace.add_item(
11886 pane.clone(),
11887 Box::new(item.clone()),
11888 None,
11889 false,
11890 false,
11891 window,
11892 cx,
11893 );
11894 });
11895
11896 // Verify the item is in the pane
11897 pane.read_with(cx, |pane, _| {
11898 assert_eq!(pane.items().count(), 1);
11899 });
11900
11901 // Simulate file deletion
11902 item.update(cx, |item, _| {
11903 item.set_has_deleted_file(true);
11904 });
11905
11906 // Emit UpdateTab event
11907 cx.run_until_parked();
11908 item.update(cx, |_, cx| {
11909 cx.emit(ItemEvent::UpdateTab);
11910 });
11911
11912 // Allow any potential close operation to complete
11913 cx.run_until_parked();
11914
11915 // Verify the item remains open (with strikethrough)
11916 pane.read_with(cx, |pane, _| {
11917 assert_eq!(
11918 pane.items().count(),
11919 1,
11920 "Item should remain open when close_on_disk_deletion is disabled"
11921 );
11922 });
11923
11924 // Verify the item shows as deleted
11925 item.read_with(cx, |item, _| {
11926 assert!(
11927 item.has_deleted_file,
11928 "Item should be marked as having deleted file"
11929 );
11930 });
11931 }
11932
11933 /// Tests that dirty files are not automatically closed when deleted from disk,
11934 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
11935 /// unsaved changes without being prompted.
11936 #[gpui::test]
11937 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
11938 init_test(cx);
11939
11940 // Enable the close_on_file_delete setting
11941 cx.update_global(|store: &mut SettingsStore, cx| {
11942 store.update_user_settings(cx, |settings| {
11943 settings.workspace.close_on_file_delete = Some(true);
11944 });
11945 });
11946
11947 let fs = FakeFs::new(cx.background_executor.clone());
11948 let project = Project::test(fs, [], cx).await;
11949 let (workspace, cx) =
11950 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11951 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11952
11953 // Create a dirty test item
11954 let item = cx.new(|cx| {
11955 TestItem::new(cx)
11956 .with_dirty(true)
11957 .with_label("test.txt")
11958 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11959 });
11960
11961 // Add item to workspace
11962 workspace.update_in(cx, |workspace, window, cx| {
11963 workspace.add_item(
11964 pane.clone(),
11965 Box::new(item.clone()),
11966 None,
11967 false,
11968 false,
11969 window,
11970 cx,
11971 );
11972 });
11973
11974 // Simulate file deletion
11975 item.update(cx, |item, _| {
11976 item.set_has_deleted_file(true);
11977 });
11978
11979 // Emit UpdateTab event to trigger the close behavior
11980 cx.run_until_parked();
11981 item.update(cx, |_, cx| {
11982 cx.emit(ItemEvent::UpdateTab);
11983 });
11984
11985 // Allow any potential close operation to complete
11986 cx.run_until_parked();
11987
11988 // Verify the item remains open (dirty files are not auto-closed)
11989 pane.read_with(cx, |pane, _| {
11990 assert_eq!(
11991 pane.items().count(),
11992 1,
11993 "Dirty items should not be automatically closed even when file is deleted"
11994 );
11995 });
11996
11997 // Verify the item is marked as deleted and still dirty
11998 item.read_with(cx, |item, _| {
11999 assert!(
12000 item.has_deleted_file,
12001 "Item should be marked as having deleted file"
12002 );
12003 assert!(item.is_dirty, "Item should still be dirty");
12004 });
12005 }
12006
12007 /// Tests that navigation history is cleaned up when files are auto-closed
12008 /// due to deletion from disk.
12009 #[gpui::test]
12010 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12011 init_test(cx);
12012
12013 // Enable the close_on_file_delete setting
12014 cx.update_global(|store: &mut SettingsStore, cx| {
12015 store.update_user_settings(cx, |settings| {
12016 settings.workspace.close_on_file_delete = Some(true);
12017 });
12018 });
12019
12020 let fs = FakeFs::new(cx.background_executor.clone());
12021 let project = Project::test(fs, [], cx).await;
12022 let (workspace, cx) =
12023 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12024 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12025
12026 // Create test items
12027 let item1 = cx.new(|cx| {
12028 TestItem::new(cx)
12029 .with_label("test1.txt")
12030 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12031 });
12032 let item1_id = item1.item_id();
12033
12034 let item2 = cx.new(|cx| {
12035 TestItem::new(cx)
12036 .with_label("test2.txt")
12037 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12038 });
12039
12040 // Add items to workspace
12041 workspace.update_in(cx, |workspace, window, cx| {
12042 workspace.add_item(
12043 pane.clone(),
12044 Box::new(item1.clone()),
12045 None,
12046 false,
12047 false,
12048 window,
12049 cx,
12050 );
12051 workspace.add_item(
12052 pane.clone(),
12053 Box::new(item2.clone()),
12054 None,
12055 false,
12056 false,
12057 window,
12058 cx,
12059 );
12060 });
12061
12062 // Activate item1 to ensure it gets navigation entries
12063 pane.update_in(cx, |pane, window, cx| {
12064 pane.activate_item(0, true, true, window, cx);
12065 });
12066
12067 // Switch to item2 and back to create navigation history
12068 pane.update_in(cx, |pane, window, cx| {
12069 pane.activate_item(1, true, true, window, cx);
12070 });
12071 cx.run_until_parked();
12072
12073 pane.update_in(cx, |pane, window, cx| {
12074 pane.activate_item(0, true, true, window, cx);
12075 });
12076 cx.run_until_parked();
12077
12078 // Simulate file deletion for item1
12079 item1.update(cx, |item, _| {
12080 item.set_has_deleted_file(true);
12081 });
12082
12083 // Emit UpdateTab event to trigger the close behavior
12084 item1.update(cx, |_, cx| {
12085 cx.emit(ItemEvent::UpdateTab);
12086 });
12087 cx.run_until_parked();
12088
12089 // Verify item1 was closed
12090 pane.read_with(cx, |pane, _| {
12091 assert_eq!(
12092 pane.items().count(),
12093 1,
12094 "Should have 1 item remaining after auto-close"
12095 );
12096 });
12097
12098 // Check navigation history after close
12099 let has_item = pane.read_with(cx, |pane, cx| {
12100 let mut has_item = false;
12101 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12102 if entry.item.id() == item1_id {
12103 has_item = true;
12104 }
12105 });
12106 has_item
12107 });
12108
12109 assert!(
12110 !has_item,
12111 "Navigation history should not contain closed item entries"
12112 );
12113 }
12114
12115 #[gpui::test]
12116 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12117 cx: &mut TestAppContext,
12118 ) {
12119 init_test(cx);
12120
12121 let fs = FakeFs::new(cx.background_executor.clone());
12122 let project = Project::test(fs, [], cx).await;
12123 let (workspace, cx) =
12124 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12125 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12126
12127 let dirty_regular_buffer = cx.new(|cx| {
12128 TestItem::new(cx)
12129 .with_dirty(true)
12130 .with_label("1.txt")
12131 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12132 });
12133 let dirty_regular_buffer_2 = cx.new(|cx| {
12134 TestItem::new(cx)
12135 .with_dirty(true)
12136 .with_label("2.txt")
12137 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12138 });
12139 let clear_regular_buffer = cx.new(|cx| {
12140 TestItem::new(cx)
12141 .with_label("3.txt")
12142 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12143 });
12144
12145 let dirty_multi_buffer = cx.new(|cx| {
12146 TestItem::new(cx)
12147 .with_dirty(true)
12148 .with_buffer_kind(ItemBufferKind::Multibuffer)
12149 .with_label("Fake Project Search")
12150 .with_project_items(&[
12151 dirty_regular_buffer.read(cx).project_items[0].clone(),
12152 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12153 clear_regular_buffer.read(cx).project_items[0].clone(),
12154 ])
12155 });
12156 workspace.update_in(cx, |workspace, window, cx| {
12157 workspace.add_item(
12158 pane.clone(),
12159 Box::new(dirty_regular_buffer.clone()),
12160 None,
12161 false,
12162 false,
12163 window,
12164 cx,
12165 );
12166 workspace.add_item(
12167 pane.clone(),
12168 Box::new(dirty_regular_buffer_2.clone()),
12169 None,
12170 false,
12171 false,
12172 window,
12173 cx,
12174 );
12175 workspace.add_item(
12176 pane.clone(),
12177 Box::new(dirty_multi_buffer.clone()),
12178 None,
12179 false,
12180 false,
12181 window,
12182 cx,
12183 );
12184 });
12185
12186 pane.update_in(cx, |pane, window, cx| {
12187 pane.activate_item(2, true, true, window, cx);
12188 assert_eq!(
12189 pane.active_item().unwrap().item_id(),
12190 dirty_multi_buffer.item_id(),
12191 "Should select the multi buffer in the pane"
12192 );
12193 });
12194 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12195 pane.close_active_item(
12196 &CloseActiveItem {
12197 save_intent: None,
12198 close_pinned: false,
12199 },
12200 window,
12201 cx,
12202 )
12203 });
12204 cx.background_executor.run_until_parked();
12205 assert!(
12206 !cx.has_pending_prompt(),
12207 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12208 );
12209 close_multi_buffer_task
12210 .await
12211 .expect("Closing multi buffer failed");
12212 pane.update(cx, |pane, cx| {
12213 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12214 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12215 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12216 assert_eq!(
12217 pane.items()
12218 .map(|item| item.item_id())
12219 .sorted()
12220 .collect::<Vec<_>>(),
12221 vec![
12222 dirty_regular_buffer.item_id(),
12223 dirty_regular_buffer_2.item_id(),
12224 ],
12225 "Should have no multi buffer left in the pane"
12226 );
12227 assert!(dirty_regular_buffer.read(cx).is_dirty);
12228 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12229 });
12230 }
12231
12232 #[gpui::test]
12233 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12234 init_test(cx);
12235 let fs = FakeFs::new(cx.executor());
12236 let project = Project::test(fs, [], cx).await;
12237 let (workspace, cx) =
12238 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12239
12240 // Add a new panel to the right dock, opening the dock and setting the
12241 // focus to the new panel.
12242 let panel = workspace.update_in(cx, |workspace, window, cx| {
12243 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12244 workspace.add_panel(panel.clone(), window, cx);
12245
12246 workspace
12247 .right_dock()
12248 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12249
12250 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12251
12252 panel
12253 });
12254
12255 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12256 // panel to the next valid position which, in this case, is the left
12257 // dock.
12258 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12259 workspace.update(cx, |workspace, cx| {
12260 assert!(workspace.left_dock().read(cx).is_open());
12261 assert_eq!(panel.read(cx).position, DockPosition::Left);
12262 });
12263
12264 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12265 // panel to the next valid position which, in this case, is the bottom
12266 // dock.
12267 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12268 workspace.update(cx, |workspace, cx| {
12269 assert!(workspace.bottom_dock().read(cx).is_open());
12270 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12271 });
12272
12273 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12274 // around moving the panel to its initial position, the right dock.
12275 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12276 workspace.update(cx, |workspace, cx| {
12277 assert!(workspace.right_dock().read(cx).is_open());
12278 assert_eq!(panel.read(cx).position, DockPosition::Right);
12279 });
12280
12281 // Remove focus from the panel, ensuring that, if the panel is not
12282 // focused, the `MoveFocusedPanelToNextPosition` action does not update
12283 // the panel's position, so the panel is still in the right dock.
12284 workspace.update_in(cx, |workspace, window, cx| {
12285 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12286 });
12287
12288 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12289 workspace.update(cx, |workspace, cx| {
12290 assert!(workspace.right_dock().read(cx).is_open());
12291 assert_eq!(panel.read(cx).position, DockPosition::Right);
12292 });
12293 }
12294
12295 #[gpui::test]
12296 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12297 init_test(cx);
12298
12299 let fs = FakeFs::new(cx.executor());
12300 let project = Project::test(fs, [], cx).await;
12301 let (workspace, cx) =
12302 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12303
12304 let item_1 = cx.new(|cx| {
12305 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12306 });
12307 workspace.update_in(cx, |workspace, window, cx| {
12308 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12309 workspace.move_item_to_pane_in_direction(
12310 &MoveItemToPaneInDirection {
12311 direction: SplitDirection::Right,
12312 focus: true,
12313 clone: false,
12314 },
12315 window,
12316 cx,
12317 );
12318 workspace.move_item_to_pane_at_index(
12319 &MoveItemToPane {
12320 destination: 3,
12321 focus: true,
12322 clone: false,
12323 },
12324 window,
12325 cx,
12326 );
12327
12328 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12329 assert_eq!(
12330 pane_items_paths(&workspace.active_pane, cx),
12331 vec!["first.txt".to_string()],
12332 "Single item was not moved anywhere"
12333 );
12334 });
12335
12336 let item_2 = cx.new(|cx| {
12337 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12338 });
12339 workspace.update_in(cx, |workspace, window, cx| {
12340 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12341 assert_eq!(
12342 pane_items_paths(&workspace.panes[0], cx),
12343 vec!["first.txt".to_string(), "second.txt".to_string()],
12344 );
12345 workspace.move_item_to_pane_in_direction(
12346 &MoveItemToPaneInDirection {
12347 direction: SplitDirection::Right,
12348 focus: true,
12349 clone: false,
12350 },
12351 window,
12352 cx,
12353 );
12354
12355 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12356 assert_eq!(
12357 pane_items_paths(&workspace.panes[0], cx),
12358 vec!["first.txt".to_string()],
12359 "After moving, one item should be left in the original pane"
12360 );
12361 assert_eq!(
12362 pane_items_paths(&workspace.panes[1], cx),
12363 vec!["second.txt".to_string()],
12364 "New item should have been moved to the new pane"
12365 );
12366 });
12367
12368 let item_3 = cx.new(|cx| {
12369 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12370 });
12371 workspace.update_in(cx, |workspace, window, cx| {
12372 let original_pane = workspace.panes[0].clone();
12373 workspace.set_active_pane(&original_pane, window, cx);
12374 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12375 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12376 assert_eq!(
12377 pane_items_paths(&workspace.active_pane, cx),
12378 vec!["first.txt".to_string(), "third.txt".to_string()],
12379 "New pane should be ready to move one item out"
12380 );
12381
12382 workspace.move_item_to_pane_at_index(
12383 &MoveItemToPane {
12384 destination: 3,
12385 focus: true,
12386 clone: false,
12387 },
12388 window,
12389 cx,
12390 );
12391 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12392 assert_eq!(
12393 pane_items_paths(&workspace.active_pane, cx),
12394 vec!["first.txt".to_string()],
12395 "After moving, one item should be left in the original pane"
12396 );
12397 assert_eq!(
12398 pane_items_paths(&workspace.panes[1], cx),
12399 vec!["second.txt".to_string()],
12400 "Previously created pane should be unchanged"
12401 );
12402 assert_eq!(
12403 pane_items_paths(&workspace.panes[2], cx),
12404 vec!["third.txt".to_string()],
12405 "New item should have been moved to the new pane"
12406 );
12407 });
12408 }
12409
12410 #[gpui::test]
12411 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12412 init_test(cx);
12413
12414 let fs = FakeFs::new(cx.executor());
12415 let project = Project::test(fs, [], cx).await;
12416 let (workspace, cx) =
12417 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12418
12419 let item_1 = cx.new(|cx| {
12420 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12421 });
12422 workspace.update_in(cx, |workspace, window, cx| {
12423 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12424 workspace.move_item_to_pane_in_direction(
12425 &MoveItemToPaneInDirection {
12426 direction: SplitDirection::Right,
12427 focus: true,
12428 clone: true,
12429 },
12430 window,
12431 cx,
12432 );
12433 });
12434 cx.run_until_parked();
12435 workspace.update_in(cx, |workspace, window, cx| {
12436 workspace.move_item_to_pane_at_index(
12437 &MoveItemToPane {
12438 destination: 3,
12439 focus: true,
12440 clone: true,
12441 },
12442 window,
12443 cx,
12444 );
12445 });
12446 cx.run_until_parked();
12447
12448 workspace.update(cx, |workspace, cx| {
12449 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
12450 for pane in workspace.panes() {
12451 assert_eq!(
12452 pane_items_paths(pane, cx),
12453 vec!["first.txt".to_string()],
12454 "Single item exists in all panes"
12455 );
12456 }
12457 });
12458
12459 // verify that the active pane has been updated after waiting for the
12460 // pane focus event to fire and resolve
12461 workspace.read_with(cx, |workspace, _app| {
12462 assert_eq!(
12463 workspace.active_pane(),
12464 &workspace.panes[2],
12465 "The third pane should be the active one: {:?}",
12466 workspace.panes
12467 );
12468 })
12469 }
12470
12471 #[gpui::test]
12472 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
12473 init_test(cx);
12474
12475 let fs = FakeFs::new(cx.executor());
12476 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
12477
12478 let project = Project::test(fs, ["root".as_ref()], cx).await;
12479 let (workspace, cx) =
12480 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12481
12482 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12483 // Add item to pane A with project path
12484 let item_a = cx.new(|cx| {
12485 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12486 });
12487 workspace.update_in(cx, |workspace, window, cx| {
12488 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
12489 });
12490
12491 // Split to create pane B
12492 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
12493 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
12494 });
12495
12496 // Add item with SAME project path to pane B, and pin it
12497 let item_b = cx.new(|cx| {
12498 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12499 });
12500 pane_b.update_in(cx, |pane, window, cx| {
12501 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
12502 pane.set_pinned_count(1);
12503 });
12504
12505 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
12506 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
12507
12508 // close_pinned: false should only close the unpinned copy
12509 workspace.update_in(cx, |workspace, window, cx| {
12510 workspace.close_item_in_all_panes(
12511 &CloseItemInAllPanes {
12512 save_intent: Some(SaveIntent::Close),
12513 close_pinned: false,
12514 },
12515 window,
12516 cx,
12517 )
12518 });
12519 cx.executor().run_until_parked();
12520
12521 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
12522 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12523 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
12524 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
12525
12526 // Split again, seeing as closing the previous item also closed its
12527 // pane, so only pane remains, which does not allow us to properly test
12528 // that both items close when `close_pinned: true`.
12529 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
12530 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
12531 });
12532
12533 // Add an item with the same project path to pane C so that
12534 // close_item_in_all_panes can determine what to close across all panes
12535 // (it reads the active item from the active pane, and split_pane
12536 // creates an empty pane).
12537 let item_c = cx.new(|cx| {
12538 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12539 });
12540 pane_c.update_in(cx, |pane, window, cx| {
12541 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
12542 });
12543
12544 // close_pinned: true should close the pinned copy too
12545 workspace.update_in(cx, |workspace, window, cx| {
12546 let panes_count = workspace.panes().len();
12547 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
12548
12549 workspace.close_item_in_all_panes(
12550 &CloseItemInAllPanes {
12551 save_intent: Some(SaveIntent::Close),
12552 close_pinned: true,
12553 },
12554 window,
12555 cx,
12556 )
12557 });
12558 cx.executor().run_until_parked();
12559
12560 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12561 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
12562 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
12563 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
12564 }
12565
12566 mod register_project_item_tests {
12567
12568 use super::*;
12569
12570 // View
12571 struct TestPngItemView {
12572 focus_handle: FocusHandle,
12573 }
12574 // Model
12575 struct TestPngItem {}
12576
12577 impl project::ProjectItem for TestPngItem {
12578 fn try_open(
12579 _project: &Entity<Project>,
12580 path: &ProjectPath,
12581 cx: &mut App,
12582 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12583 if path.path.extension().unwrap() == "png" {
12584 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
12585 } else {
12586 None
12587 }
12588 }
12589
12590 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12591 None
12592 }
12593
12594 fn project_path(&self, _: &App) -> Option<ProjectPath> {
12595 None
12596 }
12597
12598 fn is_dirty(&self) -> bool {
12599 false
12600 }
12601 }
12602
12603 impl Item for TestPngItemView {
12604 type Event = ();
12605 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12606 "".into()
12607 }
12608 }
12609 impl EventEmitter<()> for TestPngItemView {}
12610 impl Focusable for TestPngItemView {
12611 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12612 self.focus_handle.clone()
12613 }
12614 }
12615
12616 impl Render for TestPngItemView {
12617 fn render(
12618 &mut self,
12619 _window: &mut Window,
12620 _cx: &mut Context<Self>,
12621 ) -> impl IntoElement {
12622 Empty
12623 }
12624 }
12625
12626 impl ProjectItem for TestPngItemView {
12627 type Item = TestPngItem;
12628
12629 fn for_project_item(
12630 _project: Entity<Project>,
12631 _pane: Option<&Pane>,
12632 _item: Entity<Self::Item>,
12633 _: &mut Window,
12634 cx: &mut Context<Self>,
12635 ) -> Self
12636 where
12637 Self: Sized,
12638 {
12639 Self {
12640 focus_handle: cx.focus_handle(),
12641 }
12642 }
12643 }
12644
12645 // View
12646 struct TestIpynbItemView {
12647 focus_handle: FocusHandle,
12648 }
12649 // Model
12650 struct TestIpynbItem {}
12651
12652 impl project::ProjectItem for TestIpynbItem {
12653 fn try_open(
12654 _project: &Entity<Project>,
12655 path: &ProjectPath,
12656 cx: &mut App,
12657 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12658 if path.path.extension().unwrap() == "ipynb" {
12659 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
12660 } else {
12661 None
12662 }
12663 }
12664
12665 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12666 None
12667 }
12668
12669 fn project_path(&self, _: &App) -> Option<ProjectPath> {
12670 None
12671 }
12672
12673 fn is_dirty(&self) -> bool {
12674 false
12675 }
12676 }
12677
12678 impl Item for TestIpynbItemView {
12679 type Event = ();
12680 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12681 "".into()
12682 }
12683 }
12684 impl EventEmitter<()> for TestIpynbItemView {}
12685 impl Focusable for TestIpynbItemView {
12686 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12687 self.focus_handle.clone()
12688 }
12689 }
12690
12691 impl Render for TestIpynbItemView {
12692 fn render(
12693 &mut self,
12694 _window: &mut Window,
12695 _cx: &mut Context<Self>,
12696 ) -> impl IntoElement {
12697 Empty
12698 }
12699 }
12700
12701 impl ProjectItem for TestIpynbItemView {
12702 type Item = TestIpynbItem;
12703
12704 fn for_project_item(
12705 _project: Entity<Project>,
12706 _pane: Option<&Pane>,
12707 _item: Entity<Self::Item>,
12708 _: &mut Window,
12709 cx: &mut Context<Self>,
12710 ) -> Self
12711 where
12712 Self: Sized,
12713 {
12714 Self {
12715 focus_handle: cx.focus_handle(),
12716 }
12717 }
12718 }
12719
12720 struct TestAlternatePngItemView {
12721 focus_handle: FocusHandle,
12722 }
12723
12724 impl Item for TestAlternatePngItemView {
12725 type Event = ();
12726 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12727 "".into()
12728 }
12729 }
12730
12731 impl EventEmitter<()> for TestAlternatePngItemView {}
12732 impl Focusable for TestAlternatePngItemView {
12733 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12734 self.focus_handle.clone()
12735 }
12736 }
12737
12738 impl Render for TestAlternatePngItemView {
12739 fn render(
12740 &mut self,
12741 _window: &mut Window,
12742 _cx: &mut Context<Self>,
12743 ) -> impl IntoElement {
12744 Empty
12745 }
12746 }
12747
12748 impl ProjectItem for TestAlternatePngItemView {
12749 type Item = TestPngItem;
12750
12751 fn for_project_item(
12752 _project: Entity<Project>,
12753 _pane: Option<&Pane>,
12754 _item: Entity<Self::Item>,
12755 _: &mut Window,
12756 cx: &mut Context<Self>,
12757 ) -> Self
12758 where
12759 Self: Sized,
12760 {
12761 Self {
12762 focus_handle: cx.focus_handle(),
12763 }
12764 }
12765 }
12766
12767 #[gpui::test]
12768 async fn test_register_project_item(cx: &mut TestAppContext) {
12769 init_test(cx);
12770
12771 cx.update(|cx| {
12772 register_project_item::<TestPngItemView>(cx);
12773 register_project_item::<TestIpynbItemView>(cx);
12774 });
12775
12776 let fs = FakeFs::new(cx.executor());
12777 fs.insert_tree(
12778 "/root1",
12779 json!({
12780 "one.png": "BINARYDATAHERE",
12781 "two.ipynb": "{ totally a notebook }",
12782 "three.txt": "editing text, sure why not?"
12783 }),
12784 )
12785 .await;
12786
12787 let project = Project::test(fs, ["root1".as_ref()], cx).await;
12788 let (workspace, cx) =
12789 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12790
12791 let worktree_id = project.update(cx, |project, cx| {
12792 project.worktrees(cx).next().unwrap().read(cx).id()
12793 });
12794
12795 let handle = workspace
12796 .update_in(cx, |workspace, window, cx| {
12797 let project_path = (worktree_id, rel_path("one.png"));
12798 workspace.open_path(project_path, None, true, window, cx)
12799 })
12800 .await
12801 .unwrap();
12802
12803 // Now we can check if the handle we got back errored or not
12804 assert_eq!(
12805 handle.to_any_view().entity_type(),
12806 TypeId::of::<TestPngItemView>()
12807 );
12808
12809 let handle = workspace
12810 .update_in(cx, |workspace, window, cx| {
12811 let project_path = (worktree_id, rel_path("two.ipynb"));
12812 workspace.open_path(project_path, None, true, window, cx)
12813 })
12814 .await
12815 .unwrap();
12816
12817 assert_eq!(
12818 handle.to_any_view().entity_type(),
12819 TypeId::of::<TestIpynbItemView>()
12820 );
12821
12822 let handle = workspace
12823 .update_in(cx, |workspace, window, cx| {
12824 let project_path = (worktree_id, rel_path("three.txt"));
12825 workspace.open_path(project_path, None, true, window, cx)
12826 })
12827 .await;
12828 assert!(handle.is_err());
12829 }
12830
12831 #[gpui::test]
12832 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
12833 init_test(cx);
12834
12835 cx.update(|cx| {
12836 register_project_item::<TestPngItemView>(cx);
12837 register_project_item::<TestAlternatePngItemView>(cx);
12838 });
12839
12840 let fs = FakeFs::new(cx.executor());
12841 fs.insert_tree(
12842 "/root1",
12843 json!({
12844 "one.png": "BINARYDATAHERE",
12845 "two.ipynb": "{ totally a notebook }",
12846 "three.txt": "editing text, sure why not?"
12847 }),
12848 )
12849 .await;
12850 let project = Project::test(fs, ["root1".as_ref()], cx).await;
12851 let (workspace, cx) =
12852 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12853 let worktree_id = project.update(cx, |project, cx| {
12854 project.worktrees(cx).next().unwrap().read(cx).id()
12855 });
12856
12857 let handle = workspace
12858 .update_in(cx, |workspace, window, cx| {
12859 let project_path = (worktree_id, rel_path("one.png"));
12860 workspace.open_path(project_path, None, true, window, cx)
12861 })
12862 .await
12863 .unwrap();
12864
12865 // This _must_ be the second item registered
12866 assert_eq!(
12867 handle.to_any_view().entity_type(),
12868 TypeId::of::<TestAlternatePngItemView>()
12869 );
12870
12871 let handle = workspace
12872 .update_in(cx, |workspace, window, cx| {
12873 let project_path = (worktree_id, rel_path("three.txt"));
12874 workspace.open_path(project_path, None, true, window, cx)
12875 })
12876 .await;
12877 assert!(handle.is_err());
12878 }
12879 }
12880
12881 #[gpui::test]
12882 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
12883 init_test(cx);
12884
12885 let fs = FakeFs::new(cx.executor());
12886 let project = Project::test(fs, [], cx).await;
12887 let (workspace, _cx) =
12888 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12889
12890 // Test with status bar shown (default)
12891 workspace.read_with(cx, |workspace, cx| {
12892 let visible = workspace.status_bar_visible(cx);
12893 assert!(visible, "Status bar should be visible by default");
12894 });
12895
12896 // Test with status bar hidden
12897 cx.update_global(|store: &mut SettingsStore, cx| {
12898 store.update_user_settings(cx, |settings| {
12899 settings.status_bar.get_or_insert_default().show = Some(false);
12900 });
12901 });
12902
12903 workspace.read_with(cx, |workspace, cx| {
12904 let visible = workspace.status_bar_visible(cx);
12905 assert!(!visible, "Status bar should be hidden when show is false");
12906 });
12907
12908 // Test with status bar shown explicitly
12909 cx.update_global(|store: &mut SettingsStore, cx| {
12910 store.update_user_settings(cx, |settings| {
12911 settings.status_bar.get_or_insert_default().show = Some(true);
12912 });
12913 });
12914
12915 workspace.read_with(cx, |workspace, cx| {
12916 let visible = workspace.status_bar_visible(cx);
12917 assert!(visible, "Status bar should be visible when show is true");
12918 });
12919 }
12920
12921 #[gpui::test]
12922 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
12923 init_test(cx);
12924
12925 let fs = FakeFs::new(cx.executor());
12926 let project = Project::test(fs, [], cx).await;
12927 let (workspace, cx) =
12928 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12929 let panel = workspace.update_in(cx, |workspace, window, cx| {
12930 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12931 workspace.add_panel(panel.clone(), window, cx);
12932
12933 workspace
12934 .right_dock()
12935 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12936
12937 panel
12938 });
12939
12940 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12941 let item_a = cx.new(TestItem::new);
12942 let item_b = cx.new(TestItem::new);
12943 let item_a_id = item_a.entity_id();
12944 let item_b_id = item_b.entity_id();
12945
12946 pane.update_in(cx, |pane, window, cx| {
12947 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
12948 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
12949 });
12950
12951 pane.read_with(cx, |pane, _| {
12952 assert_eq!(pane.items_len(), 2);
12953 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
12954 });
12955
12956 workspace.update_in(cx, |workspace, window, cx| {
12957 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12958 });
12959
12960 workspace.update_in(cx, |_, window, cx| {
12961 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12962 });
12963
12964 // Assert that the `pane::CloseActiveItem` action is handled at the
12965 // workspace level when one of the dock panels is focused and, in that
12966 // case, the center pane's active item is closed but the focus is not
12967 // moved.
12968 cx.dispatch_action(pane::CloseActiveItem::default());
12969 cx.run_until_parked();
12970
12971 pane.read_with(cx, |pane, _| {
12972 assert_eq!(pane.items_len(), 1);
12973 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
12974 });
12975
12976 workspace.update_in(cx, |workspace, window, cx| {
12977 assert!(workspace.right_dock().read(cx).is_open());
12978 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12979 });
12980 }
12981
12982 #[gpui::test]
12983 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
12984 init_test(cx);
12985 let fs = FakeFs::new(cx.executor());
12986
12987 let project_a = Project::test(fs.clone(), [], cx).await;
12988 let project_b = Project::test(fs, [], cx).await;
12989
12990 let multi_workspace_handle =
12991 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
12992
12993 let workspace_a = multi_workspace_handle
12994 .read_with(cx, |mw, _| mw.workspace().clone())
12995 .unwrap();
12996
12997 let _workspace_b = multi_workspace_handle
12998 .update(cx, |mw, window, cx| {
12999 mw.test_add_workspace(project_b, window, cx)
13000 })
13001 .unwrap();
13002
13003 // Switch to workspace A
13004 multi_workspace_handle
13005 .update(cx, |mw, window, cx| {
13006 mw.activate_index(0, window, cx);
13007 })
13008 .unwrap();
13009
13010 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13011
13012 // Add a panel to workspace A's right dock and open the dock
13013 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13014 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13015 workspace.add_panel(panel.clone(), window, cx);
13016 workspace
13017 .right_dock()
13018 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13019 panel
13020 });
13021
13022 // Focus the panel through the workspace (matching existing test pattern)
13023 workspace_a.update_in(cx, |workspace, window, cx| {
13024 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13025 });
13026
13027 // Zoom the panel
13028 panel.update_in(cx, |panel, window, cx| {
13029 panel.set_zoomed(true, window, cx);
13030 });
13031
13032 // Verify the panel is zoomed and the dock is open
13033 workspace_a.update_in(cx, |workspace, window, cx| {
13034 assert!(
13035 workspace.right_dock().read(cx).is_open(),
13036 "dock should be open before switch"
13037 );
13038 assert!(
13039 panel.is_zoomed(window, cx),
13040 "panel should be zoomed before switch"
13041 );
13042 assert!(
13043 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13044 "panel should be focused before switch"
13045 );
13046 });
13047
13048 // Switch to workspace B
13049 multi_workspace_handle
13050 .update(cx, |mw, window, cx| {
13051 mw.activate_index(1, window, cx);
13052 })
13053 .unwrap();
13054 cx.run_until_parked();
13055
13056 // Switch back to workspace A
13057 multi_workspace_handle
13058 .update(cx, |mw, window, cx| {
13059 mw.activate_index(0, window, cx);
13060 })
13061 .unwrap();
13062 cx.run_until_parked();
13063
13064 // Verify the panel is still zoomed and the dock is still open
13065 workspace_a.update_in(cx, |workspace, window, cx| {
13066 assert!(
13067 workspace.right_dock().read(cx).is_open(),
13068 "dock should still be open after switching back"
13069 );
13070 assert!(
13071 panel.is_zoomed(window, cx),
13072 "panel should still be zoomed after switching back"
13073 );
13074 });
13075 }
13076
13077 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13078 pane.read(cx)
13079 .items()
13080 .flat_map(|item| {
13081 item.project_paths(cx)
13082 .into_iter()
13083 .map(|path| path.path.display(PathStyle::local()).into_owned())
13084 })
13085 .collect()
13086 }
13087
13088 pub fn init_test(cx: &mut TestAppContext) {
13089 cx.update(|cx| {
13090 let settings_store = SettingsStore::test(cx);
13091 cx.set_global(settings_store);
13092 theme::init(theme::LoadThemes::JustBase, cx);
13093 });
13094 }
13095
13096 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13097 let item = TestProjectItem::new(id, path, cx);
13098 item.update(cx, |item, _| {
13099 item.is_dirty = true;
13100 });
13101 item
13102 }
13103
13104 #[gpui::test]
13105 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13106 cx: &mut gpui::TestAppContext,
13107 ) {
13108 init_test(cx);
13109 let fs = FakeFs::new(cx.executor());
13110
13111 let project = Project::test(fs, [], cx).await;
13112 let (workspace, cx) =
13113 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13114
13115 let panel = workspace.update_in(cx, |workspace, window, cx| {
13116 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13117 workspace.add_panel(panel.clone(), window, cx);
13118 workspace
13119 .right_dock()
13120 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13121 panel
13122 });
13123
13124 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13125 pane.update_in(cx, |pane, window, cx| {
13126 let item = cx.new(TestItem::new);
13127 pane.add_item(Box::new(item), true, true, None, window, cx);
13128 });
13129
13130 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13131 // mirrors the real-world flow and avoids side effects from directly
13132 // focusing the panel while the center pane is active.
13133 workspace.update_in(cx, |workspace, window, cx| {
13134 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13135 });
13136
13137 panel.update_in(cx, |panel, window, cx| {
13138 panel.set_zoomed(true, window, cx);
13139 });
13140
13141 workspace.update_in(cx, |workspace, window, cx| {
13142 assert!(workspace.right_dock().read(cx).is_open());
13143 assert!(panel.is_zoomed(window, cx));
13144 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13145 });
13146
13147 // Simulate a spurious pane::Event::Focus on the center pane while the
13148 // panel still has focus. This mirrors what happens during macOS window
13149 // activation: the center pane fires a focus event even though actual
13150 // focus remains on the dock panel.
13151 pane.update_in(cx, |_, _, cx| {
13152 cx.emit(pane::Event::Focus);
13153 });
13154
13155 // The dock must remain open because the panel had focus at the time the
13156 // event was processed. Before the fix, dock_to_preserve was None for
13157 // panels that don't implement pane(), causing the dock to close.
13158 workspace.update_in(cx, |workspace, window, cx| {
13159 assert!(
13160 workspace.right_dock().read(cx).is_open(),
13161 "Dock should stay open when its zoomed panel (without pane()) still has focus"
13162 );
13163 assert!(panel.is_zoomed(window, cx));
13164 });
13165 }
13166}