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 _schedule_serialize_ssh_paths: Option<Task<()>>,
1248 pane_history_timestamp: Arc<AtomicUsize>,
1249 bounds: Bounds<Pixels>,
1250 pub centered_layout: bool,
1251 bounds_save_task_queued: Option<Task<()>>,
1252 on_prompt_for_new_path: Option<PromptForNewPath>,
1253 on_prompt_for_open_path: Option<PromptForOpenPath>,
1254 terminal_provider: Option<Box<dyn TerminalProvider>>,
1255 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1256 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1257 _items_serializer: Task<Result<()>>,
1258 session_id: Option<String>,
1259 scheduled_tasks: Vec<Task<()>>,
1260 last_open_dock_positions: Vec<DockPosition>,
1261 removing: bool,
1262}
1263
1264impl EventEmitter<Event> for Workspace {}
1265
1266#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1267pub struct ViewId {
1268 pub creator: CollaboratorId,
1269 pub id: u64,
1270}
1271
1272pub struct FollowerState {
1273 center_pane: Entity<Pane>,
1274 dock_pane: Option<Entity<Pane>>,
1275 active_view_id: Option<ViewId>,
1276 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1277}
1278
1279struct FollowerView {
1280 view: Box<dyn FollowableItemHandle>,
1281 location: Option<proto::PanelId>,
1282}
1283
1284impl Workspace {
1285 pub fn new(
1286 workspace_id: Option<WorkspaceId>,
1287 project: Entity<Project>,
1288 app_state: Arc<AppState>,
1289 window: &mut Window,
1290 cx: &mut Context<Self>,
1291 ) -> Self {
1292 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1293 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1294 if let TrustedWorktreesEvent::Trusted(..) = e {
1295 // Do not persist auto trusted worktrees
1296 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1297 worktrees_store.update(cx, |worktrees_store, cx| {
1298 worktrees_store.schedule_serialization(
1299 cx,
1300 |new_trusted_worktrees, cx| {
1301 let timeout =
1302 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1303 cx.background_spawn(async move {
1304 timeout.await;
1305 persistence::DB
1306 .save_trusted_worktrees(new_trusted_worktrees)
1307 .await
1308 .log_err();
1309 })
1310 },
1311 )
1312 });
1313 }
1314 }
1315 })
1316 .detach();
1317
1318 cx.observe_global::<SettingsStore>(|_, cx| {
1319 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1320 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1321 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1322 trusted_worktrees.auto_trust_all(cx);
1323 })
1324 }
1325 }
1326 })
1327 .detach();
1328 }
1329
1330 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1331 match event {
1332 project::Event::RemoteIdChanged(_) => {
1333 this.update_window_title(window, cx);
1334 }
1335
1336 project::Event::CollaboratorLeft(peer_id) => {
1337 this.collaborator_left(*peer_id, window, cx);
1338 }
1339
1340 &project::Event::WorktreeRemoved(id) | &project::Event::WorktreeAdded(id) => {
1341 this.update_window_title(window, cx);
1342 if this
1343 .project()
1344 .read(cx)
1345 .worktree_for_id(id, cx)
1346 .is_some_and(|wt| wt.read(cx).is_visible())
1347 {
1348 this.serialize_workspace(window, cx);
1349 this.update_history(cx);
1350 }
1351 }
1352 project::Event::WorktreeUpdatedEntries(..) => {
1353 this.update_window_title(window, cx);
1354 this.serialize_workspace(window, cx);
1355 }
1356
1357 project::Event::DisconnectedFromHost => {
1358 this.update_window_edited(window, cx);
1359 let leaders_to_unfollow =
1360 this.follower_states.keys().copied().collect::<Vec<_>>();
1361 for leader_id in leaders_to_unfollow {
1362 this.unfollow(leader_id, window, cx);
1363 }
1364 }
1365
1366 project::Event::DisconnectedFromRemote {
1367 server_not_running: _,
1368 } => {
1369 this.update_window_edited(window, cx);
1370 }
1371
1372 project::Event::Closed => {
1373 window.remove_window();
1374 }
1375
1376 project::Event::DeletedEntry(_, entry_id) => {
1377 for pane in this.panes.iter() {
1378 pane.update(cx, |pane, cx| {
1379 pane.handle_deleted_project_item(*entry_id, window, cx)
1380 });
1381 }
1382 }
1383
1384 project::Event::Toast {
1385 notification_id,
1386 message,
1387 link,
1388 } => this.show_notification(
1389 NotificationId::named(notification_id.clone()),
1390 cx,
1391 |cx| {
1392 let mut notification = MessageNotification::new(message.clone(), cx);
1393 if let Some(link) = link {
1394 notification = notification
1395 .more_info_message(link.label)
1396 .more_info_url(link.url);
1397 }
1398
1399 cx.new(|_| notification)
1400 },
1401 ),
1402
1403 project::Event::HideToast { notification_id } => {
1404 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1405 }
1406
1407 project::Event::LanguageServerPrompt(request) => {
1408 struct LanguageServerPrompt;
1409
1410 this.show_notification(
1411 NotificationId::composite::<LanguageServerPrompt>(request.id),
1412 cx,
1413 |cx| {
1414 cx.new(|cx| {
1415 notifications::LanguageServerPrompt::new(request.clone(), cx)
1416 })
1417 },
1418 );
1419 }
1420
1421 project::Event::AgentLocationChanged => {
1422 this.handle_agent_location_changed(window, cx)
1423 }
1424
1425 _ => {}
1426 }
1427 cx.notify()
1428 })
1429 .detach();
1430
1431 cx.subscribe_in(
1432 &project.read(cx).breakpoint_store(),
1433 window,
1434 |workspace, _, event, window, cx| match event {
1435 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1436 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1437 workspace.serialize_workspace(window, cx);
1438 }
1439 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1440 },
1441 )
1442 .detach();
1443 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1444 cx.subscribe_in(
1445 &toolchain_store,
1446 window,
1447 |workspace, _, event, window, cx| match event {
1448 ToolchainStoreEvent::CustomToolchainsModified => {
1449 workspace.serialize_workspace(window, cx);
1450 }
1451 _ => {}
1452 },
1453 )
1454 .detach();
1455 }
1456
1457 cx.on_focus_lost(window, |this, window, cx| {
1458 let focus_handle = this.focus_handle(cx);
1459 window.focus(&focus_handle, cx);
1460 })
1461 .detach();
1462
1463 let weak_handle = cx.entity().downgrade();
1464 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1465
1466 let center_pane = cx.new(|cx| {
1467 let mut center_pane = Pane::new(
1468 weak_handle.clone(),
1469 project.clone(),
1470 pane_history_timestamp.clone(),
1471 None,
1472 NewFile.boxed_clone(),
1473 true,
1474 window,
1475 cx,
1476 );
1477 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1478 center_pane.set_should_display_welcome_page(true);
1479 center_pane
1480 });
1481 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1482 .detach();
1483
1484 window.focus(¢er_pane.focus_handle(cx), cx);
1485
1486 cx.emit(Event::PaneAdded(center_pane.clone()));
1487
1488 let any_window_handle = window.window_handle();
1489 app_state.workspace_store.update(cx, |store, _| {
1490 store
1491 .workspaces
1492 .insert((any_window_handle, weak_handle.clone()));
1493 });
1494
1495 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1496 let mut connection_status = app_state.client.status();
1497 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1498 current_user.next().await;
1499 connection_status.next().await;
1500 let mut stream =
1501 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1502
1503 while stream.recv().await.is_some() {
1504 this.update(cx, |_, cx| cx.notify())?;
1505 }
1506 anyhow::Ok(())
1507 });
1508
1509 // All leader updates are enqueued and then processed in a single task, so
1510 // that each asynchronous operation can be run in order.
1511 let (leader_updates_tx, mut leader_updates_rx) =
1512 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1513 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1514 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1515 Self::process_leader_update(&this, leader_id, update, cx)
1516 .await
1517 .log_err();
1518 }
1519
1520 Ok(())
1521 });
1522
1523 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1524 let modal_layer = cx.new(|_| ModalLayer::new());
1525 let toast_layer = cx.new(|_| ToastLayer::new());
1526 cx.subscribe(
1527 &modal_layer,
1528 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1529 cx.emit(Event::ModalOpened);
1530 },
1531 )
1532 .detach();
1533
1534 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1535 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1536 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1537 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1538 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1539 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1540 let status_bar = cx.new(|cx| {
1541 let mut status_bar = StatusBar::new(¢er_pane.clone(), window, cx);
1542 status_bar.add_left_item(left_dock_buttons, window, cx);
1543 status_bar.add_right_item(right_dock_buttons, window, cx);
1544 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1545 status_bar
1546 });
1547
1548 let session_id = app_state.session.read(cx).id().to_owned();
1549
1550 let mut active_call = None;
1551 if let Some(call) = ActiveCall::try_global(cx) {
1552 let subscriptions = vec![cx.subscribe_in(&call, window, Self::on_active_call_event)];
1553 active_call = Some((call, subscriptions));
1554 }
1555
1556 let (serializable_items_tx, serializable_items_rx) =
1557 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1558 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1559 Self::serialize_items(&this, serializable_items_rx, cx).await
1560 });
1561
1562 let subscriptions = vec![
1563 cx.observe_window_activation(window, Self::on_window_activation_changed),
1564 cx.observe_window_bounds(window, move |this, window, cx| {
1565 if this.bounds_save_task_queued.is_some() {
1566 return;
1567 }
1568 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1569 cx.background_executor()
1570 .timer(Duration::from_millis(100))
1571 .await;
1572 this.update_in(cx, |this, window, cx| {
1573 if let Some(display) = window.display(cx)
1574 && let Ok(display_uuid) = display.uuid()
1575 {
1576 let window_bounds = window.inner_window_bounds();
1577 let has_paths = !this.root_paths(cx).is_empty();
1578 if !has_paths {
1579 cx.background_executor()
1580 .spawn(persistence::write_default_window_bounds(
1581 window_bounds,
1582 display_uuid,
1583 ))
1584 .detach_and_log_err(cx);
1585 }
1586 if let Some(database_id) = workspace_id {
1587 cx.background_executor()
1588 .spawn(DB.set_window_open_status(
1589 database_id,
1590 SerializedWindowBounds(window_bounds),
1591 display_uuid,
1592 ))
1593 .detach_and_log_err(cx);
1594 } else {
1595 cx.background_executor()
1596 .spawn(persistence::write_default_window_bounds(
1597 window_bounds,
1598 display_uuid,
1599 ))
1600 .detach_and_log_err(cx);
1601 }
1602 }
1603 this.bounds_save_task_queued.take();
1604 })
1605 .ok();
1606 }));
1607 cx.notify();
1608 }),
1609 cx.observe_window_appearance(window, |_, window, cx| {
1610 let window_appearance = window.appearance();
1611
1612 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1613
1614 GlobalTheme::reload_theme(cx);
1615 GlobalTheme::reload_icon_theme(cx);
1616 }),
1617 cx.on_release({
1618 let weak_handle = weak_handle.clone();
1619 move |this, cx| {
1620 this.app_state.workspace_store.update(cx, move |store, _| {
1621 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1622 })
1623 }
1624 }),
1625 ];
1626
1627 cx.defer_in(window, move |this, window, cx| {
1628 this.update_window_title(window, cx);
1629 this.show_initial_notifications(cx);
1630 });
1631
1632 let mut center = PaneGroup::new(center_pane.clone());
1633 center.set_is_center(true);
1634 center.mark_positions(cx);
1635
1636 Workspace {
1637 weak_self: weak_handle.clone(),
1638 zoomed: None,
1639 zoomed_position: None,
1640 previous_dock_drag_coordinates: None,
1641 center,
1642 panes: vec![center_pane.clone()],
1643 panes_by_item: Default::default(),
1644 active_pane: center_pane.clone(),
1645 last_active_center_pane: Some(center_pane.downgrade()),
1646 last_active_view_id: None,
1647 status_bar,
1648 modal_layer,
1649 toast_layer,
1650 titlebar_item: None,
1651 active_worktree_override: None,
1652 notifications: Notifications::default(),
1653 suppressed_notifications: HashSet::default(),
1654 left_dock,
1655 bottom_dock,
1656 right_dock,
1657 project: project.clone(),
1658 follower_states: Default::default(),
1659 last_leaders_by_pane: Default::default(),
1660 dispatching_keystrokes: Default::default(),
1661 window_edited: false,
1662 last_window_title: None,
1663 dirty_items: Default::default(),
1664 active_call,
1665 database_id: workspace_id,
1666 app_state,
1667 _observe_current_user,
1668 _apply_leader_updates,
1669 _schedule_serialize_workspace: None,
1670 _schedule_serialize_ssh_paths: None,
1671 leader_updates_tx,
1672 _subscriptions: subscriptions,
1673 pane_history_timestamp,
1674 workspace_actions: Default::default(),
1675 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1676 bounds: Default::default(),
1677 centered_layout: false,
1678 bounds_save_task_queued: None,
1679 on_prompt_for_new_path: None,
1680 on_prompt_for_open_path: None,
1681 terminal_provider: None,
1682 debugger_provider: None,
1683 serializable_items_tx,
1684 _items_serializer,
1685 session_id: Some(session_id),
1686
1687 scheduled_tasks: Vec::new(),
1688 last_open_dock_positions: Vec::new(),
1689 removing: false,
1690 }
1691 }
1692
1693 pub fn new_local(
1694 abs_paths: Vec<PathBuf>,
1695 app_state: Arc<AppState>,
1696 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1697 env: Option<HashMap<String, String>>,
1698 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1699 cx: &mut App,
1700 ) -> Task<
1701 anyhow::Result<(
1702 WindowHandle<MultiWorkspace>,
1703 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
1704 )>,
1705 > {
1706 let project_handle = Project::local(
1707 app_state.client.clone(),
1708 app_state.node_runtime.clone(),
1709 app_state.user_store.clone(),
1710 app_state.languages.clone(),
1711 app_state.fs.clone(),
1712 env,
1713 Default::default(),
1714 cx,
1715 );
1716
1717 cx.spawn(async move |cx| {
1718 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1719 for path in abs_paths.into_iter() {
1720 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1721 paths_to_open.push(canonical)
1722 } else {
1723 paths_to_open.push(path)
1724 }
1725 }
1726
1727 let serialized_workspace =
1728 persistence::DB.workspace_for_roots(paths_to_open.as_slice());
1729
1730 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1731 paths_to_open = paths.ordered_paths().cloned().collect();
1732 if !paths.is_lexicographically_ordered() {
1733 project_handle.update(cx, |project, cx| {
1734 project.set_worktrees_reordered(true, cx);
1735 });
1736 }
1737 }
1738
1739 // Get project paths for all of the abs_paths
1740 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1741 Vec::with_capacity(paths_to_open.len());
1742
1743 for path in paths_to_open.into_iter() {
1744 if let Some((_, project_entry)) = cx
1745 .update(|cx| {
1746 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1747 })
1748 .await
1749 .log_err()
1750 {
1751 project_paths.push((path, Some(project_entry)));
1752 } else {
1753 project_paths.push((path, None));
1754 }
1755 }
1756
1757 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1758 serialized_workspace.id
1759 } else {
1760 DB.next_id().await.unwrap_or_else(|_| Default::default())
1761 };
1762
1763 let toolchains = DB.toolchains(workspace_id).await?;
1764
1765 for (toolchain, worktree_path, path) in toolchains {
1766 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1767 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1768 this.find_worktree(&worktree_path, cx)
1769 .and_then(|(worktree, rel_path)| {
1770 if rel_path.is_empty() {
1771 Some(worktree.read(cx).id())
1772 } else {
1773 None
1774 }
1775 })
1776 }) else {
1777 // We did not find a worktree with a given path, but that's whatever.
1778 continue;
1779 };
1780 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1781 continue;
1782 }
1783
1784 project_handle
1785 .update(cx, |this, cx| {
1786 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1787 })
1788 .await;
1789 }
1790 if let Some(workspace) = serialized_workspace.as_ref() {
1791 project_handle.update(cx, |this, cx| {
1792 for (scope, toolchains) in &workspace.user_toolchains {
1793 for toolchain in toolchains {
1794 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1795 }
1796 }
1797 });
1798 }
1799
1800 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1801 if let Some(window) = requesting_window {
1802 let centered_layout = serialized_workspace
1803 .as_ref()
1804 .map(|w| w.centered_layout)
1805 .unwrap_or(false);
1806
1807 let workspace = window.update(cx, |multi_workspace, window, cx| {
1808 let workspace = cx.new(|cx| {
1809 let mut workspace = Workspace::new(
1810 Some(workspace_id),
1811 project_handle.clone(),
1812 app_state.clone(),
1813 window,
1814 cx,
1815 );
1816
1817 workspace.centered_layout = centered_layout;
1818
1819 // Call init callback to add items before window renders
1820 if let Some(init) = init {
1821 init(&mut workspace, window, cx);
1822 }
1823
1824 workspace
1825 });
1826 multi_workspace.activate(workspace.clone(), cx);
1827 workspace
1828 })?;
1829 (window, workspace)
1830 } else {
1831 let window_bounds_override = window_bounds_env_override();
1832
1833 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1834 (Some(WindowBounds::Windowed(bounds)), None)
1835 } else if let Some(workspace) = serialized_workspace.as_ref()
1836 && let Some(display) = workspace.display
1837 && let Some(bounds) = workspace.window_bounds.as_ref()
1838 {
1839 // Reopening an existing workspace - restore its saved bounds
1840 (Some(bounds.0), Some(display))
1841 } else if let Some((display, bounds)) =
1842 persistence::read_default_window_bounds()
1843 {
1844 // New or empty workspace - use the last known window bounds
1845 (Some(bounds), Some(display))
1846 } else {
1847 // New window - let GPUI's default_bounds() handle cascading
1848 (None, None)
1849 };
1850
1851 // Use the serialized workspace to construct the new window
1852 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1853 options.window_bounds = window_bounds;
1854 let centered_layout = serialized_workspace
1855 .as_ref()
1856 .map(|w| w.centered_layout)
1857 .unwrap_or(false);
1858 let window = cx.open_window(options, {
1859 let app_state = app_state.clone();
1860 let project_handle = project_handle.clone();
1861 move |window, cx| {
1862 let workspace = cx.new(|cx| {
1863 let mut workspace = Workspace::new(
1864 Some(workspace_id),
1865 project_handle,
1866 app_state,
1867 window,
1868 cx,
1869 );
1870 workspace.centered_layout = centered_layout;
1871
1872 // Call init callback to add items before window renders
1873 if let Some(init) = init {
1874 init(&mut workspace, window, cx);
1875 }
1876
1877 workspace
1878 });
1879 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1880 }
1881 })?;
1882 let workspace =
1883 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
1884 multi_workspace.workspace().clone()
1885 })?;
1886 (window, workspace)
1887 };
1888
1889 notify_if_database_failed(window, cx);
1890 // Check if this is an empty workspace (no paths to open)
1891 // An empty workspace is one where project_paths is empty
1892 let is_empty_workspace = project_paths.is_empty();
1893 // Check if serialized workspace has paths before it's moved
1894 let serialized_workspace_has_paths = serialized_workspace
1895 .as_ref()
1896 .map(|ws| !ws.paths.is_empty())
1897 .unwrap_or(false);
1898
1899 let opened_items = window
1900 .update(cx, |_, window, cx| {
1901 workspace.update(cx, |_workspace: &mut Workspace, cx| {
1902 open_items(serialized_workspace, project_paths, window, cx)
1903 })
1904 })?
1905 .await
1906 .unwrap_or_default();
1907
1908 // Restore default dock state for empty workspaces
1909 // Only restore if:
1910 // 1. This is an empty workspace (no paths), AND
1911 // 2. The serialized workspace either doesn't exist or has no paths
1912 if is_empty_workspace && !serialized_workspace_has_paths {
1913 if let Some(default_docks) = persistence::read_default_dock_state() {
1914 window
1915 .update(cx, |_, window, cx| {
1916 workspace.update(cx, |workspace, cx| {
1917 for (dock, serialized_dock) in [
1918 (&workspace.right_dock, &default_docks.right),
1919 (&workspace.left_dock, &default_docks.left),
1920 (&workspace.bottom_dock, &default_docks.bottom),
1921 ] {
1922 dock.update(cx, |dock, cx| {
1923 dock.serialized_dock = Some(serialized_dock.clone());
1924 dock.restore_state(window, cx);
1925 });
1926 }
1927 cx.notify();
1928 });
1929 })
1930 .log_err();
1931 }
1932 }
1933
1934 window
1935 .update(cx, |_, _window, cx| {
1936 workspace.update(cx, |this: &mut Workspace, cx| {
1937 this.update_history(cx);
1938 });
1939 })
1940 .log_err();
1941 Ok((window, opened_items))
1942 })
1943 }
1944
1945 pub fn weak_handle(&self) -> WeakEntity<Self> {
1946 self.weak_self.clone()
1947 }
1948
1949 pub fn left_dock(&self) -> &Entity<Dock> {
1950 &self.left_dock
1951 }
1952
1953 pub fn bottom_dock(&self) -> &Entity<Dock> {
1954 &self.bottom_dock
1955 }
1956
1957 pub fn set_bottom_dock_layout(
1958 &mut self,
1959 layout: BottomDockLayout,
1960 window: &mut Window,
1961 cx: &mut Context<Self>,
1962 ) {
1963 let fs = self.project().read(cx).fs();
1964 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
1965 content.workspace.bottom_dock_layout = Some(layout);
1966 });
1967
1968 cx.notify();
1969 self.serialize_workspace(window, cx);
1970 }
1971
1972 pub fn right_dock(&self) -> &Entity<Dock> {
1973 &self.right_dock
1974 }
1975
1976 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
1977 [&self.left_dock, &self.bottom_dock, &self.right_dock]
1978 }
1979
1980 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
1981 match position {
1982 DockPosition::Left => &self.left_dock,
1983 DockPosition::Bottom => &self.bottom_dock,
1984 DockPosition::Right => &self.right_dock,
1985 }
1986 }
1987
1988 pub fn is_edited(&self) -> bool {
1989 self.window_edited
1990 }
1991
1992 pub fn add_panel<T: Panel>(
1993 &mut self,
1994 panel: Entity<T>,
1995 window: &mut Window,
1996 cx: &mut Context<Self>,
1997 ) {
1998 let focus_handle = panel.panel_focus_handle(cx);
1999 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2000 .detach();
2001
2002 let dock_position = panel.position(window, cx);
2003 let dock = self.dock_at_position(dock_position);
2004
2005 dock.update(cx, |dock, cx| {
2006 dock.add_panel(panel, self.weak_self.clone(), window, cx)
2007 });
2008 }
2009
2010 pub fn remove_panel<T: Panel>(
2011 &mut self,
2012 panel: &Entity<T>,
2013 window: &mut Window,
2014 cx: &mut Context<Self>,
2015 ) {
2016 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2017 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2018 }
2019 }
2020
2021 pub fn status_bar(&self) -> &Entity<StatusBar> {
2022 &self.status_bar
2023 }
2024
2025 pub fn set_workspace_sidebar_open(&self, open: bool, cx: &mut App) {
2026 self.status_bar.update(cx, |status_bar, cx| {
2027 status_bar.set_workspace_sidebar_open(open, cx);
2028 });
2029 }
2030
2031 pub fn status_bar_visible(&self, cx: &App) -> bool {
2032 StatusBarSettings::get_global(cx).show
2033 }
2034
2035 pub fn app_state(&self) -> &Arc<AppState> {
2036 &self.app_state
2037 }
2038
2039 pub fn user_store(&self) -> &Entity<UserStore> {
2040 &self.app_state.user_store
2041 }
2042
2043 pub fn project(&self) -> &Entity<Project> {
2044 &self.project
2045 }
2046
2047 pub fn path_style(&self, cx: &App) -> PathStyle {
2048 self.project.read(cx).path_style(cx)
2049 }
2050
2051 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2052 let mut history: HashMap<EntityId, usize> = HashMap::default();
2053
2054 for pane_handle in &self.panes {
2055 let pane = pane_handle.read(cx);
2056
2057 for entry in pane.activation_history() {
2058 history.insert(
2059 entry.entity_id,
2060 history
2061 .get(&entry.entity_id)
2062 .cloned()
2063 .unwrap_or(0)
2064 .max(entry.timestamp),
2065 );
2066 }
2067 }
2068
2069 history
2070 }
2071
2072 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2073 let mut recent_item: Option<Entity<T>> = None;
2074 let mut recent_timestamp = 0;
2075 for pane_handle in &self.panes {
2076 let pane = pane_handle.read(cx);
2077 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2078 pane.items().map(|item| (item.item_id(), item)).collect();
2079 for entry in pane.activation_history() {
2080 if entry.timestamp > recent_timestamp
2081 && let Some(&item) = item_map.get(&entry.entity_id)
2082 && let Some(typed_item) = item.act_as::<T>(cx)
2083 {
2084 recent_timestamp = entry.timestamp;
2085 recent_item = Some(typed_item);
2086 }
2087 }
2088 }
2089 recent_item
2090 }
2091
2092 pub fn recent_navigation_history_iter(
2093 &self,
2094 cx: &App,
2095 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2096 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2097 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2098
2099 for pane in &self.panes {
2100 let pane = pane.read(cx);
2101
2102 pane.nav_history()
2103 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2104 if let Some(fs_path) = &fs_path {
2105 abs_paths_opened
2106 .entry(fs_path.clone())
2107 .or_default()
2108 .insert(project_path.clone());
2109 }
2110 let timestamp = entry.timestamp;
2111 match history.entry(project_path) {
2112 hash_map::Entry::Occupied(mut entry) => {
2113 let (_, old_timestamp) = entry.get();
2114 if ×tamp > old_timestamp {
2115 entry.insert((fs_path, timestamp));
2116 }
2117 }
2118 hash_map::Entry::Vacant(entry) => {
2119 entry.insert((fs_path, timestamp));
2120 }
2121 }
2122 });
2123
2124 if let Some(item) = pane.active_item()
2125 && let Some(project_path) = item.project_path(cx)
2126 {
2127 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2128
2129 if let Some(fs_path) = &fs_path {
2130 abs_paths_opened
2131 .entry(fs_path.clone())
2132 .or_default()
2133 .insert(project_path.clone());
2134 }
2135
2136 history.insert(project_path, (fs_path, std::usize::MAX));
2137 }
2138 }
2139
2140 history
2141 .into_iter()
2142 .sorted_by_key(|(_, (_, order))| *order)
2143 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2144 .rev()
2145 .filter(move |(history_path, abs_path)| {
2146 let latest_project_path_opened = abs_path
2147 .as_ref()
2148 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2149 .and_then(|project_paths| {
2150 project_paths
2151 .iter()
2152 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2153 });
2154
2155 latest_project_path_opened.is_none_or(|path| path == history_path)
2156 })
2157 }
2158
2159 pub fn recent_navigation_history(
2160 &self,
2161 limit: Option<usize>,
2162 cx: &App,
2163 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2164 self.recent_navigation_history_iter(cx)
2165 .take(limit.unwrap_or(usize::MAX))
2166 .collect()
2167 }
2168
2169 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2170 for pane in &self.panes {
2171 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2172 }
2173 }
2174
2175 fn navigate_history(
2176 &mut self,
2177 pane: WeakEntity<Pane>,
2178 mode: NavigationMode,
2179 window: &mut Window,
2180 cx: &mut Context<Workspace>,
2181 ) -> Task<Result<()>> {
2182 self.navigate_history_impl(
2183 pane,
2184 mode,
2185 window,
2186 &mut |history, cx| history.pop(mode, cx),
2187 cx,
2188 )
2189 }
2190
2191 fn navigate_tag_history(
2192 &mut self,
2193 pane: WeakEntity<Pane>,
2194 mode: TagNavigationMode,
2195 window: &mut Window,
2196 cx: &mut Context<Workspace>,
2197 ) -> Task<Result<()>> {
2198 self.navigate_history_impl(
2199 pane,
2200 NavigationMode::Normal,
2201 window,
2202 &mut |history, _cx| history.pop_tag(mode),
2203 cx,
2204 )
2205 }
2206
2207 fn navigate_history_impl(
2208 &mut self,
2209 pane: WeakEntity<Pane>,
2210 mode: NavigationMode,
2211 window: &mut Window,
2212 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2213 cx: &mut Context<Workspace>,
2214 ) -> Task<Result<()>> {
2215 let to_load = if let Some(pane) = pane.upgrade() {
2216 pane.update(cx, |pane, cx| {
2217 window.focus(&pane.focus_handle(cx), cx);
2218 loop {
2219 // Retrieve the weak item handle from the history.
2220 let entry = cb(pane.nav_history_mut(), cx)?;
2221
2222 // If the item is still present in this pane, then activate it.
2223 if let Some(index) = entry
2224 .item
2225 .upgrade()
2226 .and_then(|v| pane.index_for_item(v.as_ref()))
2227 {
2228 let prev_active_item_index = pane.active_item_index();
2229 pane.nav_history_mut().set_mode(mode);
2230 pane.activate_item(index, true, true, window, cx);
2231 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2232
2233 let mut navigated = prev_active_item_index != pane.active_item_index();
2234 if let Some(data) = entry.data {
2235 navigated |= pane.active_item()?.navigate(data, window, cx);
2236 }
2237
2238 if navigated {
2239 break None;
2240 }
2241 } else {
2242 // If the item is no longer present in this pane, then retrieve its
2243 // path info in order to reopen it.
2244 break pane
2245 .nav_history()
2246 .path_for_item(entry.item.id())
2247 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2248 }
2249 }
2250 })
2251 } else {
2252 None
2253 };
2254
2255 if let Some((project_path, abs_path, entry)) = to_load {
2256 // If the item was no longer present, then load it again from its previous path, first try the local path
2257 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2258
2259 cx.spawn_in(window, async move |workspace, cx| {
2260 let open_by_project_path = open_by_project_path.await;
2261 let mut navigated = false;
2262 match open_by_project_path
2263 .with_context(|| format!("Navigating to {project_path:?}"))
2264 {
2265 Ok((project_entry_id, build_item)) => {
2266 let prev_active_item_id = pane.update(cx, |pane, _| {
2267 pane.nav_history_mut().set_mode(mode);
2268 pane.active_item().map(|p| p.item_id())
2269 })?;
2270
2271 pane.update_in(cx, |pane, window, cx| {
2272 let item = pane.open_item(
2273 project_entry_id,
2274 project_path,
2275 true,
2276 entry.is_preview,
2277 true,
2278 None,
2279 window, cx,
2280 build_item,
2281 );
2282 navigated |= Some(item.item_id()) != prev_active_item_id;
2283 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2284 if let Some(data) = entry.data {
2285 navigated |= item.navigate(data, window, cx);
2286 }
2287 })?;
2288 }
2289 Err(open_by_project_path_e) => {
2290 // Fall back to opening by abs path, in case an external file was opened and closed,
2291 // and its worktree is now dropped
2292 if let Some(abs_path) = abs_path {
2293 let prev_active_item_id = pane.update(cx, |pane, _| {
2294 pane.nav_history_mut().set_mode(mode);
2295 pane.active_item().map(|p| p.item_id())
2296 })?;
2297 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2298 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2299 })?;
2300 match open_by_abs_path
2301 .await
2302 .with_context(|| format!("Navigating to {abs_path:?}"))
2303 {
2304 Ok(item) => {
2305 pane.update_in(cx, |pane, window, cx| {
2306 navigated |= Some(item.item_id()) != prev_active_item_id;
2307 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2308 if let Some(data) = entry.data {
2309 navigated |= item.navigate(data, window, cx);
2310 }
2311 })?;
2312 }
2313 Err(open_by_abs_path_e) => {
2314 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2315 }
2316 }
2317 }
2318 }
2319 }
2320
2321 if !navigated {
2322 workspace
2323 .update_in(cx, |workspace, window, cx| {
2324 Self::navigate_history(workspace, pane, mode, window, cx)
2325 })?
2326 .await?;
2327 }
2328
2329 Ok(())
2330 })
2331 } else {
2332 Task::ready(Ok(()))
2333 }
2334 }
2335
2336 pub fn go_back(
2337 &mut self,
2338 pane: WeakEntity<Pane>,
2339 window: &mut Window,
2340 cx: &mut Context<Workspace>,
2341 ) -> Task<Result<()>> {
2342 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2343 }
2344
2345 pub fn go_forward(
2346 &mut self,
2347 pane: WeakEntity<Pane>,
2348 window: &mut Window,
2349 cx: &mut Context<Workspace>,
2350 ) -> Task<Result<()>> {
2351 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2352 }
2353
2354 pub fn reopen_closed_item(
2355 &mut self,
2356 window: &mut Window,
2357 cx: &mut Context<Workspace>,
2358 ) -> Task<Result<()>> {
2359 self.navigate_history(
2360 self.active_pane().downgrade(),
2361 NavigationMode::ReopeningClosedItem,
2362 window,
2363 cx,
2364 )
2365 }
2366
2367 pub fn client(&self) -> &Arc<Client> {
2368 &self.app_state.client
2369 }
2370
2371 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2372 self.titlebar_item = Some(item);
2373 cx.notify();
2374 }
2375
2376 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2377 self.on_prompt_for_new_path = Some(prompt)
2378 }
2379
2380 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2381 self.on_prompt_for_open_path = Some(prompt)
2382 }
2383
2384 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2385 self.terminal_provider = Some(Box::new(provider));
2386 }
2387
2388 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2389 self.debugger_provider = Some(Arc::new(provider));
2390 }
2391
2392 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2393 self.debugger_provider.clone()
2394 }
2395
2396 pub fn prompt_for_open_path(
2397 &mut self,
2398 path_prompt_options: PathPromptOptions,
2399 lister: DirectoryLister,
2400 window: &mut Window,
2401 cx: &mut Context<Self>,
2402 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2403 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2404 let prompt = self.on_prompt_for_open_path.take().unwrap();
2405 let rx = prompt(self, lister, window, cx);
2406 self.on_prompt_for_open_path = Some(prompt);
2407 rx
2408 } else {
2409 let (tx, rx) = oneshot::channel();
2410 let abs_path = cx.prompt_for_paths(path_prompt_options);
2411
2412 cx.spawn_in(window, async move |workspace, cx| {
2413 let Ok(result) = abs_path.await else {
2414 return Ok(());
2415 };
2416
2417 match result {
2418 Ok(result) => {
2419 tx.send(result).ok();
2420 }
2421 Err(err) => {
2422 let rx = workspace.update_in(cx, |workspace, window, cx| {
2423 workspace.show_portal_error(err.to_string(), cx);
2424 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2425 let rx = prompt(workspace, lister, window, cx);
2426 workspace.on_prompt_for_open_path = Some(prompt);
2427 rx
2428 })?;
2429 if let Ok(path) = rx.await {
2430 tx.send(path).ok();
2431 }
2432 }
2433 };
2434 anyhow::Ok(())
2435 })
2436 .detach();
2437
2438 rx
2439 }
2440 }
2441
2442 pub fn prompt_for_new_path(
2443 &mut self,
2444 lister: DirectoryLister,
2445 suggested_name: Option<String>,
2446 window: &mut Window,
2447 cx: &mut Context<Self>,
2448 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2449 if self.project.read(cx).is_via_collab()
2450 || self.project.read(cx).is_via_remote_server()
2451 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2452 {
2453 let prompt = self.on_prompt_for_new_path.take().unwrap();
2454 let rx = prompt(self, lister, suggested_name, window, cx);
2455 self.on_prompt_for_new_path = Some(prompt);
2456 return rx;
2457 }
2458
2459 let (tx, rx) = oneshot::channel();
2460 cx.spawn_in(window, async move |workspace, cx| {
2461 let abs_path = workspace.update(cx, |workspace, cx| {
2462 let relative_to = workspace
2463 .most_recent_active_path(cx)
2464 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2465 .or_else(|| {
2466 let project = workspace.project.read(cx);
2467 project.visible_worktrees(cx).find_map(|worktree| {
2468 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2469 })
2470 })
2471 .or_else(std::env::home_dir)
2472 .unwrap_or_else(|| PathBuf::from(""));
2473 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2474 })?;
2475 let abs_path = match abs_path.await? {
2476 Ok(path) => path,
2477 Err(err) => {
2478 let rx = workspace.update_in(cx, |workspace, window, cx| {
2479 workspace.show_portal_error(err.to_string(), cx);
2480
2481 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2482 let rx = prompt(workspace, lister, suggested_name, window, cx);
2483 workspace.on_prompt_for_new_path = Some(prompt);
2484 rx
2485 })?;
2486 if let Ok(path) = rx.await {
2487 tx.send(path).ok();
2488 }
2489 return anyhow::Ok(());
2490 }
2491 };
2492
2493 tx.send(abs_path.map(|path| vec![path])).ok();
2494 anyhow::Ok(())
2495 })
2496 .detach();
2497
2498 rx
2499 }
2500
2501 pub fn titlebar_item(&self) -> Option<AnyView> {
2502 self.titlebar_item.clone()
2503 }
2504
2505 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2506 /// When set, git-related operations should use this worktree instead of deriving
2507 /// the active worktree from the focused file.
2508 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2509 self.active_worktree_override
2510 }
2511
2512 pub fn set_active_worktree_override(
2513 &mut self,
2514 worktree_id: Option<WorktreeId>,
2515 cx: &mut Context<Self>,
2516 ) {
2517 self.active_worktree_override = worktree_id;
2518 cx.notify();
2519 }
2520
2521 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2522 self.active_worktree_override = None;
2523 cx.notify();
2524 }
2525
2526 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2527 ///
2528 /// If the given workspace has a local project, then it will be passed
2529 /// to the callback. Otherwise, a new empty window will be created.
2530 pub fn with_local_workspace<T, F>(
2531 &mut self,
2532 window: &mut Window,
2533 cx: &mut Context<Self>,
2534 callback: F,
2535 ) -> Task<Result<T>>
2536 where
2537 T: 'static,
2538 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2539 {
2540 if self.project.read(cx).is_local() {
2541 Task::ready(Ok(callback(self, window, cx)))
2542 } else {
2543 let env = self.project.read(cx).cli_environment(cx);
2544 let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, None, cx);
2545 cx.spawn_in(window, async move |_vh, cx| {
2546 let (multi_workspace_window, _) = task.await?;
2547 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2548 let workspace = multi_workspace.workspace().clone();
2549 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2550 })
2551 })
2552 }
2553 }
2554
2555 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2556 ///
2557 /// If the given workspace has a local project, then it will be passed
2558 /// to the callback. Otherwise, a new empty window will be created.
2559 pub fn with_local_or_wsl_workspace<T, F>(
2560 &mut self,
2561 window: &mut Window,
2562 cx: &mut Context<Self>,
2563 callback: F,
2564 ) -> Task<Result<T>>
2565 where
2566 T: 'static,
2567 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2568 {
2569 let project = self.project.read(cx);
2570 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
2571 Task::ready(Ok(callback(self, window, cx)))
2572 } else {
2573 let env = self.project.read(cx).cli_environment(cx);
2574 let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, None, cx);
2575 cx.spawn_in(window, async move |_vh, cx| {
2576 let (multi_workspace_window, _) = task.await?;
2577 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2578 let workspace = multi_workspace.workspace().clone();
2579 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2580 })
2581 })
2582 }
2583 }
2584
2585 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2586 self.project.read(cx).worktrees(cx)
2587 }
2588
2589 pub fn visible_worktrees<'a>(
2590 &self,
2591 cx: &'a App,
2592 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2593 self.project.read(cx).visible_worktrees(cx)
2594 }
2595
2596 #[cfg(any(test, feature = "test-support"))]
2597 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
2598 let futures = self
2599 .worktrees(cx)
2600 .filter_map(|worktree| worktree.read(cx).as_local())
2601 .map(|worktree| worktree.scan_complete())
2602 .collect::<Vec<_>>();
2603 async move {
2604 for future in futures {
2605 future.await;
2606 }
2607 }
2608 }
2609
2610 pub fn close_global(cx: &mut App) {
2611 cx.defer(|cx| {
2612 cx.windows().iter().find(|window| {
2613 window
2614 .update(cx, |_, window, _| {
2615 if window.is_window_active() {
2616 //This can only get called when the window's project connection has been lost
2617 //so we don't need to prompt the user for anything and instead just close the window
2618 window.remove_window();
2619 true
2620 } else {
2621 false
2622 }
2623 })
2624 .unwrap_or(false)
2625 });
2626 });
2627 }
2628
2629 pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
2630 let prepare = self.prepare_to_close(CloseIntent::CloseWindow, window, cx);
2631 cx.spawn_in(window, async move |_, cx| {
2632 if prepare.await? {
2633 cx.update(|window, _cx| window.remove_window())?;
2634 }
2635 anyhow::Ok(())
2636 })
2637 .detach_and_log_err(cx)
2638 }
2639
2640 pub fn move_focused_panel_to_next_position(
2641 &mut self,
2642 _: &MoveFocusedPanelToNextPosition,
2643 window: &mut Window,
2644 cx: &mut Context<Self>,
2645 ) {
2646 let docks = self.all_docks();
2647 let active_dock = docks
2648 .into_iter()
2649 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
2650
2651 if let Some(dock) = active_dock {
2652 dock.update(cx, |dock, cx| {
2653 let active_panel = dock
2654 .active_panel()
2655 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
2656
2657 if let Some(panel) = active_panel {
2658 panel.move_to_next_position(window, cx);
2659 }
2660 })
2661 }
2662 }
2663
2664 pub fn prepare_to_close(
2665 &mut self,
2666 close_intent: CloseIntent,
2667 window: &mut Window,
2668 cx: &mut Context<Self>,
2669 ) -> Task<Result<bool>> {
2670 let active_call = self.active_call().cloned();
2671
2672 cx.spawn_in(window, async move |this, cx| {
2673 this.update(cx, |this, _| {
2674 if close_intent == CloseIntent::CloseWindow {
2675 this.removing = true;
2676 }
2677 })?;
2678
2679 let workspace_count = cx.update(|_window, cx| {
2680 cx.windows()
2681 .iter()
2682 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
2683 .count()
2684 })?;
2685
2686 #[cfg(target_os = "macos")]
2687 let save_last_workspace = false;
2688
2689 // On Linux and Windows, closing the last window should restore the last workspace.
2690 #[cfg(not(target_os = "macos"))]
2691 let save_last_workspace = {
2692 let remaining_workspaces = cx.update(|_window, cx| {
2693 cx.windows()
2694 .iter()
2695 .filter_map(|window| window.downcast::<MultiWorkspace>())
2696 .filter_map(|multi_workspace| {
2697 multi_workspace
2698 .update(cx, |multi_workspace, _, cx| {
2699 multi_workspace.workspace().read(cx).removing
2700 })
2701 .ok()
2702 })
2703 .filter(|removing| !removing)
2704 .count()
2705 })?;
2706
2707 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
2708 };
2709
2710 if let Some(active_call) = active_call
2711 && workspace_count == 1
2712 && active_call.read_with(cx, |call, _| call.room().is_some())
2713 {
2714 if close_intent == CloseIntent::CloseWindow {
2715 let answer = cx.update(|window, cx| {
2716 window.prompt(
2717 PromptLevel::Warning,
2718 "Do you want to leave the current call?",
2719 None,
2720 &["Close window and hang up", "Cancel"],
2721 cx,
2722 )
2723 })?;
2724
2725 if answer.await.log_err() == Some(1) {
2726 return anyhow::Ok(false);
2727 } else {
2728 active_call
2729 .update(cx, |call, cx| call.hang_up(cx))
2730 .await
2731 .log_err();
2732 }
2733 }
2734 if close_intent == CloseIntent::ReplaceWindow {
2735 _ = active_call.update(cx, |this, cx| {
2736 let multi_workspace = cx
2737 .windows()
2738 .iter()
2739 .filter_map(|window| window.downcast::<MultiWorkspace>())
2740 .next()
2741 .unwrap();
2742 let project = multi_workspace
2743 .read(cx)?
2744 .workspace()
2745 .read(cx)
2746 .project
2747 .clone();
2748 if project.read(cx).is_shared() {
2749 this.unshare_project(project, cx)?;
2750 }
2751 Ok::<_, anyhow::Error>(())
2752 })?;
2753 }
2754 }
2755
2756 let save_result = this
2757 .update_in(cx, |this, window, cx| {
2758 this.save_all_internal(SaveIntent::Close, window, cx)
2759 })?
2760 .await;
2761
2762 // If we're not quitting, but closing, we remove the workspace from
2763 // the current session.
2764 if close_intent != CloseIntent::Quit
2765 && !save_last_workspace
2766 && save_result.as_ref().is_ok_and(|&res| res)
2767 {
2768 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
2769 .await;
2770 }
2771
2772 save_result
2773 })
2774 }
2775
2776 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
2777 self.save_all_internal(
2778 action.save_intent.unwrap_or(SaveIntent::SaveAll),
2779 window,
2780 cx,
2781 )
2782 .detach_and_log_err(cx);
2783 }
2784
2785 fn send_keystrokes(
2786 &mut self,
2787 action: &SendKeystrokes,
2788 window: &mut Window,
2789 cx: &mut Context<Self>,
2790 ) {
2791 let keystrokes: Vec<Keystroke> = action
2792 .0
2793 .split(' ')
2794 .flat_map(|k| Keystroke::parse(k).log_err())
2795 .map(|k| {
2796 cx.keyboard_mapper()
2797 .map_key_equivalent(k, false)
2798 .inner()
2799 .clone()
2800 })
2801 .collect();
2802 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
2803 }
2804
2805 pub fn send_keystrokes_impl(
2806 &mut self,
2807 keystrokes: Vec<Keystroke>,
2808 window: &mut Window,
2809 cx: &mut Context<Self>,
2810 ) -> Shared<Task<()>> {
2811 let mut state = self.dispatching_keystrokes.borrow_mut();
2812 if !state.dispatched.insert(keystrokes.clone()) {
2813 cx.propagate();
2814 return state.task.clone().unwrap();
2815 }
2816
2817 state.queue.extend(keystrokes);
2818
2819 let keystrokes = self.dispatching_keystrokes.clone();
2820 if state.task.is_none() {
2821 state.task = Some(
2822 window
2823 .spawn(cx, async move |cx| {
2824 // limit to 100 keystrokes to avoid infinite recursion.
2825 for _ in 0..100 {
2826 let mut state = keystrokes.borrow_mut();
2827 let Some(keystroke) = state.queue.pop_front() else {
2828 state.dispatched.clear();
2829 state.task.take();
2830 return;
2831 };
2832 drop(state);
2833 cx.update(|window, cx| {
2834 let focused = window.focused(cx);
2835 window.dispatch_keystroke(keystroke.clone(), cx);
2836 if window.focused(cx) != focused {
2837 // dispatch_keystroke may cause the focus to change.
2838 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
2839 // And we need that to happen before the next keystroke to keep vim mode happy...
2840 // (Note that the tests always do this implicitly, so you must manually test with something like:
2841 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
2842 // )
2843 window.draw(cx).clear();
2844 }
2845 })
2846 .ok();
2847 }
2848
2849 *keystrokes.borrow_mut() = Default::default();
2850 log::error!("over 100 keystrokes passed to send_keystrokes");
2851 })
2852 .shared(),
2853 );
2854 }
2855 state.task.clone().unwrap()
2856 }
2857
2858 fn save_all_internal(
2859 &mut self,
2860 mut save_intent: SaveIntent,
2861 window: &mut Window,
2862 cx: &mut Context<Self>,
2863 ) -> Task<Result<bool>> {
2864 if self.project.read(cx).is_disconnected(cx) {
2865 return Task::ready(Ok(true));
2866 }
2867 let dirty_items = self
2868 .panes
2869 .iter()
2870 .flat_map(|pane| {
2871 pane.read(cx).items().filter_map(|item| {
2872 if item.is_dirty(cx) {
2873 item.tab_content_text(0, cx);
2874 Some((pane.downgrade(), item.boxed_clone()))
2875 } else {
2876 None
2877 }
2878 })
2879 })
2880 .collect::<Vec<_>>();
2881
2882 let project = self.project.clone();
2883 cx.spawn_in(window, async move |workspace, cx| {
2884 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
2885 let (serialize_tasks, remaining_dirty_items) =
2886 workspace.update_in(cx, |workspace, window, cx| {
2887 let mut remaining_dirty_items = Vec::new();
2888 let mut serialize_tasks = Vec::new();
2889 for (pane, item) in dirty_items {
2890 if let Some(task) = item
2891 .to_serializable_item_handle(cx)
2892 .and_then(|handle| handle.serialize(workspace, true, window, cx))
2893 {
2894 serialize_tasks.push(task);
2895 } else {
2896 remaining_dirty_items.push((pane, item));
2897 }
2898 }
2899 (serialize_tasks, remaining_dirty_items)
2900 })?;
2901
2902 futures::future::try_join_all(serialize_tasks).await?;
2903
2904 if remaining_dirty_items.len() > 1 {
2905 let answer = workspace.update_in(cx, |_, window, cx| {
2906 let detail = Pane::file_names_for_prompt(
2907 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
2908 cx,
2909 );
2910 window.prompt(
2911 PromptLevel::Warning,
2912 "Do you want to save all changes in the following files?",
2913 Some(&detail),
2914 &["Save all", "Discard all", "Cancel"],
2915 cx,
2916 )
2917 })?;
2918 match answer.await.log_err() {
2919 Some(0) => save_intent = SaveIntent::SaveAll,
2920 Some(1) => save_intent = SaveIntent::Skip,
2921 Some(2) => return Ok(false),
2922 _ => {}
2923 }
2924 }
2925
2926 remaining_dirty_items
2927 } else {
2928 dirty_items
2929 };
2930
2931 for (pane, item) in dirty_items {
2932 let (singleton, project_entry_ids) = cx.update(|_, cx| {
2933 (
2934 item.buffer_kind(cx) == ItemBufferKind::Singleton,
2935 item.project_entry_ids(cx),
2936 )
2937 })?;
2938 if (singleton || !project_entry_ids.is_empty())
2939 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
2940 {
2941 return Ok(false);
2942 }
2943 }
2944 Ok(true)
2945 })
2946 }
2947
2948 pub fn open_workspace_for_paths(
2949 &mut self,
2950 replace_current_window: bool,
2951 paths: Vec<PathBuf>,
2952 window: &mut Window,
2953 cx: &mut Context<Self>,
2954 ) -> Task<Result<()>> {
2955 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
2956 let is_remote = self.project.read(cx).is_via_collab();
2957 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
2958 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
2959
2960 let window_to_replace = if replace_current_window {
2961 window_handle
2962 } else if is_remote || has_worktree || has_dirty_items {
2963 None
2964 } else {
2965 window_handle
2966 };
2967 let app_state = self.app_state.clone();
2968
2969 cx.spawn(async move |_, cx| {
2970 cx.update(|cx| {
2971 open_paths(
2972 &paths,
2973 app_state,
2974 OpenOptions {
2975 replace_window: window_to_replace,
2976 ..Default::default()
2977 },
2978 cx,
2979 )
2980 })
2981 .await?;
2982 Ok(())
2983 })
2984 }
2985
2986 #[allow(clippy::type_complexity)]
2987 pub fn open_paths(
2988 &mut self,
2989 mut abs_paths: Vec<PathBuf>,
2990 options: OpenOptions,
2991 pane: Option<WeakEntity<Pane>>,
2992 window: &mut Window,
2993 cx: &mut Context<Self>,
2994 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
2995 let fs = self.app_state.fs.clone();
2996
2997 let caller_ordered_abs_paths = abs_paths.clone();
2998
2999 // Sort the paths to ensure we add worktrees for parents before their children.
3000 abs_paths.sort_unstable();
3001 cx.spawn_in(window, async move |this, cx| {
3002 let mut tasks = Vec::with_capacity(abs_paths.len());
3003
3004 for abs_path in &abs_paths {
3005 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3006 OpenVisible::All => Some(true),
3007 OpenVisible::None => Some(false),
3008 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3009 Some(Some(metadata)) => Some(!metadata.is_dir),
3010 Some(None) => Some(true),
3011 None => None,
3012 },
3013 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3014 Some(Some(metadata)) => Some(metadata.is_dir),
3015 Some(None) => Some(false),
3016 None => None,
3017 },
3018 };
3019 let project_path = match visible {
3020 Some(visible) => match this
3021 .update(cx, |this, cx| {
3022 Workspace::project_path_for_path(
3023 this.project.clone(),
3024 abs_path,
3025 visible,
3026 cx,
3027 )
3028 })
3029 .log_err()
3030 {
3031 Some(project_path) => project_path.await.log_err(),
3032 None => None,
3033 },
3034 None => None,
3035 };
3036
3037 let this = this.clone();
3038 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3039 let fs = fs.clone();
3040 let pane = pane.clone();
3041 let task = cx.spawn(async move |cx| {
3042 let (_worktree, project_path) = project_path?;
3043 if fs.is_dir(&abs_path).await {
3044 // Opening a directory should not race to update the active entry.
3045 // We'll select/reveal a deterministic final entry after all paths finish opening.
3046 None
3047 } else {
3048 Some(
3049 this.update_in(cx, |this, window, cx| {
3050 this.open_path(
3051 project_path,
3052 pane,
3053 options.focus.unwrap_or(true),
3054 window,
3055 cx,
3056 )
3057 })
3058 .ok()?
3059 .await,
3060 )
3061 }
3062 });
3063 tasks.push(task);
3064 }
3065
3066 let results = futures::future::join_all(tasks).await;
3067
3068 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3069 let mut winner: Option<(PathBuf, bool)> = None;
3070 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3071 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3072 if !metadata.is_dir {
3073 winner = Some((abs_path, false));
3074 break;
3075 }
3076 if winner.is_none() {
3077 winner = Some((abs_path, true));
3078 }
3079 } else if winner.is_none() {
3080 winner = Some((abs_path, false));
3081 }
3082 }
3083
3084 // Compute the winner entry id on the foreground thread and emit once, after all
3085 // paths finish opening. This avoids races between concurrently-opening paths
3086 // (directories in particular) and makes the resulting project panel selection
3087 // deterministic.
3088 if let Some((winner_abs_path, winner_is_dir)) = winner {
3089 'emit_winner: {
3090 let winner_abs_path: Arc<Path> =
3091 SanitizedPath::new(&winner_abs_path).as_path().into();
3092
3093 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3094 OpenVisible::All => true,
3095 OpenVisible::None => false,
3096 OpenVisible::OnlyFiles => !winner_is_dir,
3097 OpenVisible::OnlyDirectories => winner_is_dir,
3098 };
3099
3100 let Some(worktree_task) = this
3101 .update(cx, |workspace, cx| {
3102 workspace.project.update(cx, |project, cx| {
3103 project.find_or_create_worktree(
3104 winner_abs_path.as_ref(),
3105 visible,
3106 cx,
3107 )
3108 })
3109 })
3110 .ok()
3111 else {
3112 break 'emit_winner;
3113 };
3114
3115 let Ok((worktree, _)) = worktree_task.await else {
3116 break 'emit_winner;
3117 };
3118
3119 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3120 let worktree = worktree.read(cx);
3121 let worktree_abs_path = worktree.abs_path();
3122 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3123 worktree.root_entry()
3124 } else {
3125 winner_abs_path
3126 .strip_prefix(worktree_abs_path.as_ref())
3127 .ok()
3128 .and_then(|relative_path| {
3129 let relative_path =
3130 RelPath::new(relative_path, PathStyle::local())
3131 .log_err()?;
3132 worktree.entry_for_path(&relative_path)
3133 })
3134 }?;
3135 Some(entry.id)
3136 }) else {
3137 break 'emit_winner;
3138 };
3139
3140 this.update(cx, |workspace, cx| {
3141 workspace.project.update(cx, |_, cx| {
3142 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3143 });
3144 })
3145 .ok();
3146 }
3147 }
3148
3149 results
3150 })
3151 }
3152
3153 pub fn open_resolved_path(
3154 &mut self,
3155 path: ResolvedPath,
3156 window: &mut Window,
3157 cx: &mut Context<Self>,
3158 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3159 match path {
3160 ResolvedPath::ProjectPath { project_path, .. } => {
3161 self.open_path(project_path, None, true, window, cx)
3162 }
3163 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3164 PathBuf::from(path),
3165 OpenOptions {
3166 visible: Some(OpenVisible::None),
3167 ..Default::default()
3168 },
3169 window,
3170 cx,
3171 ),
3172 }
3173 }
3174
3175 pub fn absolute_path_of_worktree(
3176 &self,
3177 worktree_id: WorktreeId,
3178 cx: &mut Context<Self>,
3179 ) -> Option<PathBuf> {
3180 self.project
3181 .read(cx)
3182 .worktree_for_id(worktree_id, cx)
3183 // TODO: use `abs_path` or `root_dir`
3184 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3185 }
3186
3187 fn add_folder_to_project(
3188 &mut self,
3189 _: &AddFolderToProject,
3190 window: &mut Window,
3191 cx: &mut Context<Self>,
3192 ) {
3193 let project = self.project.read(cx);
3194 if project.is_via_collab() {
3195 self.show_error(
3196 &anyhow!("You cannot add folders to someone else's project"),
3197 cx,
3198 );
3199 return;
3200 }
3201 let paths = self.prompt_for_open_path(
3202 PathPromptOptions {
3203 files: false,
3204 directories: true,
3205 multiple: true,
3206 prompt: None,
3207 },
3208 DirectoryLister::Project(self.project.clone()),
3209 window,
3210 cx,
3211 );
3212 cx.spawn_in(window, async move |this, cx| {
3213 if let Some(paths) = paths.await.log_err().flatten() {
3214 let results = this
3215 .update_in(cx, |this, window, cx| {
3216 this.open_paths(
3217 paths,
3218 OpenOptions {
3219 visible: Some(OpenVisible::All),
3220 ..Default::default()
3221 },
3222 None,
3223 window,
3224 cx,
3225 )
3226 })?
3227 .await;
3228 for result in results.into_iter().flatten() {
3229 result.log_err();
3230 }
3231 }
3232 anyhow::Ok(())
3233 })
3234 .detach_and_log_err(cx);
3235 }
3236
3237 pub fn project_path_for_path(
3238 project: Entity<Project>,
3239 abs_path: &Path,
3240 visible: bool,
3241 cx: &mut App,
3242 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3243 let entry = project.update(cx, |project, cx| {
3244 project.find_or_create_worktree(abs_path, visible, cx)
3245 });
3246 cx.spawn(async move |cx| {
3247 let (worktree, path) = entry.await?;
3248 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3249 Ok((worktree, ProjectPath { worktree_id, path }))
3250 })
3251 }
3252
3253 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3254 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3255 }
3256
3257 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3258 self.items_of_type(cx).max_by_key(|item| item.item_id())
3259 }
3260
3261 pub fn items_of_type<'a, T: Item>(
3262 &'a self,
3263 cx: &'a App,
3264 ) -> impl 'a + Iterator<Item = Entity<T>> {
3265 self.panes
3266 .iter()
3267 .flat_map(|pane| pane.read(cx).items_of_type())
3268 }
3269
3270 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3271 self.active_pane().read(cx).active_item()
3272 }
3273
3274 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3275 let item = self.active_item(cx)?;
3276 item.to_any_view().downcast::<I>().ok()
3277 }
3278
3279 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3280 self.active_item(cx).and_then(|item| item.project_path(cx))
3281 }
3282
3283 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3284 self.recent_navigation_history_iter(cx)
3285 .filter_map(|(path, abs_path)| {
3286 let worktree = self
3287 .project
3288 .read(cx)
3289 .worktree_for_id(path.worktree_id, cx)?;
3290 if worktree.read(cx).is_visible() {
3291 abs_path
3292 } else {
3293 None
3294 }
3295 })
3296 .next()
3297 }
3298
3299 pub fn save_active_item(
3300 &mut self,
3301 save_intent: SaveIntent,
3302 window: &mut Window,
3303 cx: &mut App,
3304 ) -> Task<Result<()>> {
3305 let project = self.project.clone();
3306 let pane = self.active_pane();
3307 let item = pane.read(cx).active_item();
3308 let pane = pane.downgrade();
3309
3310 window.spawn(cx, async move |cx| {
3311 if let Some(item) = item {
3312 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3313 .await
3314 .map(|_| ())
3315 } else {
3316 Ok(())
3317 }
3318 })
3319 }
3320
3321 pub fn close_inactive_items_and_panes(
3322 &mut self,
3323 action: &CloseInactiveTabsAndPanes,
3324 window: &mut Window,
3325 cx: &mut Context<Self>,
3326 ) {
3327 if let Some(task) = self.close_all_internal(
3328 true,
3329 action.save_intent.unwrap_or(SaveIntent::Close),
3330 window,
3331 cx,
3332 ) {
3333 task.detach_and_log_err(cx)
3334 }
3335 }
3336
3337 pub fn close_all_items_and_panes(
3338 &mut self,
3339 action: &CloseAllItemsAndPanes,
3340 window: &mut Window,
3341 cx: &mut Context<Self>,
3342 ) {
3343 if let Some(task) = self.close_all_internal(
3344 false,
3345 action.save_intent.unwrap_or(SaveIntent::Close),
3346 window,
3347 cx,
3348 ) {
3349 task.detach_and_log_err(cx)
3350 }
3351 }
3352
3353 /// Closes the active item across all panes.
3354 pub fn close_item_in_all_panes(
3355 &mut self,
3356 action: &CloseItemInAllPanes,
3357 window: &mut Window,
3358 cx: &mut Context<Self>,
3359 ) {
3360 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3361 return;
3362 };
3363
3364 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3365 let close_pinned = action.close_pinned;
3366
3367 if let Some(project_path) = active_item.project_path(cx) {
3368 self.close_items_with_project_path(
3369 &project_path,
3370 save_intent,
3371 close_pinned,
3372 window,
3373 cx,
3374 );
3375 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3376 let item_id = active_item.item_id();
3377 self.active_pane().update(cx, |pane, cx| {
3378 pane.close_item_by_id(item_id, save_intent, window, cx)
3379 .detach_and_log_err(cx);
3380 });
3381 }
3382 }
3383
3384 /// Closes all items with the given project path across all panes.
3385 pub fn close_items_with_project_path(
3386 &mut self,
3387 project_path: &ProjectPath,
3388 save_intent: SaveIntent,
3389 close_pinned: bool,
3390 window: &mut Window,
3391 cx: &mut Context<Self>,
3392 ) {
3393 let panes = self.panes().to_vec();
3394 for pane in panes {
3395 pane.update(cx, |pane, cx| {
3396 pane.close_items_for_project_path(
3397 project_path,
3398 save_intent,
3399 close_pinned,
3400 window,
3401 cx,
3402 )
3403 .detach_and_log_err(cx);
3404 });
3405 }
3406 }
3407
3408 fn close_all_internal(
3409 &mut self,
3410 retain_active_pane: bool,
3411 save_intent: SaveIntent,
3412 window: &mut Window,
3413 cx: &mut Context<Self>,
3414 ) -> Option<Task<Result<()>>> {
3415 let current_pane = self.active_pane();
3416
3417 let mut tasks = Vec::new();
3418
3419 if retain_active_pane {
3420 let current_pane_close = current_pane.update(cx, |pane, cx| {
3421 pane.close_other_items(
3422 &CloseOtherItems {
3423 save_intent: None,
3424 close_pinned: false,
3425 },
3426 None,
3427 window,
3428 cx,
3429 )
3430 });
3431
3432 tasks.push(current_pane_close);
3433 }
3434
3435 for pane in self.panes() {
3436 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3437 continue;
3438 }
3439
3440 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3441 pane.close_all_items(
3442 &CloseAllItems {
3443 save_intent: Some(save_intent),
3444 close_pinned: false,
3445 },
3446 window,
3447 cx,
3448 )
3449 });
3450
3451 tasks.push(close_pane_items)
3452 }
3453
3454 if tasks.is_empty() {
3455 None
3456 } else {
3457 Some(cx.spawn_in(window, async move |_, _| {
3458 for task in tasks {
3459 task.await?
3460 }
3461 Ok(())
3462 }))
3463 }
3464 }
3465
3466 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3467 self.dock_at_position(position).read(cx).is_open()
3468 }
3469
3470 pub fn toggle_dock(
3471 &mut self,
3472 dock_side: DockPosition,
3473 window: &mut Window,
3474 cx: &mut Context<Self>,
3475 ) {
3476 let mut focus_center = false;
3477 let mut reveal_dock = false;
3478
3479 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3480 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3481
3482 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3483 telemetry::event!(
3484 "Panel Button Clicked",
3485 name = panel.persistent_name(),
3486 toggle_state = !was_visible
3487 );
3488 }
3489 if was_visible {
3490 self.save_open_dock_positions(cx);
3491 }
3492
3493 let dock = self.dock_at_position(dock_side);
3494 dock.update(cx, |dock, cx| {
3495 dock.set_open(!was_visible, window, cx);
3496
3497 if dock.active_panel().is_none() {
3498 let Some(panel_ix) = dock
3499 .first_enabled_panel_idx(cx)
3500 .log_with_level(log::Level::Info)
3501 else {
3502 return;
3503 };
3504 dock.activate_panel(panel_ix, window, cx);
3505 }
3506
3507 if let Some(active_panel) = dock.active_panel() {
3508 if was_visible {
3509 if active_panel
3510 .panel_focus_handle(cx)
3511 .contains_focused(window, cx)
3512 {
3513 focus_center = true;
3514 }
3515 } else {
3516 let focus_handle = &active_panel.panel_focus_handle(cx);
3517 window.focus(focus_handle, cx);
3518 reveal_dock = true;
3519 }
3520 }
3521 });
3522
3523 if reveal_dock {
3524 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3525 }
3526
3527 if focus_center {
3528 self.active_pane
3529 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3530 }
3531
3532 cx.notify();
3533 self.serialize_workspace(window, cx);
3534 }
3535
3536 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3537 self.all_docks().into_iter().find(|&dock| {
3538 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3539 })
3540 }
3541
3542 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3543 if let Some(dock) = self.active_dock(window, cx).cloned() {
3544 self.save_open_dock_positions(cx);
3545 dock.update(cx, |dock, cx| {
3546 dock.set_open(false, window, cx);
3547 });
3548 return true;
3549 }
3550 false
3551 }
3552
3553 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3554 self.save_open_dock_positions(cx);
3555 for dock in self.all_docks() {
3556 dock.update(cx, |dock, cx| {
3557 dock.set_open(false, window, cx);
3558 });
3559 }
3560
3561 cx.focus_self(window);
3562 cx.notify();
3563 self.serialize_workspace(window, cx);
3564 }
3565
3566 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
3567 self.all_docks()
3568 .into_iter()
3569 .filter_map(|dock| {
3570 let dock_ref = dock.read(cx);
3571 if dock_ref.is_open() {
3572 Some(dock_ref.position())
3573 } else {
3574 None
3575 }
3576 })
3577 .collect()
3578 }
3579
3580 /// Saves the positions of currently open docks.
3581 ///
3582 /// Updates `last_open_dock_positions` with positions of all currently open
3583 /// docks, to later be restored by the 'Toggle All Docks' action.
3584 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
3585 let open_dock_positions = self.get_open_dock_positions(cx);
3586 if !open_dock_positions.is_empty() {
3587 self.last_open_dock_positions = open_dock_positions;
3588 }
3589 }
3590
3591 /// Toggles all docks between open and closed states.
3592 ///
3593 /// If any docks are open, closes all and remembers their positions. If all
3594 /// docks are closed, restores the last remembered dock configuration.
3595 fn toggle_all_docks(
3596 &mut self,
3597 _: &ToggleAllDocks,
3598 window: &mut Window,
3599 cx: &mut Context<Self>,
3600 ) {
3601 let open_dock_positions = self.get_open_dock_positions(cx);
3602
3603 if !open_dock_positions.is_empty() {
3604 self.close_all_docks(window, cx);
3605 } else if !self.last_open_dock_positions.is_empty() {
3606 self.restore_last_open_docks(window, cx);
3607 }
3608 }
3609
3610 /// Reopens docks from the most recently remembered configuration.
3611 ///
3612 /// Opens all docks whose positions are stored in `last_open_dock_positions`
3613 /// and clears the stored positions.
3614 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3615 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
3616
3617 for position in positions_to_open {
3618 let dock = self.dock_at_position(position);
3619 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
3620 }
3621
3622 cx.focus_self(window);
3623 cx.notify();
3624 self.serialize_workspace(window, cx);
3625 }
3626
3627 /// Transfer focus to the panel of the given type.
3628 pub fn focus_panel<T: Panel>(
3629 &mut self,
3630 window: &mut Window,
3631 cx: &mut Context<Self>,
3632 ) -> Option<Entity<T>> {
3633 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
3634 panel.to_any().downcast().ok()
3635 }
3636
3637 /// Focus the panel of the given type if it isn't already focused. If it is
3638 /// already focused, then transfer focus back to the workspace center.
3639 /// When the `close_panel_on_toggle` setting is enabled, also closes the
3640 /// panel when transferring focus back to the center.
3641 pub fn toggle_panel_focus<T: Panel>(
3642 &mut self,
3643 window: &mut Window,
3644 cx: &mut Context<Self>,
3645 ) -> bool {
3646 let mut did_focus_panel = false;
3647 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
3648 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
3649 did_focus_panel
3650 });
3651
3652 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
3653 self.close_panel::<T>(window, cx);
3654 }
3655
3656 telemetry::event!(
3657 "Panel Button Clicked",
3658 name = T::persistent_name(),
3659 toggle_state = did_focus_panel
3660 );
3661
3662 did_focus_panel
3663 }
3664
3665 pub fn activate_panel_for_proto_id(
3666 &mut self,
3667 panel_id: PanelId,
3668 window: &mut Window,
3669 cx: &mut Context<Self>,
3670 ) -> Option<Arc<dyn PanelHandle>> {
3671 let mut panel = None;
3672 for dock in self.all_docks() {
3673 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
3674 panel = dock.update(cx, |dock, cx| {
3675 dock.activate_panel(panel_index, window, cx);
3676 dock.set_open(true, window, cx);
3677 dock.active_panel().cloned()
3678 });
3679 break;
3680 }
3681 }
3682
3683 if panel.is_some() {
3684 cx.notify();
3685 self.serialize_workspace(window, cx);
3686 }
3687
3688 panel
3689 }
3690
3691 /// Focus or unfocus the given panel type, depending on the given callback.
3692 fn focus_or_unfocus_panel<T: Panel>(
3693 &mut self,
3694 window: &mut Window,
3695 cx: &mut Context<Self>,
3696 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
3697 ) -> Option<Arc<dyn PanelHandle>> {
3698 let mut result_panel = None;
3699 let mut serialize = false;
3700 for dock in self.all_docks() {
3701 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3702 let mut focus_center = false;
3703 let panel = dock.update(cx, |dock, cx| {
3704 dock.activate_panel(panel_index, window, cx);
3705
3706 let panel = dock.active_panel().cloned();
3707 if let Some(panel) = panel.as_ref() {
3708 if should_focus(&**panel, window, cx) {
3709 dock.set_open(true, window, cx);
3710 panel.panel_focus_handle(cx).focus(window, cx);
3711 } else {
3712 focus_center = true;
3713 }
3714 }
3715 panel
3716 });
3717
3718 if focus_center {
3719 self.active_pane
3720 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3721 }
3722
3723 result_panel = panel;
3724 serialize = true;
3725 break;
3726 }
3727 }
3728
3729 if serialize {
3730 self.serialize_workspace(window, cx);
3731 }
3732
3733 cx.notify();
3734 result_panel
3735 }
3736
3737 /// Open the panel of the given type
3738 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3739 for dock in self.all_docks() {
3740 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3741 dock.update(cx, |dock, cx| {
3742 dock.activate_panel(panel_index, window, cx);
3743 dock.set_open(true, window, cx);
3744 });
3745 }
3746 }
3747 }
3748
3749 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
3750 for dock in self.all_docks().iter() {
3751 dock.update(cx, |dock, cx| {
3752 if dock.panel::<T>().is_some() {
3753 dock.set_open(false, window, cx)
3754 }
3755 })
3756 }
3757 }
3758
3759 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
3760 self.all_docks()
3761 .iter()
3762 .find_map(|dock| dock.read(cx).panel::<T>())
3763 }
3764
3765 fn dismiss_zoomed_items_to_reveal(
3766 &mut self,
3767 dock_to_reveal: Option<DockPosition>,
3768 window: &mut Window,
3769 cx: &mut Context<Self>,
3770 ) {
3771 // If a center pane is zoomed, unzoom it.
3772 for pane in &self.panes {
3773 if pane != &self.active_pane || dock_to_reveal.is_some() {
3774 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
3775 }
3776 }
3777
3778 // If another dock is zoomed, hide it.
3779 let mut focus_center = false;
3780 for dock in self.all_docks() {
3781 dock.update(cx, |dock, cx| {
3782 if Some(dock.position()) != dock_to_reveal
3783 && let Some(panel) = dock.active_panel()
3784 && panel.is_zoomed(window, cx)
3785 {
3786 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
3787 dock.set_open(false, window, cx);
3788 }
3789 });
3790 }
3791
3792 if focus_center {
3793 self.active_pane
3794 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3795 }
3796
3797 if self.zoomed_position != dock_to_reveal {
3798 self.zoomed = None;
3799 self.zoomed_position = None;
3800 cx.emit(Event::ZoomChanged);
3801 }
3802
3803 cx.notify();
3804 }
3805
3806 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
3807 let pane = cx.new(|cx| {
3808 let mut pane = Pane::new(
3809 self.weak_handle(),
3810 self.project.clone(),
3811 self.pane_history_timestamp.clone(),
3812 None,
3813 NewFile.boxed_clone(),
3814 true,
3815 window,
3816 cx,
3817 );
3818 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
3819 pane
3820 });
3821 cx.subscribe_in(&pane, window, Self::handle_pane_event)
3822 .detach();
3823 self.panes.push(pane.clone());
3824
3825 window.focus(&pane.focus_handle(cx), cx);
3826
3827 cx.emit(Event::PaneAdded(pane.clone()));
3828 pane
3829 }
3830
3831 pub fn add_item_to_center(
3832 &mut self,
3833 item: Box<dyn ItemHandle>,
3834 window: &mut Window,
3835 cx: &mut Context<Self>,
3836 ) -> bool {
3837 if let Some(center_pane) = self.last_active_center_pane.clone() {
3838 if let Some(center_pane) = center_pane.upgrade() {
3839 center_pane.update(cx, |pane, cx| {
3840 pane.add_item(item, true, true, None, window, cx)
3841 });
3842 true
3843 } else {
3844 false
3845 }
3846 } else {
3847 false
3848 }
3849 }
3850
3851 pub fn add_item_to_active_pane(
3852 &mut self,
3853 item: Box<dyn ItemHandle>,
3854 destination_index: Option<usize>,
3855 focus_item: bool,
3856 window: &mut Window,
3857 cx: &mut App,
3858 ) {
3859 self.add_item(
3860 self.active_pane.clone(),
3861 item,
3862 destination_index,
3863 false,
3864 focus_item,
3865 window,
3866 cx,
3867 )
3868 }
3869
3870 pub fn add_item(
3871 &mut self,
3872 pane: Entity<Pane>,
3873 item: Box<dyn ItemHandle>,
3874 destination_index: Option<usize>,
3875 activate_pane: bool,
3876 focus_item: bool,
3877 window: &mut Window,
3878 cx: &mut App,
3879 ) {
3880 pane.update(cx, |pane, cx| {
3881 pane.add_item(
3882 item,
3883 activate_pane,
3884 focus_item,
3885 destination_index,
3886 window,
3887 cx,
3888 )
3889 });
3890 }
3891
3892 pub fn split_item(
3893 &mut self,
3894 split_direction: SplitDirection,
3895 item: Box<dyn ItemHandle>,
3896 window: &mut Window,
3897 cx: &mut Context<Self>,
3898 ) {
3899 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
3900 self.add_item(new_pane, item, None, true, true, window, cx);
3901 }
3902
3903 pub fn open_abs_path(
3904 &mut self,
3905 abs_path: PathBuf,
3906 options: OpenOptions,
3907 window: &mut Window,
3908 cx: &mut Context<Self>,
3909 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3910 cx.spawn_in(window, async move |workspace, cx| {
3911 let open_paths_task_result = workspace
3912 .update_in(cx, |workspace, window, cx| {
3913 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
3914 })
3915 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
3916 .await;
3917 anyhow::ensure!(
3918 open_paths_task_result.len() == 1,
3919 "open abs path {abs_path:?} task returned incorrect number of results"
3920 );
3921 match open_paths_task_result
3922 .into_iter()
3923 .next()
3924 .expect("ensured single task result")
3925 {
3926 Some(open_result) => {
3927 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
3928 }
3929 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
3930 }
3931 })
3932 }
3933
3934 pub fn split_abs_path(
3935 &mut self,
3936 abs_path: PathBuf,
3937 visible: bool,
3938 window: &mut Window,
3939 cx: &mut Context<Self>,
3940 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3941 let project_path_task =
3942 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
3943 cx.spawn_in(window, async move |this, cx| {
3944 let (_, path) = project_path_task.await?;
3945 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
3946 .await
3947 })
3948 }
3949
3950 pub fn open_path(
3951 &mut self,
3952 path: impl Into<ProjectPath>,
3953 pane: Option<WeakEntity<Pane>>,
3954 focus_item: bool,
3955 window: &mut Window,
3956 cx: &mut App,
3957 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3958 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
3959 }
3960
3961 pub fn open_path_preview(
3962 &mut self,
3963 path: impl Into<ProjectPath>,
3964 pane: Option<WeakEntity<Pane>>,
3965 focus_item: bool,
3966 allow_preview: bool,
3967 activate: bool,
3968 window: &mut Window,
3969 cx: &mut App,
3970 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3971 let pane = pane.unwrap_or_else(|| {
3972 self.last_active_center_pane.clone().unwrap_or_else(|| {
3973 self.panes
3974 .first()
3975 .expect("There must be an active pane")
3976 .downgrade()
3977 })
3978 });
3979
3980 let project_path = path.into();
3981 let task = self.load_path(project_path.clone(), window, cx);
3982 window.spawn(cx, async move |cx| {
3983 let (project_entry_id, build_item) = task.await?;
3984
3985 pane.update_in(cx, |pane, window, cx| {
3986 pane.open_item(
3987 project_entry_id,
3988 project_path,
3989 focus_item,
3990 allow_preview,
3991 activate,
3992 None,
3993 window,
3994 cx,
3995 build_item,
3996 )
3997 })
3998 })
3999 }
4000
4001 pub fn split_path(
4002 &mut self,
4003 path: impl Into<ProjectPath>,
4004 window: &mut Window,
4005 cx: &mut Context<Self>,
4006 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4007 self.split_path_preview(path, false, None, window, cx)
4008 }
4009
4010 pub fn split_path_preview(
4011 &mut self,
4012 path: impl Into<ProjectPath>,
4013 allow_preview: bool,
4014 split_direction: Option<SplitDirection>,
4015 window: &mut Window,
4016 cx: &mut Context<Self>,
4017 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4018 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4019 self.panes
4020 .first()
4021 .expect("There must be an active pane")
4022 .downgrade()
4023 });
4024
4025 if let Member::Pane(center_pane) = &self.center.root
4026 && center_pane.read(cx).items_len() == 0
4027 {
4028 return self.open_path(path, Some(pane), true, window, cx);
4029 }
4030
4031 let project_path = path.into();
4032 let task = self.load_path(project_path.clone(), window, cx);
4033 cx.spawn_in(window, async move |this, cx| {
4034 let (project_entry_id, build_item) = task.await?;
4035 this.update_in(cx, move |this, window, cx| -> Option<_> {
4036 let pane = pane.upgrade()?;
4037 let new_pane = this.split_pane(
4038 pane,
4039 split_direction.unwrap_or(SplitDirection::Right),
4040 window,
4041 cx,
4042 );
4043 new_pane.update(cx, |new_pane, cx| {
4044 Some(new_pane.open_item(
4045 project_entry_id,
4046 project_path,
4047 true,
4048 allow_preview,
4049 true,
4050 None,
4051 window,
4052 cx,
4053 build_item,
4054 ))
4055 })
4056 })
4057 .map(|option| option.context("pane was dropped"))?
4058 })
4059 }
4060
4061 fn load_path(
4062 &mut self,
4063 path: ProjectPath,
4064 window: &mut Window,
4065 cx: &mut App,
4066 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4067 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4068 registry.open_path(self.project(), &path, window, cx)
4069 }
4070
4071 pub fn find_project_item<T>(
4072 &self,
4073 pane: &Entity<Pane>,
4074 project_item: &Entity<T::Item>,
4075 cx: &App,
4076 ) -> Option<Entity<T>>
4077 where
4078 T: ProjectItem,
4079 {
4080 use project::ProjectItem as _;
4081 let project_item = project_item.read(cx);
4082 let entry_id = project_item.entry_id(cx);
4083 let project_path = project_item.project_path(cx);
4084
4085 let mut item = None;
4086 if let Some(entry_id) = entry_id {
4087 item = pane.read(cx).item_for_entry(entry_id, cx);
4088 }
4089 if item.is_none()
4090 && let Some(project_path) = project_path
4091 {
4092 item = pane.read(cx).item_for_path(project_path, cx);
4093 }
4094
4095 item.and_then(|item| item.downcast::<T>())
4096 }
4097
4098 pub fn is_project_item_open<T>(
4099 &self,
4100 pane: &Entity<Pane>,
4101 project_item: &Entity<T::Item>,
4102 cx: &App,
4103 ) -> bool
4104 where
4105 T: ProjectItem,
4106 {
4107 self.find_project_item::<T>(pane, project_item, cx)
4108 .is_some()
4109 }
4110
4111 pub fn open_project_item<T>(
4112 &mut self,
4113 pane: Entity<Pane>,
4114 project_item: Entity<T::Item>,
4115 activate_pane: bool,
4116 focus_item: bool,
4117 keep_old_preview: bool,
4118 allow_new_preview: bool,
4119 window: &mut Window,
4120 cx: &mut Context<Self>,
4121 ) -> Entity<T>
4122 where
4123 T: ProjectItem,
4124 {
4125 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4126
4127 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4128 if !keep_old_preview
4129 && let Some(old_id) = old_item_id
4130 && old_id != item.item_id()
4131 {
4132 // switching to a different item, so unpreview old active item
4133 pane.update(cx, |pane, _| {
4134 pane.unpreview_item_if_preview(old_id);
4135 });
4136 }
4137
4138 self.activate_item(&item, activate_pane, focus_item, window, cx);
4139 if !allow_new_preview {
4140 pane.update(cx, |pane, _| {
4141 pane.unpreview_item_if_preview(item.item_id());
4142 });
4143 }
4144 return item;
4145 }
4146
4147 let item = pane.update(cx, |pane, cx| {
4148 cx.new(|cx| {
4149 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4150 })
4151 });
4152 let mut destination_index = None;
4153 pane.update(cx, |pane, cx| {
4154 if !keep_old_preview && let Some(old_id) = old_item_id {
4155 pane.unpreview_item_if_preview(old_id);
4156 }
4157 if allow_new_preview {
4158 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4159 }
4160 });
4161
4162 self.add_item(
4163 pane,
4164 Box::new(item.clone()),
4165 destination_index,
4166 activate_pane,
4167 focus_item,
4168 window,
4169 cx,
4170 );
4171 item
4172 }
4173
4174 pub fn open_shared_screen(
4175 &mut self,
4176 peer_id: PeerId,
4177 window: &mut Window,
4178 cx: &mut Context<Self>,
4179 ) {
4180 if let Some(shared_screen) =
4181 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4182 {
4183 self.active_pane.update(cx, |pane, cx| {
4184 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4185 });
4186 }
4187 }
4188
4189 pub fn activate_item(
4190 &mut self,
4191 item: &dyn ItemHandle,
4192 activate_pane: bool,
4193 focus_item: bool,
4194 window: &mut Window,
4195 cx: &mut App,
4196 ) -> bool {
4197 let result = self.panes.iter().find_map(|pane| {
4198 pane.read(cx)
4199 .index_for_item(item)
4200 .map(|ix| (pane.clone(), ix))
4201 });
4202 if let Some((pane, ix)) = result {
4203 pane.update(cx, |pane, cx| {
4204 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4205 });
4206 true
4207 } else {
4208 false
4209 }
4210 }
4211
4212 fn activate_pane_at_index(
4213 &mut self,
4214 action: &ActivatePane,
4215 window: &mut Window,
4216 cx: &mut Context<Self>,
4217 ) {
4218 let panes = self.center.panes();
4219 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4220 window.focus(&pane.focus_handle(cx), cx);
4221 } else {
4222 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4223 .detach();
4224 }
4225 }
4226
4227 fn move_item_to_pane_at_index(
4228 &mut self,
4229 action: &MoveItemToPane,
4230 window: &mut Window,
4231 cx: &mut Context<Self>,
4232 ) {
4233 let panes = self.center.panes();
4234 let destination = match panes.get(action.destination) {
4235 Some(&destination) => destination.clone(),
4236 None => {
4237 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4238 return;
4239 }
4240 let direction = SplitDirection::Right;
4241 let split_off_pane = self
4242 .find_pane_in_direction(direction, cx)
4243 .unwrap_or_else(|| self.active_pane.clone());
4244 let new_pane = self.add_pane(window, cx);
4245 if self
4246 .center
4247 .split(&split_off_pane, &new_pane, direction, cx)
4248 .log_err()
4249 .is_none()
4250 {
4251 return;
4252 };
4253 new_pane
4254 }
4255 };
4256
4257 if action.clone {
4258 if self
4259 .active_pane
4260 .read(cx)
4261 .active_item()
4262 .is_some_and(|item| item.can_split(cx))
4263 {
4264 clone_active_item(
4265 self.database_id(),
4266 &self.active_pane,
4267 &destination,
4268 action.focus,
4269 window,
4270 cx,
4271 );
4272 return;
4273 }
4274 }
4275 move_active_item(
4276 &self.active_pane,
4277 &destination,
4278 action.focus,
4279 true,
4280 window,
4281 cx,
4282 )
4283 }
4284
4285 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4286 let panes = self.center.panes();
4287 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4288 let next_ix = (ix + 1) % panes.len();
4289 let next_pane = panes[next_ix].clone();
4290 window.focus(&next_pane.focus_handle(cx), cx);
4291 }
4292 }
4293
4294 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4295 let panes = self.center.panes();
4296 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4297 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4298 let prev_pane = panes[prev_ix].clone();
4299 window.focus(&prev_pane.focus_handle(cx), cx);
4300 }
4301 }
4302
4303 pub fn activate_pane_in_direction(
4304 &mut self,
4305 direction: SplitDirection,
4306 window: &mut Window,
4307 cx: &mut App,
4308 ) {
4309 use ActivateInDirectionTarget as Target;
4310 enum Origin {
4311 LeftDock,
4312 RightDock,
4313 BottomDock,
4314 Center,
4315 }
4316
4317 let origin: Origin = [
4318 (&self.left_dock, Origin::LeftDock),
4319 (&self.right_dock, Origin::RightDock),
4320 (&self.bottom_dock, Origin::BottomDock),
4321 ]
4322 .into_iter()
4323 .find_map(|(dock, origin)| {
4324 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4325 Some(origin)
4326 } else {
4327 None
4328 }
4329 })
4330 .unwrap_or(Origin::Center);
4331
4332 let get_last_active_pane = || {
4333 let pane = self
4334 .last_active_center_pane
4335 .clone()
4336 .unwrap_or_else(|| {
4337 self.panes
4338 .first()
4339 .expect("There must be an active pane")
4340 .downgrade()
4341 })
4342 .upgrade()?;
4343 (pane.read(cx).items_len() != 0).then_some(pane)
4344 };
4345
4346 let try_dock =
4347 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4348
4349 let target = match (origin, direction) {
4350 // We're in the center, so we first try to go to a different pane,
4351 // otherwise try to go to a dock.
4352 (Origin::Center, direction) => {
4353 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4354 Some(Target::Pane(pane))
4355 } else {
4356 match direction {
4357 SplitDirection::Up => None,
4358 SplitDirection::Down => try_dock(&self.bottom_dock),
4359 SplitDirection::Left => try_dock(&self.left_dock),
4360 SplitDirection::Right => try_dock(&self.right_dock),
4361 }
4362 }
4363 }
4364
4365 (Origin::LeftDock, SplitDirection::Right) => {
4366 if let Some(last_active_pane) = get_last_active_pane() {
4367 Some(Target::Pane(last_active_pane))
4368 } else {
4369 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4370 }
4371 }
4372
4373 (Origin::LeftDock, SplitDirection::Down)
4374 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4375
4376 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4377 (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
4378 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4379
4380 (Origin::RightDock, SplitDirection::Left) => {
4381 if let Some(last_active_pane) = get_last_active_pane() {
4382 Some(Target::Pane(last_active_pane))
4383 } else {
4384 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
4385 }
4386 }
4387
4388 _ => None,
4389 };
4390
4391 match target {
4392 Some(ActivateInDirectionTarget::Pane(pane)) => {
4393 let pane = pane.read(cx);
4394 if let Some(item) = pane.active_item() {
4395 item.item_focus_handle(cx).focus(window, cx);
4396 } else {
4397 log::error!(
4398 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4399 );
4400 }
4401 }
4402 Some(ActivateInDirectionTarget::Dock(dock)) => {
4403 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4404 window.defer(cx, move |window, cx| {
4405 let dock = dock.read(cx);
4406 if let Some(panel) = dock.active_panel() {
4407 panel.panel_focus_handle(cx).focus(window, cx);
4408 } else {
4409 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4410 }
4411 })
4412 }
4413 None => {}
4414 }
4415 }
4416
4417 pub fn move_item_to_pane_in_direction(
4418 &mut self,
4419 action: &MoveItemToPaneInDirection,
4420 window: &mut Window,
4421 cx: &mut Context<Self>,
4422 ) {
4423 let destination = match self.find_pane_in_direction(action.direction, cx) {
4424 Some(destination) => destination,
4425 None => {
4426 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4427 return;
4428 }
4429 let new_pane = self.add_pane(window, cx);
4430 if self
4431 .center
4432 .split(&self.active_pane, &new_pane, action.direction, cx)
4433 .log_err()
4434 .is_none()
4435 {
4436 return;
4437 };
4438 new_pane
4439 }
4440 };
4441
4442 if action.clone {
4443 if self
4444 .active_pane
4445 .read(cx)
4446 .active_item()
4447 .is_some_and(|item| item.can_split(cx))
4448 {
4449 clone_active_item(
4450 self.database_id(),
4451 &self.active_pane,
4452 &destination,
4453 action.focus,
4454 window,
4455 cx,
4456 );
4457 return;
4458 }
4459 }
4460 move_active_item(
4461 &self.active_pane,
4462 &destination,
4463 action.focus,
4464 true,
4465 window,
4466 cx,
4467 );
4468 }
4469
4470 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4471 self.center.bounding_box_for_pane(pane)
4472 }
4473
4474 pub fn find_pane_in_direction(
4475 &mut self,
4476 direction: SplitDirection,
4477 cx: &App,
4478 ) -> Option<Entity<Pane>> {
4479 self.center
4480 .find_pane_in_direction(&self.active_pane, direction, cx)
4481 .cloned()
4482 }
4483
4484 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4485 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4486 self.center.swap(&self.active_pane, &to, cx);
4487 cx.notify();
4488 }
4489 }
4490
4491 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4492 if self
4493 .center
4494 .move_to_border(&self.active_pane, direction, cx)
4495 .unwrap()
4496 {
4497 cx.notify();
4498 }
4499 }
4500
4501 pub fn resize_pane(
4502 &mut self,
4503 axis: gpui::Axis,
4504 amount: Pixels,
4505 window: &mut Window,
4506 cx: &mut Context<Self>,
4507 ) {
4508 let docks = self.all_docks();
4509 let active_dock = docks
4510 .into_iter()
4511 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4512
4513 if let Some(dock) = active_dock {
4514 let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
4515 return;
4516 };
4517 match dock.read(cx).position() {
4518 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4519 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4520 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4521 }
4522 } else {
4523 self.center
4524 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
4525 }
4526 cx.notify();
4527 }
4528
4529 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
4530 self.center.reset_pane_sizes(cx);
4531 cx.notify();
4532 }
4533
4534 fn handle_pane_focused(
4535 &mut self,
4536 pane: Entity<Pane>,
4537 window: &mut Window,
4538 cx: &mut Context<Self>,
4539 ) {
4540 // This is explicitly hoisted out of the following check for pane identity as
4541 // terminal panel panes are not registered as a center panes.
4542 self.status_bar.update(cx, |status_bar, cx| {
4543 status_bar.set_active_pane(&pane, window, cx);
4544 });
4545 if self.active_pane != pane {
4546 self.set_active_pane(&pane, window, cx);
4547 }
4548
4549 if self.last_active_center_pane.is_none() {
4550 self.last_active_center_pane = Some(pane.downgrade());
4551 }
4552
4553 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
4554 // This prevents the dock from closing when focus events fire during window activation.
4555 // We also preserve any dock whose active panel itself has focus — this covers
4556 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
4557 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
4558 let dock_read = dock.read(cx);
4559 if let Some(panel) = dock_read.active_panel() {
4560 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
4561 || panel.panel_focus_handle(cx).contains_focused(window, cx)
4562 {
4563 return Some(dock_read.position());
4564 }
4565 }
4566 None
4567 });
4568
4569 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
4570 if pane.read(cx).is_zoomed() {
4571 self.zoomed = Some(pane.downgrade().into());
4572 } else {
4573 self.zoomed = None;
4574 }
4575 self.zoomed_position = None;
4576 cx.emit(Event::ZoomChanged);
4577 self.update_active_view_for_followers(window, cx);
4578 pane.update(cx, |pane, _| {
4579 pane.track_alternate_file_items();
4580 });
4581
4582 cx.notify();
4583 }
4584
4585 fn set_active_pane(
4586 &mut self,
4587 pane: &Entity<Pane>,
4588 window: &mut Window,
4589 cx: &mut Context<Self>,
4590 ) {
4591 self.active_pane = pane.clone();
4592 self.active_item_path_changed(true, window, cx);
4593 self.last_active_center_pane = Some(pane.downgrade());
4594 }
4595
4596 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4597 self.update_active_view_for_followers(window, cx);
4598 }
4599
4600 fn handle_pane_event(
4601 &mut self,
4602 pane: &Entity<Pane>,
4603 event: &pane::Event,
4604 window: &mut Window,
4605 cx: &mut Context<Self>,
4606 ) {
4607 let mut serialize_workspace = true;
4608 match event {
4609 pane::Event::AddItem { item } => {
4610 item.added_to_pane(self, pane.clone(), window, cx);
4611 cx.emit(Event::ItemAdded {
4612 item: item.boxed_clone(),
4613 });
4614 }
4615 pane::Event::Split { direction, mode } => {
4616 match mode {
4617 SplitMode::ClonePane => {
4618 self.split_and_clone(pane.clone(), *direction, window, cx)
4619 .detach();
4620 }
4621 SplitMode::EmptyPane => {
4622 self.split_pane(pane.clone(), *direction, window, cx);
4623 }
4624 SplitMode::MovePane => {
4625 self.split_and_move(pane.clone(), *direction, window, cx);
4626 }
4627 };
4628 }
4629 pane::Event::JoinIntoNext => {
4630 self.join_pane_into_next(pane.clone(), window, cx);
4631 }
4632 pane::Event::JoinAll => {
4633 self.join_all_panes(window, cx);
4634 }
4635 pane::Event::Remove { focus_on_pane } => {
4636 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
4637 }
4638 pane::Event::ActivateItem {
4639 local,
4640 focus_changed,
4641 } => {
4642 window.invalidate_character_coordinates();
4643
4644 pane.update(cx, |pane, _| {
4645 pane.track_alternate_file_items();
4646 });
4647 if *local {
4648 self.unfollow_in_pane(pane, window, cx);
4649 }
4650 serialize_workspace = *focus_changed || pane != self.active_pane();
4651 if pane == self.active_pane() {
4652 self.active_item_path_changed(*focus_changed, window, cx);
4653 self.update_active_view_for_followers(window, cx);
4654 } else if *local {
4655 self.set_active_pane(pane, window, cx);
4656 }
4657 }
4658 pane::Event::UserSavedItem { item, save_intent } => {
4659 cx.emit(Event::UserSavedItem {
4660 pane: pane.downgrade(),
4661 item: item.boxed_clone(),
4662 save_intent: *save_intent,
4663 });
4664 serialize_workspace = false;
4665 }
4666 pane::Event::ChangeItemTitle => {
4667 if *pane == self.active_pane {
4668 self.active_item_path_changed(false, window, cx);
4669 }
4670 serialize_workspace = false;
4671 }
4672 pane::Event::RemovedItem { item } => {
4673 cx.emit(Event::ActiveItemChanged);
4674 self.update_window_edited(window, cx);
4675 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
4676 && entry.get().entity_id() == pane.entity_id()
4677 {
4678 entry.remove();
4679 }
4680 cx.emit(Event::ItemRemoved {
4681 item_id: item.item_id(),
4682 });
4683 }
4684 pane::Event::Focus => {
4685 window.invalidate_character_coordinates();
4686 self.handle_pane_focused(pane.clone(), window, cx);
4687 }
4688 pane::Event::ZoomIn => {
4689 if *pane == self.active_pane {
4690 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
4691 if pane.read(cx).has_focus(window, cx) {
4692 self.zoomed = Some(pane.downgrade().into());
4693 self.zoomed_position = None;
4694 cx.emit(Event::ZoomChanged);
4695 }
4696 cx.notify();
4697 }
4698 }
4699 pane::Event::ZoomOut => {
4700 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4701 if self.zoomed_position.is_none() {
4702 self.zoomed = None;
4703 cx.emit(Event::ZoomChanged);
4704 }
4705 cx.notify();
4706 }
4707 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
4708 }
4709
4710 if serialize_workspace {
4711 self.serialize_workspace(window, cx);
4712 }
4713 }
4714
4715 pub fn unfollow_in_pane(
4716 &mut self,
4717 pane: &Entity<Pane>,
4718 window: &mut Window,
4719 cx: &mut Context<Workspace>,
4720 ) -> Option<CollaboratorId> {
4721 let leader_id = self.leader_for_pane(pane)?;
4722 self.unfollow(leader_id, window, cx);
4723 Some(leader_id)
4724 }
4725
4726 pub fn split_pane(
4727 &mut self,
4728 pane_to_split: Entity<Pane>,
4729 split_direction: SplitDirection,
4730 window: &mut Window,
4731 cx: &mut Context<Self>,
4732 ) -> Entity<Pane> {
4733 let new_pane = self.add_pane(window, cx);
4734 self.center
4735 .split(&pane_to_split, &new_pane, split_direction, cx)
4736 .unwrap();
4737 cx.notify();
4738 new_pane
4739 }
4740
4741 pub fn split_and_move(
4742 &mut self,
4743 pane: Entity<Pane>,
4744 direction: SplitDirection,
4745 window: &mut Window,
4746 cx: &mut Context<Self>,
4747 ) {
4748 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
4749 return;
4750 };
4751 let new_pane = self.add_pane(window, cx);
4752 new_pane.update(cx, |pane, cx| {
4753 pane.add_item(item, true, true, None, window, cx)
4754 });
4755 self.center.split(&pane, &new_pane, direction, cx).unwrap();
4756 cx.notify();
4757 }
4758
4759 pub fn split_and_clone(
4760 &mut self,
4761 pane: Entity<Pane>,
4762 direction: SplitDirection,
4763 window: &mut Window,
4764 cx: &mut Context<Self>,
4765 ) -> Task<Option<Entity<Pane>>> {
4766 let Some(item) = pane.read(cx).active_item() else {
4767 return Task::ready(None);
4768 };
4769 if !item.can_split(cx) {
4770 return Task::ready(None);
4771 }
4772 let task = item.clone_on_split(self.database_id(), window, cx);
4773 cx.spawn_in(window, async move |this, cx| {
4774 if let Some(clone) = task.await {
4775 this.update_in(cx, |this, window, cx| {
4776 let new_pane = this.add_pane(window, cx);
4777 let nav_history = pane.read(cx).fork_nav_history();
4778 new_pane.update(cx, |pane, cx| {
4779 pane.set_nav_history(nav_history, cx);
4780 pane.add_item(clone, true, true, None, window, cx)
4781 });
4782 this.center.split(&pane, &new_pane, direction, cx).unwrap();
4783 cx.notify();
4784 new_pane
4785 })
4786 .ok()
4787 } else {
4788 None
4789 }
4790 })
4791 }
4792
4793 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4794 let active_item = self.active_pane.read(cx).active_item();
4795 for pane in &self.panes {
4796 join_pane_into_active(&self.active_pane, pane, window, cx);
4797 }
4798 if let Some(active_item) = active_item {
4799 self.activate_item(active_item.as_ref(), true, true, window, cx);
4800 }
4801 cx.notify();
4802 }
4803
4804 pub fn join_pane_into_next(
4805 &mut self,
4806 pane: Entity<Pane>,
4807 window: &mut Window,
4808 cx: &mut Context<Self>,
4809 ) {
4810 let next_pane = self
4811 .find_pane_in_direction(SplitDirection::Right, cx)
4812 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
4813 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
4814 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
4815 let Some(next_pane) = next_pane else {
4816 return;
4817 };
4818 move_all_items(&pane, &next_pane, window, cx);
4819 cx.notify();
4820 }
4821
4822 fn remove_pane(
4823 &mut self,
4824 pane: Entity<Pane>,
4825 focus_on: Option<Entity<Pane>>,
4826 window: &mut Window,
4827 cx: &mut Context<Self>,
4828 ) {
4829 if self.center.remove(&pane, cx).unwrap() {
4830 self.force_remove_pane(&pane, &focus_on, window, cx);
4831 self.unfollow_in_pane(&pane, window, cx);
4832 self.last_leaders_by_pane.remove(&pane.downgrade());
4833 for removed_item in pane.read(cx).items() {
4834 self.panes_by_item.remove(&removed_item.item_id());
4835 }
4836
4837 cx.notify();
4838 } else {
4839 self.active_item_path_changed(true, window, cx);
4840 }
4841 cx.emit(Event::PaneRemoved);
4842 }
4843
4844 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
4845 &mut self.panes
4846 }
4847
4848 pub fn panes(&self) -> &[Entity<Pane>] {
4849 &self.panes
4850 }
4851
4852 pub fn active_pane(&self) -> &Entity<Pane> {
4853 &self.active_pane
4854 }
4855
4856 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
4857 for dock in self.all_docks() {
4858 if dock.focus_handle(cx).contains_focused(window, cx)
4859 && let Some(pane) = dock
4860 .read(cx)
4861 .active_panel()
4862 .and_then(|panel| panel.pane(cx))
4863 {
4864 return pane;
4865 }
4866 }
4867 self.active_pane().clone()
4868 }
4869
4870 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4871 self.find_pane_in_direction(SplitDirection::Right, cx)
4872 .unwrap_or_else(|| {
4873 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
4874 })
4875 }
4876
4877 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
4878 let weak_pane = self.panes_by_item.get(&handle.item_id())?;
4879 weak_pane.upgrade()
4880 }
4881
4882 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
4883 self.follower_states.retain(|leader_id, state| {
4884 if *leader_id == CollaboratorId::PeerId(peer_id) {
4885 for item in state.items_by_leader_view_id.values() {
4886 item.view.set_leader_id(None, window, cx);
4887 }
4888 false
4889 } else {
4890 true
4891 }
4892 });
4893 cx.notify();
4894 }
4895
4896 pub fn start_following(
4897 &mut self,
4898 leader_id: impl Into<CollaboratorId>,
4899 window: &mut Window,
4900 cx: &mut Context<Self>,
4901 ) -> Option<Task<Result<()>>> {
4902 let leader_id = leader_id.into();
4903 let pane = self.active_pane().clone();
4904
4905 self.last_leaders_by_pane
4906 .insert(pane.downgrade(), leader_id);
4907 self.unfollow(leader_id, window, cx);
4908 self.unfollow_in_pane(&pane, window, cx);
4909 self.follower_states.insert(
4910 leader_id,
4911 FollowerState {
4912 center_pane: pane.clone(),
4913 dock_pane: None,
4914 active_view_id: None,
4915 items_by_leader_view_id: Default::default(),
4916 },
4917 );
4918 cx.notify();
4919
4920 match leader_id {
4921 CollaboratorId::PeerId(leader_peer_id) => {
4922 let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
4923 let project_id = self.project.read(cx).remote_id();
4924 let request = self.app_state.client.request(proto::Follow {
4925 room_id,
4926 project_id,
4927 leader_id: Some(leader_peer_id),
4928 });
4929
4930 Some(cx.spawn_in(window, async move |this, cx| {
4931 let response = request.await?;
4932 this.update(cx, |this, _| {
4933 let state = this
4934 .follower_states
4935 .get_mut(&leader_id)
4936 .context("following interrupted")?;
4937 state.active_view_id = response
4938 .active_view
4939 .as_ref()
4940 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
4941 anyhow::Ok(())
4942 })??;
4943 if let Some(view) = response.active_view {
4944 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
4945 }
4946 this.update_in(cx, |this, window, cx| {
4947 this.leader_updated(leader_id, window, cx)
4948 })?;
4949 Ok(())
4950 }))
4951 }
4952 CollaboratorId::Agent => {
4953 self.leader_updated(leader_id, window, cx)?;
4954 Some(Task::ready(Ok(())))
4955 }
4956 }
4957 }
4958
4959 pub fn follow_next_collaborator(
4960 &mut self,
4961 _: &FollowNextCollaborator,
4962 window: &mut Window,
4963 cx: &mut Context<Self>,
4964 ) {
4965 let collaborators = self.project.read(cx).collaborators();
4966 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
4967 let mut collaborators = collaborators.keys().copied();
4968 for peer_id in collaborators.by_ref() {
4969 if CollaboratorId::PeerId(peer_id) == leader_id {
4970 break;
4971 }
4972 }
4973 collaborators.next().map(CollaboratorId::PeerId)
4974 } else if let Some(last_leader_id) =
4975 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
4976 {
4977 match last_leader_id {
4978 CollaboratorId::PeerId(peer_id) => {
4979 if collaborators.contains_key(peer_id) {
4980 Some(*last_leader_id)
4981 } else {
4982 None
4983 }
4984 }
4985 CollaboratorId::Agent => Some(CollaboratorId::Agent),
4986 }
4987 } else {
4988 None
4989 };
4990
4991 let pane = self.active_pane.clone();
4992 let Some(leader_id) = next_leader_id.or_else(|| {
4993 Some(CollaboratorId::PeerId(
4994 collaborators.keys().copied().next()?,
4995 ))
4996 }) else {
4997 return;
4998 };
4999 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5000 return;
5001 }
5002 if let Some(task) = self.start_following(leader_id, window, cx) {
5003 task.detach_and_log_err(cx)
5004 }
5005 }
5006
5007 pub fn follow(
5008 &mut self,
5009 leader_id: impl Into<CollaboratorId>,
5010 window: &mut Window,
5011 cx: &mut Context<Self>,
5012 ) {
5013 let leader_id = leader_id.into();
5014
5015 if let CollaboratorId::PeerId(peer_id) = leader_id {
5016 let Some(room) = ActiveCall::global(cx).read(cx).room() else {
5017 return;
5018 };
5019 let room = room.read(cx);
5020 let Some(remote_participant) = room.remote_participant_for_peer_id(peer_id) else {
5021 return;
5022 };
5023
5024 let project = self.project.read(cx);
5025
5026 let other_project_id = match remote_participant.location {
5027 call::ParticipantLocation::External => None,
5028 call::ParticipantLocation::UnsharedProject => None,
5029 call::ParticipantLocation::SharedProject { project_id } => {
5030 if Some(project_id) == project.remote_id() {
5031 None
5032 } else {
5033 Some(project_id)
5034 }
5035 }
5036 };
5037
5038 // if they are active in another project, follow there.
5039 if let Some(project_id) = other_project_id {
5040 let app_state = self.app_state.clone();
5041 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5042 .detach_and_log_err(cx);
5043 }
5044 }
5045
5046 // if you're already following, find the right pane and focus it.
5047 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5048 window.focus(&follower_state.pane().focus_handle(cx), cx);
5049
5050 return;
5051 }
5052
5053 // Otherwise, follow.
5054 if let Some(task) = self.start_following(leader_id, window, cx) {
5055 task.detach_and_log_err(cx)
5056 }
5057 }
5058
5059 pub fn unfollow(
5060 &mut self,
5061 leader_id: impl Into<CollaboratorId>,
5062 window: &mut Window,
5063 cx: &mut Context<Self>,
5064 ) -> Option<()> {
5065 cx.notify();
5066
5067 let leader_id = leader_id.into();
5068 let state = self.follower_states.remove(&leader_id)?;
5069 for (_, item) in state.items_by_leader_view_id {
5070 item.view.set_leader_id(None, window, cx);
5071 }
5072
5073 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5074 let project_id = self.project.read(cx).remote_id();
5075 let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
5076 self.app_state
5077 .client
5078 .send(proto::Unfollow {
5079 room_id,
5080 project_id,
5081 leader_id: Some(leader_peer_id),
5082 })
5083 .log_err();
5084 }
5085
5086 Some(())
5087 }
5088
5089 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5090 self.follower_states.contains_key(&id.into())
5091 }
5092
5093 fn active_item_path_changed(
5094 &mut self,
5095 focus_changed: bool,
5096 window: &mut Window,
5097 cx: &mut Context<Self>,
5098 ) {
5099 cx.emit(Event::ActiveItemChanged);
5100 let active_entry = self.active_project_path(cx);
5101 self.project.update(cx, |project, cx| {
5102 project.set_active_path(active_entry.clone(), cx)
5103 });
5104
5105 if focus_changed && let Some(project_path) = &active_entry {
5106 let git_store_entity = self.project.read(cx).git_store().clone();
5107 git_store_entity.update(cx, |git_store, cx| {
5108 git_store.set_active_repo_for_path(project_path, cx);
5109 });
5110 }
5111
5112 self.update_window_title(window, cx);
5113 }
5114
5115 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5116 let project = self.project().read(cx);
5117 let mut title = String::new();
5118
5119 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5120 let name = {
5121 let settings_location = SettingsLocation {
5122 worktree_id: worktree.read(cx).id(),
5123 path: RelPath::empty(),
5124 };
5125
5126 let settings = WorktreeSettings::get(Some(settings_location), cx);
5127 match &settings.project_name {
5128 Some(name) => name.as_str(),
5129 None => worktree.read(cx).root_name_str(),
5130 }
5131 };
5132 if i > 0 {
5133 title.push_str(", ");
5134 }
5135 title.push_str(name);
5136 }
5137
5138 if title.is_empty() {
5139 title = "empty project".to_string();
5140 }
5141
5142 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5143 let filename = path.path.file_name().or_else(|| {
5144 Some(
5145 project
5146 .worktree_for_id(path.worktree_id, cx)?
5147 .read(cx)
5148 .root_name_str(),
5149 )
5150 });
5151
5152 if let Some(filename) = filename {
5153 title.push_str(" — ");
5154 title.push_str(filename.as_ref());
5155 }
5156 }
5157
5158 if project.is_via_collab() {
5159 title.push_str(" ↙");
5160 } else if project.is_shared() {
5161 title.push_str(" ↗");
5162 }
5163
5164 if let Some(last_title) = self.last_window_title.as_ref()
5165 && &title == last_title
5166 {
5167 return;
5168 }
5169 window.set_window_title(&title);
5170 SystemWindowTabController::update_tab_title(
5171 cx,
5172 window.window_handle().window_id(),
5173 SharedString::from(&title),
5174 );
5175 self.last_window_title = Some(title);
5176 }
5177
5178 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5179 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5180 if is_edited != self.window_edited {
5181 self.window_edited = is_edited;
5182 window.set_window_edited(self.window_edited)
5183 }
5184 }
5185
5186 fn update_item_dirty_state(
5187 &mut self,
5188 item: &dyn ItemHandle,
5189 window: &mut Window,
5190 cx: &mut App,
5191 ) {
5192 let is_dirty = item.is_dirty(cx);
5193 let item_id = item.item_id();
5194 let was_dirty = self.dirty_items.contains_key(&item_id);
5195 if is_dirty == was_dirty {
5196 return;
5197 }
5198 if was_dirty {
5199 self.dirty_items.remove(&item_id);
5200 self.update_window_edited(window, cx);
5201 return;
5202 }
5203
5204 let workspace = self.weak_handle();
5205 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5206 return;
5207 };
5208 let on_release_callback = Box::new(move |cx: &mut App| {
5209 window_handle
5210 .update(cx, |_, window, cx| {
5211 workspace
5212 .update(cx, |workspace, cx| {
5213 workspace.dirty_items.remove(&item_id);
5214 workspace.update_window_edited(window, cx)
5215 })
5216 .ok();
5217 })
5218 .ok();
5219 });
5220
5221 let s = item.on_release(cx, on_release_callback);
5222 self.dirty_items.insert(item_id, s);
5223 self.update_window_edited(window, cx);
5224 }
5225
5226 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5227 if self.notifications.is_empty() {
5228 None
5229 } else {
5230 Some(
5231 div()
5232 .absolute()
5233 .right_3()
5234 .bottom_3()
5235 .w_112()
5236 .h_full()
5237 .flex()
5238 .flex_col()
5239 .justify_end()
5240 .gap_2()
5241 .children(
5242 self.notifications
5243 .iter()
5244 .map(|(_, notification)| notification.clone().into_any()),
5245 ),
5246 )
5247 }
5248 }
5249
5250 // RPC handlers
5251
5252 fn active_view_for_follower(
5253 &self,
5254 follower_project_id: Option<u64>,
5255 window: &mut Window,
5256 cx: &mut Context<Self>,
5257 ) -> Option<proto::View> {
5258 let (item, panel_id) = self.active_item_for_followers(window, cx);
5259 let item = item?;
5260 let leader_id = self
5261 .pane_for(&*item)
5262 .and_then(|pane| self.leader_for_pane(&pane));
5263 let leader_peer_id = match leader_id {
5264 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5265 Some(CollaboratorId::Agent) | None => None,
5266 };
5267
5268 let item_handle = item.to_followable_item_handle(cx)?;
5269 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5270 let variant = item_handle.to_state_proto(window, cx)?;
5271
5272 if item_handle.is_project_item(window, cx)
5273 && (follower_project_id.is_none()
5274 || follower_project_id != self.project.read(cx).remote_id())
5275 {
5276 return None;
5277 }
5278
5279 Some(proto::View {
5280 id: id.to_proto(),
5281 leader_id: leader_peer_id,
5282 variant: Some(variant),
5283 panel_id: panel_id.map(|id| id as i32),
5284 })
5285 }
5286
5287 fn handle_follow(
5288 &mut self,
5289 follower_project_id: Option<u64>,
5290 window: &mut Window,
5291 cx: &mut Context<Self>,
5292 ) -> proto::FollowResponse {
5293 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5294
5295 cx.notify();
5296 proto::FollowResponse {
5297 views: active_view.iter().cloned().collect(),
5298 active_view,
5299 }
5300 }
5301
5302 fn handle_update_followers(
5303 &mut self,
5304 leader_id: PeerId,
5305 message: proto::UpdateFollowers,
5306 _window: &mut Window,
5307 _cx: &mut Context<Self>,
5308 ) {
5309 self.leader_updates_tx
5310 .unbounded_send((leader_id, message))
5311 .ok();
5312 }
5313
5314 async fn process_leader_update(
5315 this: &WeakEntity<Self>,
5316 leader_id: PeerId,
5317 update: proto::UpdateFollowers,
5318 cx: &mut AsyncWindowContext,
5319 ) -> Result<()> {
5320 match update.variant.context("invalid update")? {
5321 proto::update_followers::Variant::CreateView(view) => {
5322 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5323 let should_add_view = this.update(cx, |this, _| {
5324 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5325 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5326 } else {
5327 anyhow::Ok(false)
5328 }
5329 })??;
5330
5331 if should_add_view {
5332 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5333 }
5334 }
5335 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5336 let should_add_view = this.update(cx, |this, _| {
5337 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5338 state.active_view_id = update_active_view
5339 .view
5340 .as_ref()
5341 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5342
5343 if state.active_view_id.is_some_and(|view_id| {
5344 !state.items_by_leader_view_id.contains_key(&view_id)
5345 }) {
5346 anyhow::Ok(true)
5347 } else {
5348 anyhow::Ok(false)
5349 }
5350 } else {
5351 anyhow::Ok(false)
5352 }
5353 })??;
5354
5355 if should_add_view && let Some(view) = update_active_view.view {
5356 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5357 }
5358 }
5359 proto::update_followers::Variant::UpdateView(update_view) => {
5360 let variant = update_view.variant.context("missing update view variant")?;
5361 let id = update_view.id.context("missing update view id")?;
5362 let mut tasks = Vec::new();
5363 this.update_in(cx, |this, window, cx| {
5364 let project = this.project.clone();
5365 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5366 let view_id = ViewId::from_proto(id.clone())?;
5367 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5368 tasks.push(item.view.apply_update_proto(
5369 &project,
5370 variant.clone(),
5371 window,
5372 cx,
5373 ));
5374 }
5375 }
5376 anyhow::Ok(())
5377 })??;
5378 try_join_all(tasks).await.log_err();
5379 }
5380 }
5381 this.update_in(cx, |this, window, cx| {
5382 this.leader_updated(leader_id, window, cx)
5383 })?;
5384 Ok(())
5385 }
5386
5387 async fn add_view_from_leader(
5388 this: WeakEntity<Self>,
5389 leader_id: PeerId,
5390 view: &proto::View,
5391 cx: &mut AsyncWindowContext,
5392 ) -> Result<()> {
5393 let this = this.upgrade().context("workspace dropped")?;
5394
5395 let Some(id) = view.id.clone() else {
5396 anyhow::bail!("no id for view");
5397 };
5398 let id = ViewId::from_proto(id)?;
5399 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5400
5401 let pane = this.update(cx, |this, _cx| {
5402 let state = this
5403 .follower_states
5404 .get(&leader_id.into())
5405 .context("stopped following")?;
5406 anyhow::Ok(state.pane().clone())
5407 })?;
5408 let existing_item = pane.update_in(cx, |pane, window, cx| {
5409 let client = this.read(cx).client().clone();
5410 pane.items().find_map(|item| {
5411 let item = item.to_followable_item_handle(cx)?;
5412 if item.remote_id(&client, window, cx) == Some(id) {
5413 Some(item)
5414 } else {
5415 None
5416 }
5417 })
5418 })?;
5419 let item = if let Some(existing_item) = existing_item {
5420 existing_item
5421 } else {
5422 let variant = view.variant.clone();
5423 anyhow::ensure!(variant.is_some(), "missing view variant");
5424
5425 let task = cx.update(|window, cx| {
5426 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5427 })?;
5428
5429 let Some(task) = task else {
5430 anyhow::bail!(
5431 "failed to construct view from leader (maybe from a different version of zed?)"
5432 );
5433 };
5434
5435 let mut new_item = task.await?;
5436 pane.update_in(cx, |pane, window, cx| {
5437 let mut item_to_remove = None;
5438 for (ix, item) in pane.items().enumerate() {
5439 if let Some(item) = item.to_followable_item_handle(cx) {
5440 match new_item.dedup(item.as_ref(), window, cx) {
5441 Some(item::Dedup::KeepExisting) => {
5442 new_item =
5443 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5444 break;
5445 }
5446 Some(item::Dedup::ReplaceExisting) => {
5447 item_to_remove = Some((ix, item.item_id()));
5448 break;
5449 }
5450 None => {}
5451 }
5452 }
5453 }
5454
5455 if let Some((ix, id)) = item_to_remove {
5456 pane.remove_item(id, false, false, window, cx);
5457 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5458 }
5459 })?;
5460
5461 new_item
5462 };
5463
5464 this.update_in(cx, |this, window, cx| {
5465 let state = this.follower_states.get_mut(&leader_id.into())?;
5466 item.set_leader_id(Some(leader_id.into()), window, cx);
5467 state.items_by_leader_view_id.insert(
5468 id,
5469 FollowerView {
5470 view: item,
5471 location: panel_id,
5472 },
5473 );
5474
5475 Some(())
5476 })
5477 .context("no follower state")?;
5478
5479 Ok(())
5480 }
5481
5482 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5483 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5484 return;
5485 };
5486
5487 if let Some(agent_location) = self.project.read(cx).agent_location() {
5488 let buffer_entity_id = agent_location.buffer.entity_id();
5489 let view_id = ViewId {
5490 creator: CollaboratorId::Agent,
5491 id: buffer_entity_id.as_u64(),
5492 };
5493 follower_state.active_view_id = Some(view_id);
5494
5495 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5496 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5497 hash_map::Entry::Vacant(entry) => {
5498 let existing_view =
5499 follower_state
5500 .center_pane
5501 .read(cx)
5502 .items()
5503 .find_map(|item| {
5504 let item = item.to_followable_item_handle(cx)?;
5505 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5506 && item.project_item_model_ids(cx).as_slice()
5507 == [buffer_entity_id]
5508 {
5509 Some(item)
5510 } else {
5511 None
5512 }
5513 });
5514 let view = existing_view.or_else(|| {
5515 agent_location.buffer.upgrade().and_then(|buffer| {
5516 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
5517 registry.build_item(buffer, self.project.clone(), None, window, cx)
5518 })?
5519 .to_followable_item_handle(cx)
5520 })
5521 });
5522
5523 view.map(|view| {
5524 entry.insert(FollowerView {
5525 view,
5526 location: None,
5527 })
5528 })
5529 }
5530 };
5531
5532 if let Some(item) = item {
5533 item.view
5534 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
5535 item.view
5536 .update_agent_location(agent_location.position, window, cx);
5537 }
5538 } else {
5539 follower_state.active_view_id = None;
5540 }
5541
5542 self.leader_updated(CollaboratorId::Agent, window, cx);
5543 }
5544
5545 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
5546 let mut is_project_item = true;
5547 let mut update = proto::UpdateActiveView::default();
5548 if window.is_window_active() {
5549 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
5550
5551 if let Some(item) = active_item
5552 && item.item_focus_handle(cx).contains_focused(window, cx)
5553 {
5554 let leader_id = self
5555 .pane_for(&*item)
5556 .and_then(|pane| self.leader_for_pane(&pane));
5557 let leader_peer_id = match leader_id {
5558 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5559 Some(CollaboratorId::Agent) | None => None,
5560 };
5561
5562 if let Some(item) = item.to_followable_item_handle(cx) {
5563 let id = item
5564 .remote_id(&self.app_state.client, window, cx)
5565 .map(|id| id.to_proto());
5566
5567 if let Some(id) = id
5568 && let Some(variant) = item.to_state_proto(window, cx)
5569 {
5570 let view = Some(proto::View {
5571 id,
5572 leader_id: leader_peer_id,
5573 variant: Some(variant),
5574 panel_id: panel_id.map(|id| id as i32),
5575 });
5576
5577 is_project_item = item.is_project_item(window, cx);
5578 update = proto::UpdateActiveView { view };
5579 };
5580 }
5581 }
5582 }
5583
5584 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
5585 if active_view_id != self.last_active_view_id.as_ref() {
5586 self.last_active_view_id = active_view_id.cloned();
5587 self.update_followers(
5588 is_project_item,
5589 proto::update_followers::Variant::UpdateActiveView(update),
5590 window,
5591 cx,
5592 );
5593 }
5594 }
5595
5596 fn active_item_for_followers(
5597 &self,
5598 window: &mut Window,
5599 cx: &mut App,
5600 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
5601 let mut active_item = None;
5602 let mut panel_id = None;
5603 for dock in self.all_docks() {
5604 if dock.focus_handle(cx).contains_focused(window, cx)
5605 && let Some(panel) = dock.read(cx).active_panel()
5606 && let Some(pane) = panel.pane(cx)
5607 && let Some(item) = pane.read(cx).active_item()
5608 {
5609 active_item = Some(item);
5610 panel_id = panel.remote_id();
5611 break;
5612 }
5613 }
5614
5615 if active_item.is_none() {
5616 active_item = self.active_pane().read(cx).active_item();
5617 }
5618 (active_item, panel_id)
5619 }
5620
5621 fn update_followers(
5622 &self,
5623 project_only: bool,
5624 update: proto::update_followers::Variant,
5625 _: &mut Window,
5626 cx: &mut App,
5627 ) -> Option<()> {
5628 // If this update only applies to for followers in the current project,
5629 // then skip it unless this project is shared. If it applies to all
5630 // followers, regardless of project, then set `project_id` to none,
5631 // indicating that it goes to all followers.
5632 let project_id = if project_only {
5633 Some(self.project.read(cx).remote_id()?)
5634 } else {
5635 None
5636 };
5637 self.app_state().workspace_store.update(cx, |store, cx| {
5638 store.update_followers(project_id, update, cx)
5639 })
5640 }
5641
5642 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
5643 self.follower_states.iter().find_map(|(leader_id, state)| {
5644 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
5645 Some(*leader_id)
5646 } else {
5647 None
5648 }
5649 })
5650 }
5651
5652 fn leader_updated(
5653 &mut self,
5654 leader_id: impl Into<CollaboratorId>,
5655 window: &mut Window,
5656 cx: &mut Context<Self>,
5657 ) -> Option<Box<dyn ItemHandle>> {
5658 cx.notify();
5659
5660 let leader_id = leader_id.into();
5661 let (panel_id, item) = match leader_id {
5662 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
5663 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
5664 };
5665
5666 let state = self.follower_states.get(&leader_id)?;
5667 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
5668 let pane;
5669 if let Some(panel_id) = panel_id {
5670 pane = self
5671 .activate_panel_for_proto_id(panel_id, window, cx)?
5672 .pane(cx)?;
5673 let state = self.follower_states.get_mut(&leader_id)?;
5674 state.dock_pane = Some(pane.clone());
5675 } else {
5676 pane = state.center_pane.clone();
5677 let state = self.follower_states.get_mut(&leader_id)?;
5678 if let Some(dock_pane) = state.dock_pane.take() {
5679 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
5680 }
5681 }
5682
5683 pane.update(cx, |pane, cx| {
5684 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
5685 if let Some(index) = pane.index_for_item(item.as_ref()) {
5686 pane.activate_item(index, false, false, window, cx);
5687 } else {
5688 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
5689 }
5690
5691 if focus_active_item {
5692 pane.focus_active_item(window, cx)
5693 }
5694 });
5695
5696 Some(item)
5697 }
5698
5699 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
5700 let state = self.follower_states.get(&CollaboratorId::Agent)?;
5701 let active_view_id = state.active_view_id?;
5702 Some(
5703 state
5704 .items_by_leader_view_id
5705 .get(&active_view_id)?
5706 .view
5707 .boxed_clone(),
5708 )
5709 }
5710
5711 fn active_item_for_peer(
5712 &self,
5713 peer_id: PeerId,
5714 window: &mut Window,
5715 cx: &mut Context<Self>,
5716 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
5717 let call = self.active_call()?;
5718 let room = call.read(cx).room()?.read(cx);
5719 let participant = room.remote_participant_for_peer_id(peer_id)?;
5720 let leader_in_this_app;
5721 let leader_in_this_project;
5722 match participant.location {
5723 call::ParticipantLocation::SharedProject { project_id } => {
5724 leader_in_this_app = true;
5725 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
5726 }
5727 call::ParticipantLocation::UnsharedProject => {
5728 leader_in_this_app = true;
5729 leader_in_this_project = false;
5730 }
5731 call::ParticipantLocation::External => {
5732 leader_in_this_app = false;
5733 leader_in_this_project = false;
5734 }
5735 };
5736 let state = self.follower_states.get(&peer_id.into())?;
5737 let mut item_to_activate = None;
5738 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
5739 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
5740 && (leader_in_this_project || !item.view.is_project_item(window, cx))
5741 {
5742 item_to_activate = Some((item.location, item.view.boxed_clone()));
5743 }
5744 } else if let Some(shared_screen) =
5745 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
5746 {
5747 item_to_activate = Some((None, Box::new(shared_screen)));
5748 }
5749 item_to_activate
5750 }
5751
5752 fn shared_screen_for_peer(
5753 &self,
5754 peer_id: PeerId,
5755 pane: &Entity<Pane>,
5756 window: &mut Window,
5757 cx: &mut App,
5758 ) -> Option<Entity<SharedScreen>> {
5759 let call = self.active_call()?;
5760 let room = call.read(cx).room()?.clone();
5761 let participant = room.read(cx).remote_participant_for_peer_id(peer_id)?;
5762 let track = participant.video_tracks.values().next()?.clone();
5763 let user = participant.user.clone();
5764
5765 for item in pane.read(cx).items_of_type::<SharedScreen>() {
5766 if item.read(cx).peer_id == peer_id {
5767 return Some(item);
5768 }
5769 }
5770
5771 Some(cx.new(|cx| SharedScreen::new(track, peer_id, user.clone(), room.clone(), window, cx)))
5772 }
5773
5774 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5775 if window.is_window_active() {
5776 self.update_active_view_for_followers(window, cx);
5777
5778 if let Some(database_id) = self.database_id {
5779 cx.background_spawn(persistence::DB.update_timestamp(database_id))
5780 .detach();
5781 }
5782 } else {
5783 for pane in &self.panes {
5784 pane.update(cx, |pane, cx| {
5785 if let Some(item) = pane.active_item() {
5786 item.workspace_deactivated(window, cx);
5787 }
5788 for item in pane.items() {
5789 if matches!(
5790 item.workspace_settings(cx).autosave,
5791 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
5792 ) {
5793 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
5794 .detach_and_log_err(cx);
5795 }
5796 }
5797 });
5798 }
5799 }
5800 }
5801
5802 pub fn active_call(&self) -> Option<&Entity<ActiveCall>> {
5803 self.active_call.as_ref().map(|(call, _)| call)
5804 }
5805
5806 fn on_active_call_event(
5807 &mut self,
5808 _: &Entity<ActiveCall>,
5809 event: &call::room::Event,
5810 window: &mut Window,
5811 cx: &mut Context<Self>,
5812 ) {
5813 match event {
5814 call::room::Event::ParticipantLocationChanged { participant_id }
5815 | call::room::Event::RemoteVideoTracksChanged { participant_id } => {
5816 self.leader_updated(participant_id, window, cx);
5817 }
5818 _ => {}
5819 }
5820 }
5821
5822 pub fn database_id(&self) -> Option<WorkspaceId> {
5823 self.database_id
5824 }
5825
5826 pub fn session_id(&self) -> Option<String> {
5827 self.session_id.clone()
5828 }
5829
5830 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
5831 let project = self.project().read(cx);
5832 project
5833 .visible_worktrees(cx)
5834 .map(|worktree| worktree.read(cx).abs_path())
5835 .collect::<Vec<_>>()
5836 }
5837
5838 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
5839 match member {
5840 Member::Axis(PaneAxis { members, .. }) => {
5841 for child in members.iter() {
5842 self.remove_panes(child.clone(), window, cx)
5843 }
5844 }
5845 Member::Pane(pane) => {
5846 self.force_remove_pane(&pane, &None, window, cx);
5847 }
5848 }
5849 }
5850
5851 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
5852 self.session_id.take();
5853 self.serialize_workspace_internal(window, cx)
5854 }
5855
5856 fn force_remove_pane(
5857 &mut self,
5858 pane: &Entity<Pane>,
5859 focus_on: &Option<Entity<Pane>>,
5860 window: &mut Window,
5861 cx: &mut Context<Workspace>,
5862 ) {
5863 self.panes.retain(|p| p != pane);
5864 if let Some(focus_on) = focus_on {
5865 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
5866 } else if self.active_pane() == pane {
5867 self.panes
5868 .last()
5869 .unwrap()
5870 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
5871 }
5872 if self.last_active_center_pane == Some(pane.downgrade()) {
5873 self.last_active_center_pane = None;
5874 }
5875 cx.notify();
5876 }
5877
5878 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5879 if self._schedule_serialize_workspace.is_none() {
5880 self._schedule_serialize_workspace =
5881 Some(cx.spawn_in(window, async move |this, cx| {
5882 cx.background_executor()
5883 .timer(SERIALIZATION_THROTTLE_TIME)
5884 .await;
5885 this.update_in(cx, |this, window, cx| {
5886 this.serialize_workspace_internal(window, cx).detach();
5887 this._schedule_serialize_workspace.take();
5888 })
5889 .log_err();
5890 }));
5891 }
5892 }
5893
5894 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
5895 let Some(database_id) = self.database_id() else {
5896 return Task::ready(());
5897 };
5898
5899 fn serialize_pane_handle(
5900 pane_handle: &Entity<Pane>,
5901 window: &mut Window,
5902 cx: &mut App,
5903 ) -> SerializedPane {
5904 let (items, active, pinned_count) = {
5905 let pane = pane_handle.read(cx);
5906 let active_item_id = pane.active_item().map(|item| item.item_id());
5907 (
5908 pane.items()
5909 .filter_map(|handle| {
5910 let handle = handle.to_serializable_item_handle(cx)?;
5911
5912 Some(SerializedItem {
5913 kind: Arc::from(handle.serialized_item_kind()),
5914 item_id: handle.item_id().as_u64(),
5915 active: Some(handle.item_id()) == active_item_id,
5916 preview: pane.is_active_preview_item(handle.item_id()),
5917 })
5918 })
5919 .collect::<Vec<_>>(),
5920 pane.has_focus(window, cx),
5921 pane.pinned_count(),
5922 )
5923 };
5924
5925 SerializedPane::new(items, active, pinned_count)
5926 }
5927
5928 fn build_serialized_pane_group(
5929 pane_group: &Member,
5930 window: &mut Window,
5931 cx: &mut App,
5932 ) -> SerializedPaneGroup {
5933 match pane_group {
5934 Member::Axis(PaneAxis {
5935 axis,
5936 members,
5937 flexes,
5938 bounding_boxes: _,
5939 }) => SerializedPaneGroup::Group {
5940 axis: SerializedAxis(*axis),
5941 children: members
5942 .iter()
5943 .map(|member| build_serialized_pane_group(member, window, cx))
5944 .collect::<Vec<_>>(),
5945 flexes: Some(flexes.lock().clone()),
5946 },
5947 Member::Pane(pane_handle) => {
5948 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
5949 }
5950 }
5951 }
5952
5953 fn build_serialized_docks(
5954 this: &Workspace,
5955 window: &mut Window,
5956 cx: &mut App,
5957 ) -> DockStructure {
5958 let left_dock = this.left_dock.read(cx);
5959 let left_visible = left_dock.is_open();
5960 let left_active_panel = left_dock
5961 .active_panel()
5962 .map(|panel| panel.persistent_name().to_string());
5963 let left_dock_zoom = left_dock
5964 .active_panel()
5965 .map(|panel| panel.is_zoomed(window, cx))
5966 .unwrap_or(false);
5967
5968 let right_dock = this.right_dock.read(cx);
5969 let right_visible = right_dock.is_open();
5970 let right_active_panel = right_dock
5971 .active_panel()
5972 .map(|panel| panel.persistent_name().to_string());
5973 let right_dock_zoom = right_dock
5974 .active_panel()
5975 .map(|panel| panel.is_zoomed(window, cx))
5976 .unwrap_or(false);
5977
5978 let bottom_dock = this.bottom_dock.read(cx);
5979 let bottom_visible = bottom_dock.is_open();
5980 let bottom_active_panel = bottom_dock
5981 .active_panel()
5982 .map(|panel| panel.persistent_name().to_string());
5983 let bottom_dock_zoom = bottom_dock
5984 .active_panel()
5985 .map(|panel| panel.is_zoomed(window, cx))
5986 .unwrap_or(false);
5987
5988 DockStructure {
5989 left: DockData {
5990 visible: left_visible,
5991 active_panel: left_active_panel,
5992 zoom: left_dock_zoom,
5993 },
5994 right: DockData {
5995 visible: right_visible,
5996 active_panel: right_active_panel,
5997 zoom: right_dock_zoom,
5998 },
5999 bottom: DockData {
6000 visible: bottom_visible,
6001 active_panel: bottom_active_panel,
6002 zoom: bottom_dock_zoom,
6003 },
6004 }
6005 }
6006
6007 match self.workspace_location(cx) {
6008 WorkspaceLocation::Location(location, paths) => {
6009 let breakpoints = self.project.update(cx, |project, cx| {
6010 project
6011 .breakpoint_store()
6012 .read(cx)
6013 .all_source_breakpoints(cx)
6014 });
6015 let user_toolchains = self
6016 .project
6017 .read(cx)
6018 .user_toolchains(cx)
6019 .unwrap_or_default();
6020
6021 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6022 let docks = build_serialized_docks(self, window, cx);
6023 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6024
6025 let serialized_workspace = SerializedWorkspace {
6026 id: database_id,
6027 location,
6028 paths,
6029 center_group,
6030 window_bounds,
6031 display: Default::default(),
6032 docks,
6033 centered_layout: self.centered_layout,
6034 session_id: self.session_id.clone(),
6035 breakpoints,
6036 window_id: Some(window.window_handle().window_id().as_u64()),
6037 user_toolchains,
6038 };
6039
6040 window.spawn(cx, async move |_| {
6041 persistence::DB.save_workspace(serialized_workspace).await;
6042 })
6043 }
6044 WorkspaceLocation::DetachFromSession => {
6045 let window_bounds = SerializedWindowBounds(window.window_bounds());
6046 let display = window.display(cx).and_then(|d| d.uuid().ok());
6047 // Save dock state for empty local workspaces
6048 let docks = build_serialized_docks(self, window, cx);
6049 window.spawn(cx, async move |_| {
6050 persistence::DB
6051 .set_window_open_status(
6052 database_id,
6053 window_bounds,
6054 display.unwrap_or_default(),
6055 )
6056 .await
6057 .log_err();
6058 persistence::DB
6059 .set_session_id(database_id, None)
6060 .await
6061 .log_err();
6062 persistence::write_default_dock_state(docks).await.log_err();
6063 })
6064 }
6065 WorkspaceLocation::None => {
6066 // Save dock state for empty non-local workspaces
6067 let docks = build_serialized_docks(self, window, cx);
6068 window.spawn(cx, async move |_| {
6069 persistence::write_default_dock_state(docks).await.log_err();
6070 })
6071 }
6072 }
6073 }
6074
6075 fn has_any_items_open(&self, cx: &App) -> bool {
6076 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6077 }
6078
6079 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6080 let paths = PathList::new(&self.root_paths(cx));
6081 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6082 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6083 } else if self.project.read(cx).is_local() {
6084 if !paths.is_empty() || self.has_any_items_open(cx) {
6085 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6086 } else {
6087 WorkspaceLocation::DetachFromSession
6088 }
6089 } else {
6090 WorkspaceLocation::None
6091 }
6092 }
6093
6094 fn update_history(&self, cx: &mut App) {
6095 let Some(id) = self.database_id() else {
6096 return;
6097 };
6098 if !self.project.read(cx).is_local() {
6099 return;
6100 }
6101 if let Some(manager) = HistoryManager::global(cx) {
6102 let paths = PathList::new(&self.root_paths(cx));
6103 manager.update(cx, |this, cx| {
6104 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6105 });
6106 }
6107 }
6108
6109 async fn serialize_items(
6110 this: &WeakEntity<Self>,
6111 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6112 cx: &mut AsyncWindowContext,
6113 ) -> Result<()> {
6114 const CHUNK_SIZE: usize = 200;
6115
6116 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6117
6118 while let Some(items_received) = serializable_items.next().await {
6119 let unique_items =
6120 items_received
6121 .into_iter()
6122 .fold(HashMap::default(), |mut acc, item| {
6123 acc.entry(item.item_id()).or_insert(item);
6124 acc
6125 });
6126
6127 // We use into_iter() here so that the references to the items are moved into
6128 // the tasks and not kept alive while we're sleeping.
6129 for (_, item) in unique_items.into_iter() {
6130 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6131 item.serialize(workspace, false, window, cx)
6132 }) {
6133 cx.background_spawn(async move { task.await.log_err() })
6134 .detach();
6135 }
6136 }
6137
6138 cx.background_executor()
6139 .timer(SERIALIZATION_THROTTLE_TIME)
6140 .await;
6141 }
6142
6143 Ok(())
6144 }
6145
6146 pub(crate) fn enqueue_item_serialization(
6147 &mut self,
6148 item: Box<dyn SerializableItemHandle>,
6149 ) -> Result<()> {
6150 self.serializable_items_tx
6151 .unbounded_send(item)
6152 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6153 }
6154
6155 pub(crate) fn load_workspace(
6156 serialized_workspace: SerializedWorkspace,
6157 paths_to_open: Vec<Option<ProjectPath>>,
6158 window: &mut Window,
6159 cx: &mut Context<Workspace>,
6160 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6161 cx.spawn_in(window, async move |workspace, cx| {
6162 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6163
6164 let mut center_group = None;
6165 let mut center_items = None;
6166
6167 // Traverse the splits tree and add to things
6168 if let Some((group, active_pane, items)) = serialized_workspace
6169 .center_group
6170 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6171 .await
6172 {
6173 center_items = Some(items);
6174 center_group = Some((group, active_pane))
6175 }
6176
6177 let mut items_by_project_path = HashMap::default();
6178 let mut item_ids_by_kind = HashMap::default();
6179 let mut all_deserialized_items = Vec::default();
6180 cx.update(|_, cx| {
6181 for item in center_items.unwrap_or_default().into_iter().flatten() {
6182 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6183 item_ids_by_kind
6184 .entry(serializable_item_handle.serialized_item_kind())
6185 .or_insert(Vec::new())
6186 .push(item.item_id().as_u64() as ItemId);
6187 }
6188
6189 if let Some(project_path) = item.project_path(cx) {
6190 items_by_project_path.insert(project_path, item.clone());
6191 }
6192 all_deserialized_items.push(item);
6193 }
6194 })?;
6195
6196 let opened_items = paths_to_open
6197 .into_iter()
6198 .map(|path_to_open| {
6199 path_to_open
6200 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6201 })
6202 .collect::<Vec<_>>();
6203
6204 // Remove old panes from workspace panes list
6205 workspace.update_in(cx, |workspace, window, cx| {
6206 if let Some((center_group, active_pane)) = center_group {
6207 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6208
6209 // Swap workspace center group
6210 workspace.center = PaneGroup::with_root(center_group);
6211 workspace.center.set_is_center(true);
6212 workspace.center.mark_positions(cx);
6213
6214 if let Some(active_pane) = active_pane {
6215 workspace.set_active_pane(&active_pane, window, cx);
6216 cx.focus_self(window);
6217 } else {
6218 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6219 }
6220 }
6221
6222 let docks = serialized_workspace.docks;
6223
6224 for (dock, serialized_dock) in [
6225 (&mut workspace.right_dock, docks.right),
6226 (&mut workspace.left_dock, docks.left),
6227 (&mut workspace.bottom_dock, docks.bottom),
6228 ]
6229 .iter_mut()
6230 {
6231 dock.update(cx, |dock, cx| {
6232 dock.serialized_dock = Some(serialized_dock.clone());
6233 dock.restore_state(window, cx);
6234 });
6235 }
6236
6237 cx.notify();
6238 })?;
6239
6240 let _ = project
6241 .update(cx, |project, cx| {
6242 project
6243 .breakpoint_store()
6244 .update(cx, |breakpoint_store, cx| {
6245 breakpoint_store
6246 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6247 })
6248 })
6249 .await;
6250
6251 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6252 // after loading the items, we might have different items and in order to avoid
6253 // the database filling up, we delete items that haven't been loaded now.
6254 //
6255 // The items that have been loaded, have been saved after they've been added to the workspace.
6256 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6257 item_ids_by_kind
6258 .into_iter()
6259 .map(|(item_kind, loaded_items)| {
6260 SerializableItemRegistry::cleanup(
6261 item_kind,
6262 serialized_workspace.id,
6263 loaded_items,
6264 window,
6265 cx,
6266 )
6267 .log_err()
6268 })
6269 .collect::<Vec<_>>()
6270 })?;
6271
6272 futures::future::join_all(clean_up_tasks).await;
6273
6274 workspace
6275 .update_in(cx, |workspace, window, cx| {
6276 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6277 workspace.serialize_workspace_internal(window, cx).detach();
6278
6279 // Ensure that we mark the window as edited if we did load dirty items
6280 workspace.update_window_edited(window, cx);
6281 })
6282 .ok();
6283
6284 Ok(opened_items)
6285 })
6286 }
6287
6288 fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6289 self.add_workspace_actions_listeners(div, window, cx)
6290 .on_action(cx.listener(
6291 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6292 for action in &action_sequence.0 {
6293 window.dispatch_action(action.boxed_clone(), cx);
6294 }
6295 },
6296 ))
6297 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6298 .on_action(cx.listener(Self::close_all_items_and_panes))
6299 .on_action(cx.listener(Self::close_item_in_all_panes))
6300 .on_action(cx.listener(Self::save_all))
6301 .on_action(cx.listener(Self::send_keystrokes))
6302 .on_action(cx.listener(Self::add_folder_to_project))
6303 .on_action(cx.listener(Self::follow_next_collaborator))
6304 .on_action(cx.listener(Self::close_window))
6305 .on_action(cx.listener(Self::activate_pane_at_index))
6306 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6307 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6308 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6309 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6310 let pane = workspace.active_pane().clone();
6311 workspace.unfollow_in_pane(&pane, window, cx);
6312 }))
6313 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6314 workspace
6315 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6316 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6317 }))
6318 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6319 workspace
6320 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6321 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6322 }))
6323 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6324 workspace
6325 .save_active_item(SaveIntent::SaveAs, window, cx)
6326 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6327 }))
6328 .on_action(
6329 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6330 workspace.activate_previous_pane(window, cx)
6331 }),
6332 )
6333 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6334 workspace.activate_next_pane(window, cx)
6335 }))
6336 .on_action(
6337 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6338 workspace.activate_next_window(cx)
6339 }),
6340 )
6341 .on_action(
6342 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6343 workspace.activate_previous_window(cx)
6344 }),
6345 )
6346 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6347 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6348 }))
6349 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6350 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6351 }))
6352 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6353 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6354 }))
6355 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6356 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6357 }))
6358 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6359 workspace.activate_next_pane(window, cx)
6360 }))
6361 .on_action(cx.listener(
6362 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6363 workspace.move_item_to_pane_in_direction(action, window, cx)
6364 },
6365 ))
6366 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6367 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6368 }))
6369 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6370 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6371 }))
6372 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6373 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6374 }))
6375 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6376 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6377 }))
6378 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6379 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6380 SplitDirection::Down,
6381 SplitDirection::Up,
6382 SplitDirection::Right,
6383 SplitDirection::Left,
6384 ];
6385 for dir in DIRECTION_PRIORITY {
6386 if workspace.find_pane_in_direction(dir, cx).is_some() {
6387 workspace.swap_pane_in_direction(dir, cx);
6388 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6389 break;
6390 }
6391 }
6392 }))
6393 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6394 workspace.move_pane_to_border(SplitDirection::Left, cx)
6395 }))
6396 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6397 workspace.move_pane_to_border(SplitDirection::Right, cx)
6398 }))
6399 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6400 workspace.move_pane_to_border(SplitDirection::Up, cx)
6401 }))
6402 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6403 workspace.move_pane_to_border(SplitDirection::Down, cx)
6404 }))
6405 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6406 this.toggle_dock(DockPosition::Left, window, cx);
6407 }))
6408 .on_action(cx.listener(
6409 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6410 workspace.toggle_dock(DockPosition::Right, window, cx);
6411 },
6412 ))
6413 .on_action(cx.listener(
6414 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6415 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6416 },
6417 ))
6418 .on_action(cx.listener(
6419 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6420 if !workspace.close_active_dock(window, cx) {
6421 cx.propagate();
6422 }
6423 },
6424 ))
6425 .on_action(
6426 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6427 workspace.close_all_docks(window, cx);
6428 }),
6429 )
6430 .on_action(cx.listener(Self::toggle_all_docks))
6431 .on_action(cx.listener(
6432 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6433 workspace.clear_all_notifications(cx);
6434 },
6435 ))
6436 .on_action(cx.listener(
6437 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6438 workspace.clear_navigation_history(window, cx);
6439 },
6440 ))
6441 .on_action(cx.listener(
6442 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6443 if let Some((notification_id, _)) = workspace.notifications.pop() {
6444 workspace.suppress_notification(¬ification_id, cx);
6445 }
6446 },
6447 ))
6448 .on_action(cx.listener(
6449 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6450 workspace.show_worktree_trust_security_modal(true, window, cx);
6451 },
6452 ))
6453 .on_action(
6454 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6455 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6456 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6457 trusted_worktrees.clear_trusted_paths()
6458 });
6459 let clear_task = persistence::DB.clear_trusted_worktrees();
6460 cx.spawn(async move |_, cx| {
6461 if clear_task.await.log_err().is_some() {
6462 cx.update(|cx| reload(cx));
6463 }
6464 })
6465 .detach();
6466 }
6467 }),
6468 )
6469 .on_action(cx.listener(
6470 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
6471 workspace.reopen_closed_item(window, cx).detach();
6472 },
6473 ))
6474 .on_action(cx.listener(
6475 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
6476 for dock in workspace.all_docks() {
6477 if dock.focus_handle(cx).contains_focused(window, cx) {
6478 let Some(panel) = dock.read(cx).active_panel() else {
6479 return;
6480 };
6481
6482 // Set to `None`, then the size will fall back to the default.
6483 panel.clone().set_size(None, window, cx);
6484
6485 return;
6486 }
6487 }
6488 },
6489 ))
6490 .on_action(cx.listener(
6491 |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
6492 for dock in workspace.all_docks() {
6493 if let Some(panel) = dock.read(cx).visible_panel() {
6494 // Set to `None`, then the size will fall back to the default.
6495 panel.clone().set_size(None, window, cx);
6496 }
6497 }
6498 },
6499 ))
6500 .on_action(cx.listener(
6501 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
6502 adjust_active_dock_size_by_px(
6503 px_with_ui_font_fallback(act.px, cx),
6504 workspace,
6505 window,
6506 cx,
6507 );
6508 },
6509 ))
6510 .on_action(cx.listener(
6511 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
6512 adjust_active_dock_size_by_px(
6513 px_with_ui_font_fallback(act.px, cx) * -1.,
6514 workspace,
6515 window,
6516 cx,
6517 );
6518 },
6519 ))
6520 .on_action(cx.listener(
6521 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
6522 adjust_open_docks_size_by_px(
6523 px_with_ui_font_fallback(act.px, cx),
6524 workspace,
6525 window,
6526 cx,
6527 );
6528 },
6529 ))
6530 .on_action(cx.listener(
6531 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
6532 adjust_open_docks_size_by_px(
6533 px_with_ui_font_fallback(act.px, cx) * -1.,
6534 workspace,
6535 window,
6536 cx,
6537 );
6538 },
6539 ))
6540 .on_action(cx.listener(Workspace::toggle_centered_layout))
6541 .on_action(cx.listener(
6542 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
6543 if let Some(active_dock) = workspace.active_dock(window, cx) {
6544 let dock = active_dock.read(cx);
6545 if let Some(active_panel) = dock.active_panel() {
6546 if active_panel.pane(cx).is_none() {
6547 let mut recent_pane: Option<Entity<Pane>> = None;
6548 let mut recent_timestamp = 0;
6549 for pane_handle in workspace.panes() {
6550 let pane = pane_handle.read(cx);
6551 for entry in pane.activation_history() {
6552 if entry.timestamp > recent_timestamp {
6553 recent_timestamp = entry.timestamp;
6554 recent_pane = Some(pane_handle.clone());
6555 }
6556 }
6557 }
6558
6559 if let Some(pane) = recent_pane {
6560 pane.update(cx, |pane, cx| {
6561 let current_index = pane.active_item_index();
6562 let items_len = pane.items_len();
6563 if items_len > 0 {
6564 let next_index = if current_index + 1 < items_len {
6565 current_index + 1
6566 } else {
6567 0
6568 };
6569 pane.activate_item(
6570 next_index, false, false, window, cx,
6571 );
6572 }
6573 });
6574 return;
6575 }
6576 }
6577 }
6578 }
6579 cx.propagate();
6580 },
6581 ))
6582 .on_action(cx.listener(
6583 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
6584 if let Some(active_dock) = workspace.active_dock(window, cx) {
6585 let dock = active_dock.read(cx);
6586 if let Some(active_panel) = dock.active_panel() {
6587 if active_panel.pane(cx).is_none() {
6588 let mut recent_pane: Option<Entity<Pane>> = None;
6589 let mut recent_timestamp = 0;
6590 for pane_handle in workspace.panes() {
6591 let pane = pane_handle.read(cx);
6592 for entry in pane.activation_history() {
6593 if entry.timestamp > recent_timestamp {
6594 recent_timestamp = entry.timestamp;
6595 recent_pane = Some(pane_handle.clone());
6596 }
6597 }
6598 }
6599
6600 if let Some(pane) = recent_pane {
6601 pane.update(cx, |pane, cx| {
6602 let current_index = pane.active_item_index();
6603 let items_len = pane.items_len();
6604 if items_len > 0 {
6605 let prev_index = if current_index > 0 {
6606 current_index - 1
6607 } else {
6608 items_len.saturating_sub(1)
6609 };
6610 pane.activate_item(
6611 prev_index, false, false, window, cx,
6612 );
6613 }
6614 });
6615 return;
6616 }
6617 }
6618 }
6619 }
6620 cx.propagate();
6621 },
6622 ))
6623 .on_action(cx.listener(
6624 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
6625 if let Some(active_dock) = workspace.active_dock(window, cx) {
6626 let dock = active_dock.read(cx);
6627 if let Some(active_panel) = dock.active_panel() {
6628 if active_panel.pane(cx).is_none() {
6629 let active_pane = workspace.active_pane().clone();
6630 active_pane.update(cx, |pane, cx| {
6631 pane.close_active_item(action, window, cx)
6632 .detach_and_log_err(cx);
6633 });
6634 return;
6635 }
6636 }
6637 }
6638 cx.propagate();
6639 },
6640 ))
6641 .on_action(
6642 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
6643 let pane = workspace.active_pane().clone();
6644 if let Some(item) = pane.read(cx).active_item() {
6645 item.toggle_read_only(window, cx);
6646 }
6647 }),
6648 )
6649 .on_action(cx.listener(Workspace::cancel))
6650 }
6651
6652 #[cfg(any(test, feature = "test-support"))]
6653 pub fn set_random_database_id(&mut self) {
6654 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
6655 }
6656
6657 #[cfg(any(test, feature = "test-support"))]
6658 pub(crate) fn test_new(
6659 project: Entity<Project>,
6660 window: &mut Window,
6661 cx: &mut Context<Self>,
6662 ) -> Self {
6663 use node_runtime::NodeRuntime;
6664 use session::Session;
6665
6666 let client = project.read(cx).client();
6667 let user_store = project.read(cx).user_store();
6668 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
6669 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
6670 window.activate_window();
6671 let app_state = Arc::new(AppState {
6672 languages: project.read(cx).languages().clone(),
6673 workspace_store,
6674 client,
6675 user_store,
6676 fs: project.read(cx).fs().clone(),
6677 build_window_options: |_, _| Default::default(),
6678 node_runtime: NodeRuntime::unavailable(),
6679 session,
6680 });
6681 let workspace = Self::new(Default::default(), project, app_state, window, cx);
6682 workspace
6683 .active_pane
6684 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6685 workspace
6686 }
6687
6688 pub fn register_action<A: Action>(
6689 &mut self,
6690 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
6691 ) -> &mut Self {
6692 let callback = Arc::new(callback);
6693
6694 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
6695 let callback = callback.clone();
6696 div.on_action(cx.listener(move |workspace, event, window, cx| {
6697 (callback)(workspace, event, window, cx)
6698 }))
6699 }));
6700 self
6701 }
6702 pub fn register_action_renderer(
6703 &mut self,
6704 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
6705 ) -> &mut Self {
6706 self.workspace_actions.push(Box::new(callback));
6707 self
6708 }
6709
6710 fn add_workspace_actions_listeners(
6711 &self,
6712 mut div: Div,
6713 window: &mut Window,
6714 cx: &mut Context<Self>,
6715 ) -> Div {
6716 for action in self.workspace_actions.iter() {
6717 div = (action)(div, self, window, cx)
6718 }
6719 div
6720 }
6721
6722 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
6723 self.modal_layer.read(cx).has_active_modal()
6724 }
6725
6726 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
6727 self.modal_layer.read(cx).active_modal()
6728 }
6729
6730 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
6731 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
6732 /// If no modal is active, the new modal will be shown.
6733 ///
6734 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
6735 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
6736 /// will not be shown.
6737 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
6738 where
6739 B: FnOnce(&mut Window, &mut Context<V>) -> V,
6740 {
6741 self.modal_layer.update(cx, |modal_layer, cx| {
6742 modal_layer.toggle_modal(window, cx, build)
6743 })
6744 }
6745
6746 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
6747 self.modal_layer
6748 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
6749 }
6750
6751 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
6752 self.toast_layer
6753 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
6754 }
6755
6756 pub fn toggle_centered_layout(
6757 &mut self,
6758 _: &ToggleCenteredLayout,
6759 _: &mut Window,
6760 cx: &mut Context<Self>,
6761 ) {
6762 self.centered_layout = !self.centered_layout;
6763 if let Some(database_id) = self.database_id() {
6764 cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
6765 .detach_and_log_err(cx);
6766 }
6767 cx.notify();
6768 }
6769
6770 fn adjust_padding(padding: Option<f32>) -> f32 {
6771 padding
6772 .unwrap_or(CenteredPaddingSettings::default().0)
6773 .clamp(
6774 CenteredPaddingSettings::MIN_PADDING,
6775 CenteredPaddingSettings::MAX_PADDING,
6776 )
6777 }
6778
6779 fn render_dock(
6780 &self,
6781 position: DockPosition,
6782 dock: &Entity<Dock>,
6783 window: &mut Window,
6784 cx: &mut App,
6785 ) -> Option<Div> {
6786 if self.zoomed_position == Some(position) {
6787 return None;
6788 }
6789
6790 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
6791 let pane = panel.pane(cx)?;
6792 let follower_states = &self.follower_states;
6793 leader_border_for_pane(follower_states, &pane, window, cx)
6794 });
6795
6796 Some(
6797 div()
6798 .flex()
6799 .flex_none()
6800 .overflow_hidden()
6801 .child(dock.clone())
6802 .children(leader_border),
6803 )
6804 }
6805
6806 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
6807 window
6808 .root::<MultiWorkspace>()
6809 .flatten()
6810 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
6811 }
6812
6813 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
6814 self.zoomed.as_ref()
6815 }
6816
6817 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
6818 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
6819 return;
6820 };
6821 let windows = cx.windows();
6822 let next_window =
6823 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
6824 || {
6825 windows
6826 .iter()
6827 .cycle()
6828 .skip_while(|window| window.window_id() != current_window_id)
6829 .nth(1)
6830 },
6831 );
6832
6833 if let Some(window) = next_window {
6834 window
6835 .update(cx, |_, window, _| window.activate_window())
6836 .ok();
6837 }
6838 }
6839
6840 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
6841 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
6842 return;
6843 };
6844 let windows = cx.windows();
6845 let prev_window =
6846 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
6847 || {
6848 windows
6849 .iter()
6850 .rev()
6851 .cycle()
6852 .skip_while(|window| window.window_id() != current_window_id)
6853 .nth(1)
6854 },
6855 );
6856
6857 if let Some(window) = prev_window {
6858 window
6859 .update(cx, |_, window, _| window.activate_window())
6860 .ok();
6861 }
6862 }
6863
6864 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
6865 if cx.stop_active_drag(window) {
6866 } else if let Some((notification_id, _)) = self.notifications.pop() {
6867 dismiss_app_notification(¬ification_id, cx);
6868 } else {
6869 cx.propagate();
6870 }
6871 }
6872
6873 fn adjust_dock_size_by_px(
6874 &mut self,
6875 panel_size: Pixels,
6876 dock_pos: DockPosition,
6877 px: Pixels,
6878 window: &mut Window,
6879 cx: &mut Context<Self>,
6880 ) {
6881 match dock_pos {
6882 DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
6883 DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
6884 DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
6885 }
6886 }
6887
6888 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6889 let size = new_size.min(self.bounds.right() - RESIZE_HANDLE_SIZE);
6890
6891 self.left_dock.update(cx, |left_dock, cx| {
6892 if WorkspaceSettings::get_global(cx)
6893 .resize_all_panels_in_dock
6894 .contains(&DockPosition::Left)
6895 {
6896 left_dock.resize_all_panels(Some(size), window, cx);
6897 } else {
6898 left_dock.resize_active_panel(Some(size), window, cx);
6899 }
6900 });
6901 }
6902
6903 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6904 let mut size = new_size.max(self.bounds.left() - RESIZE_HANDLE_SIZE);
6905 self.left_dock.read_with(cx, |left_dock, cx| {
6906 let left_dock_size = left_dock
6907 .active_panel_size(window, cx)
6908 .unwrap_or(Pixels::ZERO);
6909 if left_dock_size + size > self.bounds.right() {
6910 size = self.bounds.right() - left_dock_size
6911 }
6912 });
6913 self.right_dock.update(cx, |right_dock, cx| {
6914 if WorkspaceSettings::get_global(cx)
6915 .resize_all_panels_in_dock
6916 .contains(&DockPosition::Right)
6917 {
6918 right_dock.resize_all_panels(Some(size), window, cx);
6919 } else {
6920 right_dock.resize_active_panel(Some(size), window, cx);
6921 }
6922 });
6923 }
6924
6925 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
6926 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
6927 self.bottom_dock.update(cx, |bottom_dock, cx| {
6928 if WorkspaceSettings::get_global(cx)
6929 .resize_all_panels_in_dock
6930 .contains(&DockPosition::Bottom)
6931 {
6932 bottom_dock.resize_all_panels(Some(size), window, cx);
6933 } else {
6934 bottom_dock.resize_active_panel(Some(size), window, cx);
6935 }
6936 });
6937 }
6938
6939 fn toggle_edit_predictions_all_files(
6940 &mut self,
6941 _: &ToggleEditPrediction,
6942 _window: &mut Window,
6943 cx: &mut Context<Self>,
6944 ) {
6945 let fs = self.project().read(cx).fs().clone();
6946 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
6947 update_settings_file(fs, cx, move |file, _| {
6948 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
6949 });
6950 }
6951
6952 pub fn show_worktree_trust_security_modal(
6953 &mut self,
6954 toggle: bool,
6955 window: &mut Window,
6956 cx: &mut Context<Self>,
6957 ) {
6958 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
6959 if toggle {
6960 security_modal.update(cx, |security_modal, cx| {
6961 security_modal.dismiss(cx);
6962 })
6963 } else {
6964 security_modal.update(cx, |security_modal, cx| {
6965 security_modal.refresh_restricted_paths(cx);
6966 });
6967 }
6968 } else {
6969 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
6970 .map(|trusted_worktrees| {
6971 trusted_worktrees
6972 .read(cx)
6973 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
6974 })
6975 .unwrap_or(false);
6976 if has_restricted_worktrees {
6977 let project = self.project().read(cx);
6978 let remote_host = project
6979 .remote_connection_options(cx)
6980 .map(RemoteHostLocation::from);
6981 let worktree_store = project.worktree_store().downgrade();
6982 self.toggle_modal(window, cx, |_, cx| {
6983 SecurityModal::new(worktree_store, remote_host, cx)
6984 });
6985 }
6986 }
6987 }
6988}
6989
6990fn leader_border_for_pane(
6991 follower_states: &HashMap<CollaboratorId, FollowerState>,
6992 pane: &Entity<Pane>,
6993 _: &Window,
6994 cx: &App,
6995) -> Option<Div> {
6996 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
6997 if state.pane() == pane {
6998 Some((*leader_id, state))
6999 } else {
7000 None
7001 }
7002 })?;
7003
7004 let mut leader_color = match leader_id {
7005 CollaboratorId::PeerId(leader_peer_id) => {
7006 let room = ActiveCall::try_global(cx)?.read(cx).room()?.read(cx);
7007 let leader = room.remote_participant_for_peer_id(leader_peer_id)?;
7008
7009 cx.theme()
7010 .players()
7011 .color_for_participant(leader.participant_index.0)
7012 .cursor
7013 }
7014 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7015 };
7016 leader_color.fade_out(0.3);
7017 Some(
7018 div()
7019 .absolute()
7020 .size_full()
7021 .left_0()
7022 .top_0()
7023 .border_2()
7024 .border_color(leader_color),
7025 )
7026}
7027
7028fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7029 ZED_WINDOW_POSITION
7030 .zip(*ZED_WINDOW_SIZE)
7031 .map(|(position, size)| Bounds {
7032 origin: position,
7033 size,
7034 })
7035}
7036
7037fn open_items(
7038 serialized_workspace: Option<SerializedWorkspace>,
7039 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7040 window: &mut Window,
7041 cx: &mut Context<Workspace>,
7042) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7043 let restored_items = serialized_workspace.map(|serialized_workspace| {
7044 Workspace::load_workspace(
7045 serialized_workspace,
7046 project_paths_to_open
7047 .iter()
7048 .map(|(_, project_path)| project_path)
7049 .cloned()
7050 .collect(),
7051 window,
7052 cx,
7053 )
7054 });
7055
7056 cx.spawn_in(window, async move |workspace, cx| {
7057 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7058
7059 if let Some(restored_items) = restored_items {
7060 let restored_items = restored_items.await?;
7061
7062 let restored_project_paths = restored_items
7063 .iter()
7064 .filter_map(|item| {
7065 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7066 .ok()
7067 .flatten()
7068 })
7069 .collect::<HashSet<_>>();
7070
7071 for restored_item in restored_items {
7072 opened_items.push(restored_item.map(Ok));
7073 }
7074
7075 project_paths_to_open
7076 .iter_mut()
7077 .for_each(|(_, project_path)| {
7078 if let Some(project_path_to_open) = project_path
7079 && restored_project_paths.contains(project_path_to_open)
7080 {
7081 *project_path = None;
7082 }
7083 });
7084 } else {
7085 for _ in 0..project_paths_to_open.len() {
7086 opened_items.push(None);
7087 }
7088 }
7089 assert!(opened_items.len() == project_paths_to_open.len());
7090
7091 let tasks =
7092 project_paths_to_open
7093 .into_iter()
7094 .enumerate()
7095 .map(|(ix, (abs_path, project_path))| {
7096 let workspace = workspace.clone();
7097 cx.spawn(async move |cx| {
7098 let file_project_path = project_path?;
7099 let abs_path_task = workspace.update(cx, |workspace, cx| {
7100 workspace.project().update(cx, |project, cx| {
7101 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7102 })
7103 });
7104
7105 // We only want to open file paths here. If one of the items
7106 // here is a directory, it was already opened further above
7107 // with a `find_or_create_worktree`.
7108 if let Ok(task) = abs_path_task
7109 && task.await.is_none_or(|p| p.is_file())
7110 {
7111 return Some((
7112 ix,
7113 workspace
7114 .update_in(cx, |workspace, window, cx| {
7115 workspace.open_path(
7116 file_project_path,
7117 None,
7118 true,
7119 window,
7120 cx,
7121 )
7122 })
7123 .log_err()?
7124 .await,
7125 ));
7126 }
7127 None
7128 })
7129 });
7130
7131 let tasks = tasks.collect::<Vec<_>>();
7132
7133 let tasks = futures::future::join_all(tasks);
7134 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7135 opened_items[ix] = Some(path_open_result);
7136 }
7137
7138 Ok(opened_items)
7139 })
7140}
7141
7142enum ActivateInDirectionTarget {
7143 Pane(Entity<Pane>),
7144 Dock(Entity<Dock>),
7145}
7146
7147fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7148 window
7149 .update(cx, |multi_workspace, _, cx| {
7150 let workspace = multi_workspace.workspace().clone();
7151 workspace.update(cx, |workspace, cx| {
7152 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7153 struct DatabaseFailedNotification;
7154
7155 workspace.show_notification(
7156 NotificationId::unique::<DatabaseFailedNotification>(),
7157 cx,
7158 |cx| {
7159 cx.new(|cx| {
7160 MessageNotification::new("Failed to load the database file.", cx)
7161 .primary_message("File an Issue")
7162 .primary_icon(IconName::Plus)
7163 .primary_on_click(|window, cx| {
7164 window.dispatch_action(Box::new(FileBugReport), cx)
7165 })
7166 })
7167 },
7168 );
7169 }
7170 });
7171 })
7172 .log_err();
7173}
7174
7175fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7176 if val == 0 {
7177 ThemeSettings::get_global(cx).ui_font_size(cx)
7178 } else {
7179 px(val as f32)
7180 }
7181}
7182
7183fn adjust_active_dock_size_by_px(
7184 px: Pixels,
7185 workspace: &mut Workspace,
7186 window: &mut Window,
7187 cx: &mut Context<Workspace>,
7188) {
7189 let Some(active_dock) = workspace
7190 .all_docks()
7191 .into_iter()
7192 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7193 else {
7194 return;
7195 };
7196 let dock = active_dock.read(cx);
7197 let Some(panel_size) = dock.active_panel_size(window, cx) else {
7198 return;
7199 };
7200 let dock_pos = dock.position();
7201 workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
7202}
7203
7204fn adjust_open_docks_size_by_px(
7205 px: Pixels,
7206 workspace: &mut Workspace,
7207 window: &mut Window,
7208 cx: &mut Context<Workspace>,
7209) {
7210 let docks = workspace
7211 .all_docks()
7212 .into_iter()
7213 .filter_map(|dock| {
7214 if dock.read(cx).is_open() {
7215 let dock = dock.read(cx);
7216 let panel_size = dock.active_panel_size(window, cx)?;
7217 let dock_pos = dock.position();
7218 Some((panel_size, dock_pos, px))
7219 } else {
7220 None
7221 }
7222 })
7223 .collect::<Vec<_>>();
7224
7225 docks
7226 .into_iter()
7227 .for_each(|(panel_size, dock_pos, offset)| {
7228 workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
7229 });
7230}
7231
7232impl Focusable for Workspace {
7233 fn focus_handle(&self, cx: &App) -> FocusHandle {
7234 self.active_pane.focus_handle(cx)
7235 }
7236}
7237
7238#[derive(Clone)]
7239struct DraggedDock(DockPosition);
7240
7241impl Render for DraggedDock {
7242 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7243 gpui::Empty
7244 }
7245}
7246
7247impl Render for Workspace {
7248 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7249 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7250 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7251 log::info!("Rendered first frame");
7252 }
7253 let mut context = KeyContext::new_with_defaults();
7254 context.add("Workspace");
7255 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
7256 if let Some(status) = self
7257 .debugger_provider
7258 .as_ref()
7259 .and_then(|provider| provider.active_thread_state(cx))
7260 {
7261 match status {
7262 ThreadStatus::Running | ThreadStatus::Stepping => {
7263 context.add("debugger_running");
7264 }
7265 ThreadStatus::Stopped => context.add("debugger_stopped"),
7266 ThreadStatus::Exited | ThreadStatus::Ended => {}
7267 }
7268 }
7269
7270 if self.left_dock.read(cx).is_open() {
7271 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
7272 context.set("left_dock", active_panel.panel_key());
7273 }
7274 }
7275
7276 if self.right_dock.read(cx).is_open() {
7277 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
7278 context.set("right_dock", active_panel.panel_key());
7279 }
7280 }
7281
7282 if self.bottom_dock.read(cx).is_open() {
7283 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
7284 context.set("bottom_dock", active_panel.panel_key());
7285 }
7286 }
7287
7288 let centered_layout = self.centered_layout
7289 && self.center.panes().len() == 1
7290 && self.active_item(cx).is_some();
7291 let render_padding = |size| {
7292 (size > 0.0).then(|| {
7293 div()
7294 .h_full()
7295 .w(relative(size))
7296 .bg(cx.theme().colors().editor_background)
7297 .border_color(cx.theme().colors().pane_group_border)
7298 })
7299 };
7300 let paddings = if centered_layout {
7301 let settings = WorkspaceSettings::get_global(cx).centered_layout;
7302 (
7303 render_padding(Self::adjust_padding(
7304 settings.left_padding.map(|padding| padding.0),
7305 )),
7306 render_padding(Self::adjust_padding(
7307 settings.right_padding.map(|padding| padding.0),
7308 )),
7309 )
7310 } else {
7311 (None, None)
7312 };
7313 let ui_font = theme::setup_ui_font(window, cx);
7314
7315 let theme = cx.theme().clone();
7316 let colors = theme.colors();
7317 let notification_entities = self
7318 .notifications
7319 .iter()
7320 .map(|(_, notification)| notification.entity_id())
7321 .collect::<Vec<_>>();
7322 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
7323
7324 self.actions(div(), window, cx)
7325 .key_context(context)
7326 .relative()
7327 .size_full()
7328 .flex()
7329 .flex_col()
7330 .font(ui_font)
7331 .gap_0()
7332 .justify_start()
7333 .items_start()
7334 .text_color(colors.text)
7335 .overflow_hidden()
7336 .children(self.titlebar_item.clone())
7337 .on_modifiers_changed(move |_, _, cx| {
7338 for &id in ¬ification_entities {
7339 cx.notify(id);
7340 }
7341 })
7342 .child(
7343 div()
7344 .size_full()
7345 .relative()
7346 .flex_1()
7347 .flex()
7348 .flex_col()
7349 .child(
7350 div()
7351 .id("workspace")
7352 .bg(colors.background)
7353 .relative()
7354 .flex_1()
7355 .w_full()
7356 .flex()
7357 .flex_col()
7358 .overflow_hidden()
7359 .border_t_1()
7360 .border_b_1()
7361 .border_color(colors.border)
7362 .child({
7363 let this = cx.entity();
7364 canvas(
7365 move |bounds, window, cx| {
7366 this.update(cx, |this, cx| {
7367 let bounds_changed = this.bounds != bounds;
7368 this.bounds = bounds;
7369
7370 if bounds_changed {
7371 this.left_dock.update(cx, |dock, cx| {
7372 dock.clamp_panel_size(
7373 bounds.size.width,
7374 window,
7375 cx,
7376 )
7377 });
7378
7379 this.right_dock.update(cx, |dock, cx| {
7380 dock.clamp_panel_size(
7381 bounds.size.width,
7382 window,
7383 cx,
7384 )
7385 });
7386
7387 this.bottom_dock.update(cx, |dock, cx| {
7388 dock.clamp_panel_size(
7389 bounds.size.height,
7390 window,
7391 cx,
7392 )
7393 });
7394 }
7395 })
7396 },
7397 |_, _, _, _| {},
7398 )
7399 .absolute()
7400 .size_full()
7401 })
7402 .when(self.zoomed.is_none(), |this| {
7403 this.on_drag_move(cx.listener(
7404 move |workspace,
7405 e: &DragMoveEvent<DraggedDock>,
7406 window,
7407 cx| {
7408 if workspace.previous_dock_drag_coordinates
7409 != Some(e.event.position)
7410 {
7411 workspace.previous_dock_drag_coordinates =
7412 Some(e.event.position);
7413 match e.drag(cx).0 {
7414 DockPosition::Left => {
7415 workspace.resize_left_dock(
7416 e.event.position.x
7417 - workspace.bounds.left(),
7418 window,
7419 cx,
7420 );
7421 }
7422 DockPosition::Right => {
7423 workspace.resize_right_dock(
7424 workspace.bounds.right()
7425 - e.event.position.x,
7426 window,
7427 cx,
7428 );
7429 }
7430 DockPosition::Bottom => {
7431 workspace.resize_bottom_dock(
7432 workspace.bounds.bottom()
7433 - e.event.position.y,
7434 window,
7435 cx,
7436 );
7437 }
7438 };
7439 workspace.serialize_workspace(window, cx);
7440 }
7441 },
7442 ))
7443
7444 })
7445 .child({
7446 match bottom_dock_layout {
7447 BottomDockLayout::Full => div()
7448 .flex()
7449 .flex_col()
7450 .h_full()
7451 .child(
7452 div()
7453 .flex()
7454 .flex_row()
7455 .flex_1()
7456 .overflow_hidden()
7457 .children(self.render_dock(
7458 DockPosition::Left,
7459 &self.left_dock,
7460 window,
7461 cx,
7462 ))
7463
7464 .child(
7465 div()
7466 .flex()
7467 .flex_col()
7468 .flex_1()
7469 .overflow_hidden()
7470 .child(
7471 h_flex()
7472 .flex_1()
7473 .when_some(
7474 paddings.0,
7475 |this, p| {
7476 this.child(
7477 p.border_r_1(),
7478 )
7479 },
7480 )
7481 .child(self.center.render(
7482 self.zoomed.as_ref(),
7483 &PaneRenderContext {
7484 follower_states:
7485 &self.follower_states,
7486 active_call: self.active_call(),
7487 active_pane: &self.active_pane,
7488 app_state: &self.app_state,
7489 project: &self.project,
7490 workspace: &self.weak_self,
7491 },
7492 window,
7493 cx,
7494 ))
7495 .when_some(
7496 paddings.1,
7497 |this, p| {
7498 this.child(
7499 p.border_l_1(),
7500 )
7501 },
7502 ),
7503 ),
7504 )
7505
7506 .children(self.render_dock(
7507 DockPosition::Right,
7508 &self.right_dock,
7509 window,
7510 cx,
7511 )),
7512 )
7513 .child(div().w_full().children(self.render_dock(
7514 DockPosition::Bottom,
7515 &self.bottom_dock,
7516 window,
7517 cx
7518 ))),
7519
7520 BottomDockLayout::LeftAligned => div()
7521 .flex()
7522 .flex_row()
7523 .h_full()
7524 .child(
7525 div()
7526 .flex()
7527 .flex_col()
7528 .flex_1()
7529 .h_full()
7530 .child(
7531 div()
7532 .flex()
7533 .flex_row()
7534 .flex_1()
7535 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
7536
7537 .child(
7538 div()
7539 .flex()
7540 .flex_col()
7541 .flex_1()
7542 .overflow_hidden()
7543 .child(
7544 h_flex()
7545 .flex_1()
7546 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7547 .child(self.center.render(
7548 self.zoomed.as_ref(),
7549 &PaneRenderContext {
7550 follower_states:
7551 &self.follower_states,
7552 active_call: self.active_call(),
7553 active_pane: &self.active_pane,
7554 app_state: &self.app_state,
7555 project: &self.project,
7556 workspace: &self.weak_self,
7557 },
7558 window,
7559 cx,
7560 ))
7561 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7562 )
7563 )
7564
7565 )
7566 .child(
7567 div()
7568 .w_full()
7569 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7570 ),
7571 )
7572 .children(self.render_dock(
7573 DockPosition::Right,
7574 &self.right_dock,
7575 window,
7576 cx,
7577 )),
7578
7579 BottomDockLayout::RightAligned => div()
7580 .flex()
7581 .flex_row()
7582 .h_full()
7583 .children(self.render_dock(
7584 DockPosition::Left,
7585 &self.left_dock,
7586 window,
7587 cx,
7588 ))
7589
7590 .child(
7591 div()
7592 .flex()
7593 .flex_col()
7594 .flex_1()
7595 .h_full()
7596 .child(
7597 div()
7598 .flex()
7599 .flex_row()
7600 .flex_1()
7601 .child(
7602 div()
7603 .flex()
7604 .flex_col()
7605 .flex_1()
7606 .overflow_hidden()
7607 .child(
7608 h_flex()
7609 .flex_1()
7610 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7611 .child(self.center.render(
7612 self.zoomed.as_ref(),
7613 &PaneRenderContext {
7614 follower_states:
7615 &self.follower_states,
7616 active_call: self.active_call(),
7617 active_pane: &self.active_pane,
7618 app_state: &self.app_state,
7619 project: &self.project,
7620 workspace: &self.weak_self,
7621 },
7622 window,
7623 cx,
7624 ))
7625 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7626 )
7627 )
7628
7629 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
7630 )
7631 .child(
7632 div()
7633 .w_full()
7634 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7635 ),
7636 ),
7637
7638 BottomDockLayout::Contained => div()
7639 .flex()
7640 .flex_row()
7641 .h_full()
7642 .children(self.render_dock(
7643 DockPosition::Left,
7644 &self.left_dock,
7645 window,
7646 cx,
7647 ))
7648
7649 .child(
7650 div()
7651 .flex()
7652 .flex_col()
7653 .flex_1()
7654 .overflow_hidden()
7655 .child(
7656 h_flex()
7657 .flex_1()
7658 .when_some(paddings.0, |this, p| {
7659 this.child(p.border_r_1())
7660 })
7661 .child(self.center.render(
7662 self.zoomed.as_ref(),
7663 &PaneRenderContext {
7664 follower_states:
7665 &self.follower_states,
7666 active_call: self.active_call(),
7667 active_pane: &self.active_pane,
7668 app_state: &self.app_state,
7669 project: &self.project,
7670 workspace: &self.weak_self,
7671 },
7672 window,
7673 cx,
7674 ))
7675 .when_some(paddings.1, |this, p| {
7676 this.child(p.border_l_1())
7677 }),
7678 )
7679 .children(self.render_dock(
7680 DockPosition::Bottom,
7681 &self.bottom_dock,
7682 window,
7683 cx,
7684 )),
7685 )
7686
7687 .children(self.render_dock(
7688 DockPosition::Right,
7689 &self.right_dock,
7690 window,
7691 cx,
7692 )),
7693 }
7694 })
7695 .children(self.zoomed.as_ref().and_then(|view| {
7696 let zoomed_view = view.upgrade()?;
7697 let div = div()
7698 .occlude()
7699 .absolute()
7700 .overflow_hidden()
7701 .border_color(colors.border)
7702 .bg(colors.background)
7703 .child(zoomed_view)
7704 .inset_0()
7705 .shadow_lg();
7706
7707 if !WorkspaceSettings::get_global(cx).zoomed_padding {
7708 return Some(div);
7709 }
7710
7711 Some(match self.zoomed_position {
7712 Some(DockPosition::Left) => div.right_2().border_r_1(),
7713 Some(DockPosition::Right) => div.left_2().border_l_1(),
7714 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
7715 None => {
7716 div.top_2().bottom_2().left_2().right_2().border_1()
7717 }
7718 })
7719 }))
7720 .children(self.render_notifications(window, cx)),
7721 )
7722 .when(self.status_bar_visible(cx), |parent| {
7723 parent.child(self.status_bar.clone())
7724 })
7725 .child(self.modal_layer.clone())
7726 .child(self.toast_layer.clone()),
7727 )
7728 }
7729}
7730
7731impl WorkspaceStore {
7732 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
7733 Self {
7734 workspaces: Default::default(),
7735 _subscriptions: vec![
7736 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
7737 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
7738 ],
7739 client,
7740 }
7741 }
7742
7743 pub fn update_followers(
7744 &self,
7745 project_id: Option<u64>,
7746 update: proto::update_followers::Variant,
7747 cx: &App,
7748 ) -> Option<()> {
7749 let active_call = ActiveCall::try_global(cx)?;
7750 let room_id = active_call.read(cx).room()?.read(cx).id();
7751 self.client
7752 .send(proto::UpdateFollowers {
7753 room_id,
7754 project_id,
7755 variant: Some(update),
7756 })
7757 .log_err()
7758 }
7759
7760 pub async fn handle_follow(
7761 this: Entity<Self>,
7762 envelope: TypedEnvelope<proto::Follow>,
7763 mut cx: AsyncApp,
7764 ) -> Result<proto::FollowResponse> {
7765 this.update(&mut cx, |this, cx| {
7766 let follower = Follower {
7767 project_id: envelope.payload.project_id,
7768 peer_id: envelope.original_sender_id()?,
7769 };
7770
7771 let mut response = proto::FollowResponse::default();
7772
7773 this.workspaces.retain(|(window_handle, weak_workspace)| {
7774 let Some(workspace) = weak_workspace.upgrade() else {
7775 return false;
7776 };
7777 window_handle
7778 .update(cx, |_, window, cx| {
7779 workspace.update(cx, |workspace, cx| {
7780 let handler_response =
7781 workspace.handle_follow(follower.project_id, window, cx);
7782 if let Some(active_view) = handler_response.active_view
7783 && workspace.project.read(cx).remote_id() == follower.project_id
7784 {
7785 response.active_view = Some(active_view)
7786 }
7787 });
7788 })
7789 .is_ok()
7790 });
7791
7792 Ok(response)
7793 })
7794 }
7795
7796 async fn handle_update_followers(
7797 this: Entity<Self>,
7798 envelope: TypedEnvelope<proto::UpdateFollowers>,
7799 mut cx: AsyncApp,
7800 ) -> Result<()> {
7801 let leader_id = envelope.original_sender_id()?;
7802 let update = envelope.payload;
7803
7804 this.update(&mut cx, |this, cx| {
7805 this.workspaces.retain(|(window_handle, weak_workspace)| {
7806 let Some(workspace) = weak_workspace.upgrade() else {
7807 return false;
7808 };
7809 window_handle
7810 .update(cx, |_, window, cx| {
7811 workspace.update(cx, |workspace, cx| {
7812 let project_id = workspace.project.read(cx).remote_id();
7813 if update.project_id != project_id && update.project_id.is_some() {
7814 return;
7815 }
7816 workspace.handle_update_followers(
7817 leader_id,
7818 update.clone(),
7819 window,
7820 cx,
7821 );
7822 });
7823 })
7824 .is_ok()
7825 });
7826 Ok(())
7827 })
7828 }
7829
7830 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
7831 self.workspaces.iter().map(|(_, weak)| weak)
7832 }
7833
7834 pub fn workspaces_with_windows(
7835 &self,
7836 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
7837 self.workspaces.iter().map(|(window, weak)| (*window, weak))
7838 }
7839}
7840
7841impl ViewId {
7842 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
7843 Ok(Self {
7844 creator: message
7845 .creator
7846 .map(CollaboratorId::PeerId)
7847 .context("creator is missing")?,
7848 id: message.id,
7849 })
7850 }
7851
7852 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
7853 if let CollaboratorId::PeerId(peer_id) = self.creator {
7854 Some(proto::ViewId {
7855 creator: Some(peer_id),
7856 id: self.id,
7857 })
7858 } else {
7859 None
7860 }
7861 }
7862}
7863
7864impl FollowerState {
7865 fn pane(&self) -> &Entity<Pane> {
7866 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
7867 }
7868}
7869
7870pub trait WorkspaceHandle {
7871 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
7872}
7873
7874impl WorkspaceHandle for Entity<Workspace> {
7875 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
7876 self.read(cx)
7877 .worktrees(cx)
7878 .flat_map(|worktree| {
7879 let worktree_id = worktree.read(cx).id();
7880 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
7881 worktree_id,
7882 path: f.path.clone(),
7883 })
7884 })
7885 .collect::<Vec<_>>()
7886 }
7887}
7888
7889pub async fn last_opened_workspace_location(
7890 fs: &dyn fs::Fs,
7891) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
7892 DB.last_workspace(fs)
7893 .await
7894 .log_err()
7895 .flatten()
7896 .map(|(id, location, paths, _timestamp)| (id, location, paths))
7897}
7898
7899pub async fn last_session_workspace_locations(
7900 last_session_id: &str,
7901 last_session_window_stack: Option<Vec<WindowId>>,
7902 fs: &dyn fs::Fs,
7903) -> Option<Vec<SessionWorkspace>> {
7904 DB.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
7905 .await
7906 .log_err()
7907}
7908
7909pub async fn restore_multiworkspace(
7910 multi_workspace: SerializedMultiWorkspace,
7911 app_state: Arc<AppState>,
7912 cx: &mut AsyncApp,
7913) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
7914 let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
7915 let mut group_iter = workspaces.into_iter();
7916 let first = group_iter
7917 .next()
7918 .context("window group must not be empty")?;
7919
7920 let window_handle = if first.paths.is_empty() {
7921 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
7922 .await?
7923 } else {
7924 let (window, _items) = cx
7925 .update(|cx| {
7926 Workspace::new_local(
7927 first.paths.paths().to_vec(),
7928 app_state.clone(),
7929 None,
7930 None,
7931 None,
7932 cx,
7933 )
7934 })
7935 .await?;
7936 window
7937 };
7938
7939 for session_workspace in group_iter {
7940 if session_workspace.paths.is_empty() {
7941 cx.update(|cx| {
7942 open_workspace_by_id(
7943 session_workspace.workspace_id,
7944 app_state.clone(),
7945 Some(window_handle),
7946 cx,
7947 )
7948 })
7949 .await?;
7950 } else {
7951 cx.update(|cx| {
7952 Workspace::new_local(
7953 session_workspace.paths.paths().to_vec(),
7954 app_state.clone(),
7955 Some(window_handle),
7956 None,
7957 None,
7958 cx,
7959 )
7960 })
7961 .await?;
7962 }
7963 }
7964
7965 if let Some(target_id) = state.active_workspace_id {
7966 window_handle
7967 .update(cx, |multi_workspace, window, cx| {
7968 let target_index = multi_workspace
7969 .workspaces()
7970 .iter()
7971 .position(|ws| ws.read(cx).database_id() == Some(target_id));
7972 if let Some(index) = target_index {
7973 multi_workspace.activate_index(index, window, cx);
7974 } else if !multi_workspace.workspaces().is_empty() {
7975 multi_workspace.activate_index(0, window, cx);
7976 }
7977 })
7978 .ok();
7979 } else {
7980 window_handle
7981 .update(cx, |multi_workspace, window, cx| {
7982 if !multi_workspace.workspaces().is_empty() {
7983 multi_workspace.activate_index(0, window, cx);
7984 }
7985 })
7986 .ok();
7987 }
7988
7989 if state.sidebar_open {
7990 window_handle
7991 .update(cx, |multi_workspace, _, cx| {
7992 multi_workspace.open_sidebar(cx);
7993 })
7994 .ok();
7995 }
7996
7997 window_handle
7998 .update(cx, |_, window, _cx| {
7999 window.activate_window();
8000 })
8001 .ok();
8002
8003 Ok(window_handle)
8004}
8005
8006actions!(
8007 collab,
8008 [
8009 /// Opens the channel notes for the current call.
8010 ///
8011 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8012 /// channel in the collab panel.
8013 ///
8014 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8015 /// can be copied via "Copy link to section" in the context menu of the channel notes
8016 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8017 OpenChannelNotes,
8018 /// Mutes your microphone.
8019 Mute,
8020 /// Deafens yourself (mute both microphone and speakers).
8021 Deafen,
8022 /// Leaves the current call.
8023 LeaveCall,
8024 /// Shares the current project with collaborators.
8025 ShareProject,
8026 /// Shares your screen with collaborators.
8027 ScreenShare,
8028 /// Copies the current room name and session id for debugging purposes.
8029 CopyRoomId,
8030 ]
8031);
8032actions!(
8033 zed,
8034 [
8035 /// Opens the Zed log file.
8036 OpenLog,
8037 /// Reveals the Zed log file in the system file manager.
8038 RevealLogInFileManager
8039 ]
8040);
8041
8042async fn join_channel_internal(
8043 channel_id: ChannelId,
8044 app_state: &Arc<AppState>,
8045 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8046 requesting_workspace: Option<WeakEntity<Workspace>>,
8047 active_call: &Entity<ActiveCall>,
8048 cx: &mut AsyncApp,
8049) -> Result<bool> {
8050 let (should_prompt, open_room) = active_call.update(cx, |active_call, cx| {
8051 let Some(room) = active_call.room().map(|room| room.read(cx)) else {
8052 return (false, None);
8053 };
8054
8055 let already_in_channel = room.channel_id() == Some(channel_id);
8056 let should_prompt = room.is_sharing_project()
8057 && !room.remote_participants().is_empty()
8058 && !already_in_channel;
8059 let open_room = if already_in_channel {
8060 active_call.room().cloned()
8061 } else {
8062 None
8063 };
8064 (should_prompt, open_room)
8065 });
8066
8067 if let Some(room) = open_room {
8068 let task = room.update(cx, |room, cx| {
8069 if let Some((project, host)) = room.most_active_project(cx) {
8070 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8071 }
8072
8073 None
8074 });
8075 if let Some(task) = task {
8076 task.await?;
8077 }
8078 return anyhow::Ok(true);
8079 }
8080
8081 if should_prompt {
8082 if let Some(multi_workspace) = requesting_window {
8083 let answer = multi_workspace
8084 .update(cx, |_, window, cx| {
8085 window.prompt(
8086 PromptLevel::Warning,
8087 "Do you want to switch channels?",
8088 Some("Leaving this call will unshare your current project."),
8089 &["Yes, Join Channel", "Cancel"],
8090 cx,
8091 )
8092 })?
8093 .await;
8094
8095 if answer == Ok(1) {
8096 return Ok(false);
8097 }
8098 } else {
8099 return Ok(false); // unreachable!() hopefully
8100 }
8101 }
8102
8103 let client = cx.update(|cx| active_call.read(cx).client());
8104
8105 let mut client_status = client.status();
8106
8107 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8108 'outer: loop {
8109 let Some(status) = client_status.recv().await else {
8110 anyhow::bail!("error connecting");
8111 };
8112
8113 match status {
8114 Status::Connecting
8115 | Status::Authenticating
8116 | Status::Authenticated
8117 | Status::Reconnecting
8118 | Status::Reauthenticating
8119 | Status::Reauthenticated => continue,
8120 Status::Connected { .. } => break 'outer,
8121 Status::SignedOut | Status::AuthenticationError => {
8122 return Err(ErrorCode::SignedOut.into());
8123 }
8124 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8125 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8126 return Err(ErrorCode::Disconnected.into());
8127 }
8128 }
8129 }
8130
8131 let room = active_call
8132 .update(cx, |active_call, cx| {
8133 active_call.join_channel(channel_id, cx)
8134 })
8135 .await?;
8136
8137 let Some(room) = room else {
8138 return anyhow::Ok(true);
8139 };
8140
8141 room.update(cx, |room, _| room.room_update_completed())
8142 .await;
8143
8144 let task = room.update(cx, |room, cx| {
8145 if let Some((project, host)) = room.most_active_project(cx) {
8146 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8147 }
8148
8149 // If you are the first to join a channel, see if you should share your project.
8150 if room.remote_participants().is_empty()
8151 && !room.local_participant_is_guest()
8152 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8153 {
8154 let project = workspace.update(cx, |workspace, cx| {
8155 let project = workspace.project.read(cx);
8156
8157 if !CallSettings::get_global(cx).share_on_join {
8158 return None;
8159 }
8160
8161 if (project.is_local() || project.is_via_remote_server())
8162 && project.visible_worktrees(cx).any(|tree| {
8163 tree.read(cx)
8164 .root_entry()
8165 .is_some_and(|entry| entry.is_dir())
8166 })
8167 {
8168 Some(workspace.project.clone())
8169 } else {
8170 None
8171 }
8172 });
8173 if let Some(project) = project {
8174 return Some(cx.spawn(async move |room, cx| {
8175 room.update(cx, |room, cx| room.share_project(project, cx))?
8176 .await?;
8177 Ok(())
8178 }));
8179 }
8180 }
8181
8182 None
8183 });
8184 if let Some(task) = task {
8185 task.await?;
8186 return anyhow::Ok(true);
8187 }
8188 anyhow::Ok(false)
8189}
8190
8191pub fn join_channel(
8192 channel_id: ChannelId,
8193 app_state: Arc<AppState>,
8194 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8195 requesting_workspace: Option<WeakEntity<Workspace>>,
8196 cx: &mut App,
8197) -> Task<Result<()>> {
8198 let active_call = ActiveCall::global(cx);
8199 cx.spawn(async move |cx| {
8200 let result = join_channel_internal(
8201 channel_id,
8202 &app_state,
8203 requesting_window,
8204 requesting_workspace,
8205 &active_call,
8206 cx,
8207 )
8208 .await;
8209
8210 // join channel succeeded, and opened a window
8211 if matches!(result, Ok(true)) {
8212 return anyhow::Ok(());
8213 }
8214
8215 // find an existing workspace to focus and show call controls
8216 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8217 if active_window.is_none() {
8218 // no open workspaces, make one to show the error in (blergh)
8219 let (window_handle, _) = cx
8220 .update(|cx| {
8221 Workspace::new_local(
8222 vec![],
8223 app_state.clone(),
8224 requesting_window,
8225 None,
8226 None,
8227 cx,
8228 )
8229 })
8230 .await?;
8231
8232 window_handle
8233 .update(cx, |_, window, _cx| {
8234 window.activate_window();
8235 })
8236 .ok();
8237
8238 if result.is_ok() {
8239 cx.update(|cx| {
8240 cx.dispatch_action(&OpenChannelNotes);
8241 });
8242 }
8243
8244 active_window = Some(window_handle);
8245 }
8246
8247 if let Err(err) = result {
8248 log::error!("failed to join channel: {}", err);
8249 if let Some(active_window) = active_window {
8250 active_window
8251 .update(cx, |_, window, cx| {
8252 let detail: SharedString = match err.error_code() {
8253 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8254 ErrorCode::UpgradeRequired => concat!(
8255 "Your are running an unsupported version of Zed. ",
8256 "Please update to continue."
8257 )
8258 .into(),
8259 ErrorCode::NoSuchChannel => concat!(
8260 "No matching channel was found. ",
8261 "Please check the link and try again."
8262 )
8263 .into(),
8264 ErrorCode::Forbidden => concat!(
8265 "This channel is private, and you do not have access. ",
8266 "Please ask someone to add you and try again."
8267 )
8268 .into(),
8269 ErrorCode::Disconnected => {
8270 "Please check your internet connection and try again.".into()
8271 }
8272 _ => format!("{}\n\nPlease try again.", err).into(),
8273 };
8274 window.prompt(
8275 PromptLevel::Critical,
8276 "Failed to join channel",
8277 Some(&detail),
8278 &["Ok"],
8279 cx,
8280 )
8281 })?
8282 .await
8283 .ok();
8284 }
8285 }
8286
8287 // return ok, we showed the error to the user.
8288 anyhow::Ok(())
8289 })
8290}
8291
8292pub async fn get_any_active_multi_workspace(
8293 app_state: Arc<AppState>,
8294 mut cx: AsyncApp,
8295) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8296 // find an existing workspace to focus and show call controls
8297 let active_window = activate_any_workspace_window(&mut cx);
8298 if active_window.is_none() {
8299 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, cx))
8300 .await?;
8301 }
8302 activate_any_workspace_window(&mut cx).context("could not open zed")
8303}
8304
8305fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
8306 cx.update(|cx| {
8307 if let Some(workspace_window) = cx
8308 .active_window()
8309 .and_then(|window| window.downcast::<MultiWorkspace>())
8310 {
8311 return Some(workspace_window);
8312 }
8313
8314 for window in cx.windows() {
8315 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
8316 workspace_window
8317 .update(cx, |_, window, _| window.activate_window())
8318 .ok();
8319 return Some(workspace_window);
8320 }
8321 }
8322 None
8323 })
8324}
8325
8326pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
8327 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
8328}
8329
8330pub fn workspace_windows_for_location(
8331 serialized_location: &SerializedWorkspaceLocation,
8332 cx: &App,
8333) -> Vec<WindowHandle<MultiWorkspace>> {
8334 cx.windows()
8335 .into_iter()
8336 .filter_map(|window| window.downcast::<MultiWorkspace>())
8337 .filter(|multi_workspace| {
8338 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
8339 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
8340 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
8341 }
8342 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
8343 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
8344 a.distro_name == b.distro_name
8345 }
8346 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
8347 a.container_id == b.container_id
8348 }
8349 #[cfg(any(test, feature = "test-support"))]
8350 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
8351 a.id == b.id
8352 }
8353 _ => false,
8354 };
8355
8356 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
8357 multi_workspace.workspaces().iter().any(|workspace| {
8358 match workspace.read(cx).workspace_location(cx) {
8359 WorkspaceLocation::Location(location, _) => {
8360 match (&location, serialized_location) {
8361 (
8362 SerializedWorkspaceLocation::Local,
8363 SerializedWorkspaceLocation::Local,
8364 ) => true,
8365 (
8366 SerializedWorkspaceLocation::Remote(a),
8367 SerializedWorkspaceLocation::Remote(b),
8368 ) => same_host(a, b),
8369 _ => false,
8370 }
8371 }
8372 _ => false,
8373 }
8374 })
8375 })
8376 })
8377 .collect()
8378}
8379
8380pub async fn find_existing_workspace(
8381 abs_paths: &[PathBuf],
8382 open_options: &OpenOptions,
8383 location: &SerializedWorkspaceLocation,
8384 cx: &mut AsyncApp,
8385) -> (
8386 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
8387 OpenVisible,
8388) {
8389 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
8390 let mut open_visible = OpenVisible::All;
8391 let mut best_match = None;
8392
8393 if open_options.open_new_workspace != Some(true) {
8394 cx.update(|cx| {
8395 for window in workspace_windows_for_location(location, cx) {
8396 if let Ok(multi_workspace) = window.read(cx) {
8397 for workspace in multi_workspace.workspaces() {
8398 let project = workspace.read(cx).project.read(cx);
8399 let m = project.visibility_for_paths(
8400 abs_paths,
8401 open_options.open_new_workspace == None,
8402 cx,
8403 );
8404 if m > best_match {
8405 existing = Some((window, workspace.clone()));
8406 best_match = m;
8407 } else if best_match.is_none()
8408 && open_options.open_new_workspace == Some(false)
8409 {
8410 existing = Some((window, workspace.clone()))
8411 }
8412 }
8413 }
8414 }
8415 });
8416
8417 let all_paths_are_files = existing
8418 .as_ref()
8419 .and_then(|(_, target_workspace)| {
8420 cx.update(|cx| {
8421 let workspace = target_workspace.read(cx);
8422 let project = workspace.project.read(cx);
8423 let path_style = workspace.path_style(cx);
8424 Some(!abs_paths.iter().any(|path| {
8425 let path = util::paths::SanitizedPath::new(path);
8426 project.worktrees(cx).any(|worktree| {
8427 let worktree = worktree.read(cx);
8428 let abs_path = worktree.abs_path();
8429 path_style
8430 .strip_prefix(path.as_ref(), abs_path.as_ref())
8431 .and_then(|rel| worktree.entry_for_path(&rel))
8432 .is_some_and(|e| e.is_dir())
8433 })
8434 }))
8435 })
8436 })
8437 .unwrap_or(false);
8438
8439 if open_options.open_new_workspace.is_none()
8440 && existing.is_some()
8441 && open_options.wait
8442 && all_paths_are_files
8443 {
8444 cx.update(|cx| {
8445 let windows = workspace_windows_for_location(location, cx);
8446 let window = cx
8447 .active_window()
8448 .and_then(|window| window.downcast::<MultiWorkspace>())
8449 .filter(|window| windows.contains(window))
8450 .or_else(|| windows.into_iter().next());
8451 if let Some(window) = window {
8452 if let Ok(multi_workspace) = window.read(cx) {
8453 let active_workspace = multi_workspace.workspace().clone();
8454 existing = Some((window, active_workspace));
8455 open_visible = OpenVisible::None;
8456 }
8457 }
8458 });
8459 }
8460 }
8461 (existing, open_visible)
8462}
8463
8464#[derive(Default, Clone)]
8465pub struct OpenOptions {
8466 pub visible: Option<OpenVisible>,
8467 pub focus: Option<bool>,
8468 pub open_new_workspace: Option<bool>,
8469 pub wait: bool,
8470 pub replace_window: Option<WindowHandle<MultiWorkspace>>,
8471 pub env: Option<HashMap<String, String>>,
8472}
8473
8474/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
8475pub fn open_workspace_by_id(
8476 workspace_id: WorkspaceId,
8477 app_state: Arc<AppState>,
8478 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8479 cx: &mut App,
8480) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
8481 let project_handle = Project::local(
8482 app_state.client.clone(),
8483 app_state.node_runtime.clone(),
8484 app_state.user_store.clone(),
8485 app_state.languages.clone(),
8486 app_state.fs.clone(),
8487 None,
8488 project::LocalProjectFlags {
8489 init_worktree_trust: true,
8490 ..project::LocalProjectFlags::default()
8491 },
8492 cx,
8493 );
8494
8495 cx.spawn(async move |cx| {
8496 let serialized_workspace = persistence::DB
8497 .workspace_for_id(workspace_id)
8498 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
8499
8500 let centered_layout = serialized_workspace.centered_layout;
8501
8502 let (window, workspace) = if let Some(window) = requesting_window {
8503 let workspace = window.update(cx, |multi_workspace, window, cx| {
8504 let workspace = cx.new(|cx| {
8505 let mut workspace = Workspace::new(
8506 Some(workspace_id),
8507 project_handle.clone(),
8508 app_state.clone(),
8509 window,
8510 cx,
8511 );
8512 workspace.centered_layout = centered_layout;
8513 workspace
8514 });
8515 multi_workspace.add_workspace(workspace.clone(), cx);
8516 workspace
8517 })?;
8518 (window, workspace)
8519 } else {
8520 let window_bounds_override = window_bounds_env_override();
8521
8522 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
8523 (Some(WindowBounds::Windowed(bounds)), None)
8524 } else if let Some(display) = serialized_workspace.display
8525 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
8526 {
8527 (Some(bounds.0), Some(display))
8528 } else if let Some((display, bounds)) = persistence::read_default_window_bounds() {
8529 (Some(bounds), Some(display))
8530 } else {
8531 (None, None)
8532 };
8533
8534 let options = cx.update(|cx| {
8535 let mut options = (app_state.build_window_options)(display, cx);
8536 options.window_bounds = window_bounds;
8537 options
8538 });
8539
8540 let window = cx.open_window(options, {
8541 let app_state = app_state.clone();
8542 let project_handle = project_handle.clone();
8543 move |window, cx| {
8544 let workspace = cx.new(|cx| {
8545 let mut workspace = Workspace::new(
8546 Some(workspace_id),
8547 project_handle,
8548 app_state,
8549 window,
8550 cx,
8551 );
8552 workspace.centered_layout = centered_layout;
8553 workspace
8554 });
8555 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
8556 }
8557 })?;
8558
8559 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
8560 multi_workspace.workspace().clone()
8561 })?;
8562
8563 (window, workspace)
8564 };
8565
8566 notify_if_database_failed(window, cx);
8567
8568 // Restore items from the serialized workspace
8569 window
8570 .update(cx, |_, window, cx| {
8571 workspace.update(cx, |_workspace, cx| {
8572 open_items(Some(serialized_workspace), vec![], window, cx)
8573 })
8574 })?
8575 .await?;
8576
8577 window.update(cx, |_, window, cx| {
8578 workspace.update(cx, |workspace, cx| {
8579 workspace.serialize_workspace(window, cx);
8580 });
8581 })?;
8582
8583 Ok(window)
8584 })
8585}
8586
8587#[allow(clippy::type_complexity)]
8588pub fn open_paths(
8589 abs_paths: &[PathBuf],
8590 app_state: Arc<AppState>,
8591 open_options: OpenOptions,
8592 cx: &mut App,
8593) -> Task<
8594 anyhow::Result<(
8595 WindowHandle<MultiWorkspace>,
8596 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
8597 )>,
8598> {
8599 let abs_paths = abs_paths.to_vec();
8600 #[cfg(target_os = "windows")]
8601 let wsl_path = abs_paths
8602 .iter()
8603 .find_map(|p| util::paths::WslPath::from_path(p));
8604
8605 cx.spawn(async move |cx| {
8606 let (mut existing, mut open_visible) = find_existing_workspace(
8607 &abs_paths,
8608 &open_options,
8609 &SerializedWorkspaceLocation::Local,
8610 cx,
8611 )
8612 .await;
8613
8614 // Fallback: if no workspace contains the paths and all paths are files,
8615 // prefer an existing local workspace window (active window first).
8616 if open_options.open_new_workspace.is_none() && existing.is_none() {
8617 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
8618 let all_metadatas = futures::future::join_all(all_paths)
8619 .await
8620 .into_iter()
8621 .filter_map(|result| result.ok().flatten())
8622 .collect::<Vec<_>>();
8623
8624 if all_metadatas.iter().all(|file| !file.is_dir) {
8625 cx.update(|cx| {
8626 let windows = workspace_windows_for_location(
8627 &SerializedWorkspaceLocation::Local,
8628 cx,
8629 );
8630 let window = cx
8631 .active_window()
8632 .and_then(|window| window.downcast::<MultiWorkspace>())
8633 .filter(|window| windows.contains(window))
8634 .or_else(|| windows.into_iter().next());
8635 if let Some(window) = window {
8636 if let Ok(multi_workspace) = window.read(cx) {
8637 let active_workspace = multi_workspace.workspace().clone();
8638 existing = Some((window, active_workspace));
8639 open_visible = OpenVisible::None;
8640 }
8641 }
8642 });
8643 }
8644 }
8645
8646 let result = if let Some((existing, target_workspace)) = existing {
8647 let open_task = existing
8648 .update(cx, |multi_workspace, window, cx| {
8649 window.activate_window();
8650 multi_workspace.activate(target_workspace.clone(), cx);
8651 target_workspace.update(cx, |workspace, cx| {
8652 workspace.open_paths(
8653 abs_paths,
8654 OpenOptions {
8655 visible: Some(open_visible),
8656 ..Default::default()
8657 },
8658 None,
8659 window,
8660 cx,
8661 )
8662 })
8663 })?
8664 .await;
8665
8666 _ = existing.update(cx, |multi_workspace, _, cx| {
8667 let workspace = multi_workspace.workspace().clone();
8668 workspace.update(cx, |workspace, cx| {
8669 for item in open_task.iter().flatten() {
8670 if let Err(e) = item {
8671 workspace.show_error(&e, cx);
8672 }
8673 }
8674 });
8675 });
8676
8677 Ok((existing, open_task))
8678 } else {
8679 let result = cx
8680 .update(move |cx| {
8681 Workspace::new_local(
8682 abs_paths,
8683 app_state.clone(),
8684 open_options.replace_window,
8685 open_options.env,
8686 None,
8687 cx,
8688 )
8689 })
8690 .await;
8691
8692 if let Ok((ref window_handle, _)) = result {
8693 window_handle
8694 .update(cx, |_, window, _cx| {
8695 window.activate_window();
8696 })
8697 .log_err();
8698 }
8699
8700 result
8701 };
8702
8703 #[cfg(target_os = "windows")]
8704 if let Some(util::paths::WslPath{distro, path}) = wsl_path
8705 && let Ok((multi_workspace_window, _)) = &result
8706 {
8707 multi_workspace_window
8708 .update(cx, move |multi_workspace, _window, cx| {
8709 struct OpenInWsl;
8710 let workspace = multi_workspace.workspace().clone();
8711 workspace.update(cx, |workspace, cx| {
8712 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
8713 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
8714 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
8715 cx.new(move |cx| {
8716 MessageNotification::new(msg, cx)
8717 .primary_message("Open in WSL")
8718 .primary_icon(IconName::FolderOpen)
8719 .primary_on_click(move |window, cx| {
8720 window.dispatch_action(Box::new(remote::OpenWslPath {
8721 distro: remote::WslConnectionOptions {
8722 distro_name: distro.clone(),
8723 user: None,
8724 },
8725 paths: vec![path.clone().into()],
8726 }), cx)
8727 })
8728 })
8729 });
8730 });
8731 })
8732 .unwrap();
8733 };
8734 result
8735 })
8736}
8737
8738pub fn open_new(
8739 open_options: OpenOptions,
8740 app_state: Arc<AppState>,
8741 cx: &mut App,
8742 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
8743) -> Task<anyhow::Result<()>> {
8744 let task = Workspace::new_local(
8745 Vec::new(),
8746 app_state,
8747 open_options.replace_window,
8748 open_options.env,
8749 Some(Box::new(init)),
8750 cx,
8751 );
8752 cx.spawn(async move |cx| {
8753 let (window, _opened_paths) = task.await?;
8754 window
8755 .update(cx, |_, window, _cx| {
8756 window.activate_window();
8757 })
8758 .ok();
8759 Ok(())
8760 })
8761}
8762
8763pub fn create_and_open_local_file(
8764 path: &'static Path,
8765 window: &mut Window,
8766 cx: &mut Context<Workspace>,
8767 default_content: impl 'static + Send + FnOnce() -> Rope,
8768) -> Task<Result<Box<dyn ItemHandle>>> {
8769 cx.spawn_in(window, async move |workspace, cx| {
8770 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
8771 if !fs.is_file(path).await {
8772 fs.create_file(path, Default::default()).await?;
8773 fs.save(path, &default_content(), Default::default())
8774 .await?;
8775 }
8776
8777 workspace
8778 .update_in(cx, |workspace, window, cx| {
8779 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
8780 let path = workspace
8781 .project
8782 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
8783 cx.spawn_in(window, async move |workspace, cx| {
8784 let path = path.await?;
8785 let mut items = workspace
8786 .update_in(cx, |workspace, window, cx| {
8787 workspace.open_paths(
8788 vec![path.to_path_buf()],
8789 OpenOptions {
8790 visible: Some(OpenVisible::None),
8791 ..Default::default()
8792 },
8793 None,
8794 window,
8795 cx,
8796 )
8797 })?
8798 .await;
8799 let item = items.pop().flatten();
8800 item.with_context(|| format!("path {path:?} is not a file"))?
8801 })
8802 })
8803 })?
8804 .await?
8805 .await
8806 })
8807}
8808
8809pub fn open_remote_project_with_new_connection(
8810 window: WindowHandle<MultiWorkspace>,
8811 remote_connection: Arc<dyn RemoteConnection>,
8812 cancel_rx: oneshot::Receiver<()>,
8813 delegate: Arc<dyn RemoteClientDelegate>,
8814 app_state: Arc<AppState>,
8815 paths: Vec<PathBuf>,
8816 cx: &mut App,
8817) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
8818 cx.spawn(async move |cx| {
8819 let (workspace_id, serialized_workspace) =
8820 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
8821 .await?;
8822
8823 let session = match cx
8824 .update(|cx| {
8825 remote::RemoteClient::new(
8826 ConnectionIdentifier::Workspace(workspace_id.0),
8827 remote_connection,
8828 cancel_rx,
8829 delegate,
8830 cx,
8831 )
8832 })
8833 .await?
8834 {
8835 Some(result) => result,
8836 None => return Ok(Vec::new()),
8837 };
8838
8839 let project = cx.update(|cx| {
8840 project::Project::remote(
8841 session,
8842 app_state.client.clone(),
8843 app_state.node_runtime.clone(),
8844 app_state.user_store.clone(),
8845 app_state.languages.clone(),
8846 app_state.fs.clone(),
8847 true,
8848 cx,
8849 )
8850 });
8851
8852 open_remote_project_inner(
8853 project,
8854 paths,
8855 workspace_id,
8856 serialized_workspace,
8857 app_state,
8858 window,
8859 cx,
8860 )
8861 .await
8862 })
8863}
8864
8865pub fn open_remote_project_with_existing_connection(
8866 connection_options: RemoteConnectionOptions,
8867 project: Entity<Project>,
8868 paths: Vec<PathBuf>,
8869 app_state: Arc<AppState>,
8870 window: WindowHandle<MultiWorkspace>,
8871 cx: &mut AsyncApp,
8872) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
8873 cx.spawn(async move |cx| {
8874 let (workspace_id, serialized_workspace) =
8875 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
8876
8877 open_remote_project_inner(
8878 project,
8879 paths,
8880 workspace_id,
8881 serialized_workspace,
8882 app_state,
8883 window,
8884 cx,
8885 )
8886 .await
8887 })
8888}
8889
8890async fn open_remote_project_inner(
8891 project: Entity<Project>,
8892 paths: Vec<PathBuf>,
8893 workspace_id: WorkspaceId,
8894 serialized_workspace: Option<SerializedWorkspace>,
8895 app_state: Arc<AppState>,
8896 window: WindowHandle<MultiWorkspace>,
8897 cx: &mut AsyncApp,
8898) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
8899 let toolchains = DB.toolchains(workspace_id).await?;
8900 for (toolchain, worktree_path, path) in toolchains {
8901 project
8902 .update(cx, |this, cx| {
8903 let Some(worktree_id) =
8904 this.find_worktree(&worktree_path, cx)
8905 .and_then(|(worktree, rel_path)| {
8906 if rel_path.is_empty() {
8907 Some(worktree.read(cx).id())
8908 } else {
8909 None
8910 }
8911 })
8912 else {
8913 return Task::ready(None);
8914 };
8915
8916 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
8917 })
8918 .await;
8919 }
8920 let mut project_paths_to_open = vec![];
8921 let mut project_path_errors = vec![];
8922
8923 for path in paths {
8924 let result = cx
8925 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
8926 .await;
8927 match result {
8928 Ok((_, project_path)) => {
8929 project_paths_to_open.push((path.clone(), Some(project_path)));
8930 }
8931 Err(error) => {
8932 project_path_errors.push(error);
8933 }
8934 };
8935 }
8936
8937 if project_paths_to_open.is_empty() {
8938 return Err(project_path_errors.pop().context("no paths given")?);
8939 }
8940
8941 let workspace = window.update(cx, |multi_workspace, window, cx| {
8942 telemetry::event!("SSH Project Opened");
8943
8944 let new_workspace = cx.new(|cx| {
8945 let mut workspace =
8946 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
8947 workspace.update_history(cx);
8948
8949 if let Some(ref serialized) = serialized_workspace {
8950 workspace.centered_layout = serialized.centered_layout;
8951 }
8952
8953 workspace
8954 });
8955
8956 multi_workspace.activate(new_workspace.clone(), cx);
8957 new_workspace
8958 })?;
8959
8960 let items = window
8961 .update(cx, |_, window, cx| {
8962 window.activate_window();
8963 workspace.update(cx, |_workspace, cx| {
8964 open_items(serialized_workspace, project_paths_to_open, window, cx)
8965 })
8966 })?
8967 .await?;
8968
8969 workspace.update(cx, |workspace, cx| {
8970 for error in project_path_errors {
8971 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
8972 if let Some(path) = error.error_tag("path") {
8973 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
8974 }
8975 } else {
8976 workspace.show_error(&error, cx)
8977 }
8978 }
8979 });
8980
8981 Ok(items.into_iter().map(|item| item?.ok()).collect())
8982}
8983
8984fn deserialize_remote_project(
8985 connection_options: RemoteConnectionOptions,
8986 paths: Vec<PathBuf>,
8987 cx: &AsyncApp,
8988) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
8989 cx.background_spawn(async move {
8990 let remote_connection_id = persistence::DB
8991 .get_or_create_remote_connection(connection_options)
8992 .await?;
8993
8994 let serialized_workspace =
8995 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
8996
8997 let workspace_id = if let Some(workspace_id) =
8998 serialized_workspace.as_ref().map(|workspace| workspace.id)
8999 {
9000 workspace_id
9001 } else {
9002 persistence::DB.next_id().await?
9003 };
9004
9005 Ok((workspace_id, serialized_workspace))
9006 })
9007}
9008
9009pub fn join_in_room_project(
9010 project_id: u64,
9011 follow_user_id: u64,
9012 app_state: Arc<AppState>,
9013 cx: &mut App,
9014) -> Task<Result<()>> {
9015 let windows = cx.windows();
9016 cx.spawn(async move |cx| {
9017 let existing_window_and_workspace: Option<(
9018 WindowHandle<MultiWorkspace>,
9019 Entity<Workspace>,
9020 )> = windows.into_iter().find_map(|window_handle| {
9021 window_handle
9022 .downcast::<MultiWorkspace>()
9023 .and_then(|window_handle| {
9024 window_handle
9025 .update(cx, |multi_workspace, _window, cx| {
9026 for workspace in multi_workspace.workspaces() {
9027 if workspace.read(cx).project().read(cx).remote_id()
9028 == Some(project_id)
9029 {
9030 return Some((window_handle, workspace.clone()));
9031 }
9032 }
9033 None
9034 })
9035 .unwrap_or(None)
9036 })
9037 });
9038
9039 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9040 existing_window_and_workspace
9041 {
9042 existing_window
9043 .update(cx, |multi_workspace, _, cx| {
9044 multi_workspace.activate(target_workspace, cx);
9045 })
9046 .ok();
9047 existing_window
9048 } else {
9049 let active_call = cx.update(|cx| ActiveCall::global(cx));
9050 let room = active_call
9051 .read_with(cx, |call, _| call.room().cloned())
9052 .context("not in a call")?;
9053 let project = room
9054 .update(cx, |room, cx| {
9055 room.join_project(
9056 project_id,
9057 app_state.languages.clone(),
9058 app_state.fs.clone(),
9059 cx,
9060 )
9061 })
9062 .await?;
9063
9064 let window_bounds_override = window_bounds_env_override();
9065 cx.update(|cx| {
9066 let mut options = (app_state.build_window_options)(None, cx);
9067 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9068 cx.open_window(options, |window, cx| {
9069 let workspace = cx.new(|cx| {
9070 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9071 });
9072 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9073 })
9074 })?
9075 };
9076
9077 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9078 cx.activate(true);
9079 window.activate_window();
9080
9081 // We set the active workspace above, so this is the correct workspace.
9082 let workspace = multi_workspace.workspace().clone();
9083 workspace.update(cx, |workspace, cx| {
9084 if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
9085 let follow_peer_id = room
9086 .read(cx)
9087 .remote_participants()
9088 .iter()
9089 .find(|(_, participant)| participant.user.id == follow_user_id)
9090 .map(|(_, p)| p.peer_id)
9091 .or_else(|| {
9092 // If we couldn't follow the given user, follow the host instead.
9093 let collaborator = workspace
9094 .project()
9095 .read(cx)
9096 .collaborators()
9097 .values()
9098 .find(|collaborator| collaborator.is_host)?;
9099 Some(collaborator.peer_id)
9100 });
9101
9102 if let Some(follow_peer_id) = follow_peer_id {
9103 workspace.follow(follow_peer_id, window, cx);
9104 }
9105 }
9106 });
9107 })?;
9108
9109 anyhow::Ok(())
9110 })
9111}
9112
9113pub fn reload(cx: &mut App) {
9114 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9115 let mut workspace_windows = cx
9116 .windows()
9117 .into_iter()
9118 .filter_map(|window| window.downcast::<MultiWorkspace>())
9119 .collect::<Vec<_>>();
9120
9121 // If multiple windows have unsaved changes, and need a save prompt,
9122 // prompt in the active window before switching to a different window.
9123 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9124
9125 let mut prompt = None;
9126 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9127 prompt = window
9128 .update(cx, |_, window, cx| {
9129 window.prompt(
9130 PromptLevel::Info,
9131 "Are you sure you want to restart?",
9132 None,
9133 &["Restart", "Cancel"],
9134 cx,
9135 )
9136 })
9137 .ok();
9138 }
9139
9140 cx.spawn(async move |cx| {
9141 if let Some(prompt) = prompt {
9142 let answer = prompt.await?;
9143 if answer != 0 {
9144 return anyhow::Ok(());
9145 }
9146 }
9147
9148 // If the user cancels any save prompt, then keep the app open.
9149 for window in workspace_windows {
9150 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9151 let workspace = multi_workspace.workspace().clone();
9152 workspace.update(cx, |workspace, cx| {
9153 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9154 })
9155 }) && !should_close.await?
9156 {
9157 return anyhow::Ok(());
9158 }
9159 }
9160 cx.update(|cx| cx.restart());
9161 anyhow::Ok(())
9162 })
9163 .detach_and_log_err(cx);
9164}
9165
9166fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9167 let mut parts = value.split(',');
9168 let x: usize = parts.next()?.parse().ok()?;
9169 let y: usize = parts.next()?.parse().ok()?;
9170 Some(point(px(x as f32), px(y as f32)))
9171}
9172
9173fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9174 let mut parts = value.split(',');
9175 let width: usize = parts.next()?.parse().ok()?;
9176 let height: usize = parts.next()?.parse().ok()?;
9177 Some(size(px(width as f32), px(height as f32)))
9178}
9179
9180/// Add client-side decorations (rounded corners, shadows, resize handling) when
9181/// appropriate.
9182///
9183/// The `border_radius_tiling` parameter allows overriding which corners get
9184/// rounded, independently of the actual window tiling state. This is used
9185/// specifically for the workspace switcher sidebar: when the sidebar is open,
9186/// we want square corners on the left (so the sidebar appears flush with the
9187/// window edge) but we still need the shadow padding for proper visual
9188/// appearance. Unlike actual window tiling, this only affects border radius -
9189/// not padding or shadows.
9190pub fn client_side_decorations(
9191 element: impl IntoElement,
9192 window: &mut Window,
9193 cx: &mut App,
9194 border_radius_tiling: Tiling,
9195) -> Stateful<Div> {
9196 const BORDER_SIZE: Pixels = px(1.0);
9197 let decorations = window.window_decorations();
9198 let tiling = match decorations {
9199 Decorations::Server => Tiling::default(),
9200 Decorations::Client { tiling } => tiling,
9201 };
9202
9203 match decorations {
9204 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9205 Decorations::Server => window.set_client_inset(px(0.0)),
9206 }
9207
9208 struct GlobalResizeEdge(ResizeEdge);
9209 impl Global for GlobalResizeEdge {}
9210
9211 div()
9212 .id("window-backdrop")
9213 .bg(transparent_black())
9214 .map(|div| match decorations {
9215 Decorations::Server => div,
9216 Decorations::Client { .. } => div
9217 .when(
9218 !(tiling.top
9219 || tiling.right
9220 || border_radius_tiling.top
9221 || border_radius_tiling.right),
9222 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9223 )
9224 .when(
9225 !(tiling.top
9226 || tiling.left
9227 || border_radius_tiling.top
9228 || border_radius_tiling.left),
9229 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9230 )
9231 .when(
9232 !(tiling.bottom
9233 || tiling.right
9234 || border_radius_tiling.bottom
9235 || border_radius_tiling.right),
9236 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9237 )
9238 .when(
9239 !(tiling.bottom
9240 || tiling.left
9241 || border_radius_tiling.bottom
9242 || border_radius_tiling.left),
9243 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9244 )
9245 .when(!tiling.top, |div| {
9246 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9247 })
9248 .when(!tiling.bottom, |div| {
9249 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9250 })
9251 .when(!tiling.left, |div| {
9252 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9253 })
9254 .when(!tiling.right, |div| {
9255 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9256 })
9257 .on_mouse_move(move |e, window, cx| {
9258 let size = window.window_bounds().get_bounds().size;
9259 let pos = e.position;
9260
9261 let new_edge =
9262 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9263
9264 let edge = cx.try_global::<GlobalResizeEdge>();
9265 if new_edge != edge.map(|edge| edge.0) {
9266 window
9267 .window_handle()
9268 .update(cx, |workspace, _, cx| {
9269 cx.notify(workspace.entity_id());
9270 })
9271 .ok();
9272 }
9273 })
9274 .on_mouse_down(MouseButton::Left, move |e, window, _| {
9275 let size = window.window_bounds().get_bounds().size;
9276 let pos = e.position;
9277
9278 let edge = match resize_edge(
9279 pos,
9280 theme::CLIENT_SIDE_DECORATION_SHADOW,
9281 size,
9282 tiling,
9283 ) {
9284 Some(value) => value,
9285 None => return,
9286 };
9287
9288 window.start_window_resize(edge);
9289 }),
9290 })
9291 .size_full()
9292 .child(
9293 div()
9294 .cursor(CursorStyle::Arrow)
9295 .map(|div| match decorations {
9296 Decorations::Server => div,
9297 Decorations::Client { .. } => div
9298 .border_color(cx.theme().colors().border)
9299 .when(
9300 !(tiling.top
9301 || tiling.right
9302 || border_radius_tiling.top
9303 || border_radius_tiling.right),
9304 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9305 )
9306 .when(
9307 !(tiling.top
9308 || tiling.left
9309 || border_radius_tiling.top
9310 || border_radius_tiling.left),
9311 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9312 )
9313 .when(
9314 !(tiling.bottom
9315 || tiling.right
9316 || border_radius_tiling.bottom
9317 || border_radius_tiling.right),
9318 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9319 )
9320 .when(
9321 !(tiling.bottom
9322 || tiling.left
9323 || border_radius_tiling.bottom
9324 || border_radius_tiling.left),
9325 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9326 )
9327 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
9328 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
9329 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
9330 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
9331 .when(!tiling.is_tiled(), |div| {
9332 div.shadow(vec![gpui::BoxShadow {
9333 color: Hsla {
9334 h: 0.,
9335 s: 0.,
9336 l: 0.,
9337 a: 0.4,
9338 },
9339 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
9340 spread_radius: px(0.),
9341 offset: point(px(0.0), px(0.0)),
9342 }])
9343 }),
9344 })
9345 .on_mouse_move(|_e, _, cx| {
9346 cx.stop_propagation();
9347 })
9348 .size_full()
9349 .child(element),
9350 )
9351 .map(|div| match decorations {
9352 Decorations::Server => div,
9353 Decorations::Client { tiling, .. } => div.child(
9354 canvas(
9355 |_bounds, window, _| {
9356 window.insert_hitbox(
9357 Bounds::new(
9358 point(px(0.0), px(0.0)),
9359 window.window_bounds().get_bounds().size,
9360 ),
9361 HitboxBehavior::Normal,
9362 )
9363 },
9364 move |_bounds, hitbox, window, cx| {
9365 let mouse = window.mouse_position();
9366 let size = window.window_bounds().get_bounds().size;
9367 let Some(edge) =
9368 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
9369 else {
9370 return;
9371 };
9372 cx.set_global(GlobalResizeEdge(edge));
9373 window.set_cursor_style(
9374 match edge {
9375 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
9376 ResizeEdge::Left | ResizeEdge::Right => {
9377 CursorStyle::ResizeLeftRight
9378 }
9379 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
9380 CursorStyle::ResizeUpLeftDownRight
9381 }
9382 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
9383 CursorStyle::ResizeUpRightDownLeft
9384 }
9385 },
9386 &hitbox,
9387 );
9388 },
9389 )
9390 .size_full()
9391 .absolute(),
9392 ),
9393 })
9394}
9395
9396fn resize_edge(
9397 pos: Point<Pixels>,
9398 shadow_size: Pixels,
9399 window_size: Size<Pixels>,
9400 tiling: Tiling,
9401) -> Option<ResizeEdge> {
9402 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
9403 if bounds.contains(&pos) {
9404 return None;
9405 }
9406
9407 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
9408 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
9409 if !tiling.top && top_left_bounds.contains(&pos) {
9410 return Some(ResizeEdge::TopLeft);
9411 }
9412
9413 let top_right_bounds = Bounds::new(
9414 Point::new(window_size.width - corner_size.width, px(0.)),
9415 corner_size,
9416 );
9417 if !tiling.top && top_right_bounds.contains(&pos) {
9418 return Some(ResizeEdge::TopRight);
9419 }
9420
9421 let bottom_left_bounds = Bounds::new(
9422 Point::new(px(0.), window_size.height - corner_size.height),
9423 corner_size,
9424 );
9425 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
9426 return Some(ResizeEdge::BottomLeft);
9427 }
9428
9429 let bottom_right_bounds = Bounds::new(
9430 Point::new(
9431 window_size.width - corner_size.width,
9432 window_size.height - corner_size.height,
9433 ),
9434 corner_size,
9435 );
9436 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
9437 return Some(ResizeEdge::BottomRight);
9438 }
9439
9440 if !tiling.top && pos.y < shadow_size {
9441 Some(ResizeEdge::Top)
9442 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
9443 Some(ResizeEdge::Bottom)
9444 } else if !tiling.left && pos.x < shadow_size {
9445 Some(ResizeEdge::Left)
9446 } else if !tiling.right && pos.x > window_size.width - shadow_size {
9447 Some(ResizeEdge::Right)
9448 } else {
9449 None
9450 }
9451}
9452
9453fn join_pane_into_active(
9454 active_pane: &Entity<Pane>,
9455 pane: &Entity<Pane>,
9456 window: &mut Window,
9457 cx: &mut App,
9458) {
9459 if pane == active_pane {
9460 } else if pane.read(cx).items_len() == 0 {
9461 pane.update(cx, |_, cx| {
9462 cx.emit(pane::Event::Remove {
9463 focus_on_pane: None,
9464 });
9465 })
9466 } else {
9467 move_all_items(pane, active_pane, window, cx);
9468 }
9469}
9470
9471fn move_all_items(
9472 from_pane: &Entity<Pane>,
9473 to_pane: &Entity<Pane>,
9474 window: &mut Window,
9475 cx: &mut App,
9476) {
9477 let destination_is_different = from_pane != to_pane;
9478 let mut moved_items = 0;
9479 for (item_ix, item_handle) in from_pane
9480 .read(cx)
9481 .items()
9482 .enumerate()
9483 .map(|(ix, item)| (ix, item.clone()))
9484 .collect::<Vec<_>>()
9485 {
9486 let ix = item_ix - moved_items;
9487 if destination_is_different {
9488 // Close item from previous pane
9489 from_pane.update(cx, |source, cx| {
9490 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
9491 });
9492 moved_items += 1;
9493 }
9494
9495 // This automatically removes duplicate items in the pane
9496 to_pane.update(cx, |destination, cx| {
9497 destination.add_item(item_handle, true, true, None, window, cx);
9498 window.focus(&destination.focus_handle(cx), cx)
9499 });
9500 }
9501}
9502
9503pub fn move_item(
9504 source: &Entity<Pane>,
9505 destination: &Entity<Pane>,
9506 item_id_to_move: EntityId,
9507 destination_index: usize,
9508 activate: bool,
9509 window: &mut Window,
9510 cx: &mut App,
9511) {
9512 let Some((item_ix, item_handle)) = source
9513 .read(cx)
9514 .items()
9515 .enumerate()
9516 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
9517 .map(|(ix, item)| (ix, item.clone()))
9518 else {
9519 // Tab was closed during drag
9520 return;
9521 };
9522
9523 if source != destination {
9524 // Close item from previous pane
9525 source.update(cx, |source, cx| {
9526 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
9527 });
9528 }
9529
9530 // This automatically removes duplicate items in the pane
9531 destination.update(cx, |destination, cx| {
9532 destination.add_item_inner(
9533 item_handle,
9534 activate,
9535 activate,
9536 activate,
9537 Some(destination_index),
9538 window,
9539 cx,
9540 );
9541 if activate {
9542 window.focus(&destination.focus_handle(cx), cx)
9543 }
9544 });
9545}
9546
9547pub fn move_active_item(
9548 source: &Entity<Pane>,
9549 destination: &Entity<Pane>,
9550 focus_destination: bool,
9551 close_if_empty: bool,
9552 window: &mut Window,
9553 cx: &mut App,
9554) {
9555 if source == destination {
9556 return;
9557 }
9558 let Some(active_item) = source.read(cx).active_item() else {
9559 return;
9560 };
9561 source.update(cx, |source_pane, cx| {
9562 let item_id = active_item.item_id();
9563 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
9564 destination.update(cx, |target_pane, cx| {
9565 target_pane.add_item(
9566 active_item,
9567 focus_destination,
9568 focus_destination,
9569 Some(target_pane.items_len()),
9570 window,
9571 cx,
9572 );
9573 });
9574 });
9575}
9576
9577pub fn clone_active_item(
9578 workspace_id: Option<WorkspaceId>,
9579 source: &Entity<Pane>,
9580 destination: &Entity<Pane>,
9581 focus_destination: bool,
9582 window: &mut Window,
9583 cx: &mut App,
9584) {
9585 if source == destination {
9586 return;
9587 }
9588 let Some(active_item) = source.read(cx).active_item() else {
9589 return;
9590 };
9591 if !active_item.can_split(cx) {
9592 return;
9593 }
9594 let destination = destination.downgrade();
9595 let task = active_item.clone_on_split(workspace_id, window, cx);
9596 window
9597 .spawn(cx, async move |cx| {
9598 let Some(clone) = task.await else {
9599 return;
9600 };
9601 destination
9602 .update_in(cx, |target_pane, window, cx| {
9603 target_pane.add_item(
9604 clone,
9605 focus_destination,
9606 focus_destination,
9607 Some(target_pane.items_len()),
9608 window,
9609 cx,
9610 );
9611 })
9612 .log_err();
9613 })
9614 .detach();
9615}
9616
9617#[derive(Debug)]
9618pub struct WorkspacePosition {
9619 pub window_bounds: Option<WindowBounds>,
9620 pub display: Option<Uuid>,
9621 pub centered_layout: bool,
9622}
9623
9624pub fn remote_workspace_position_from_db(
9625 connection_options: RemoteConnectionOptions,
9626 paths_to_open: &[PathBuf],
9627 cx: &App,
9628) -> Task<Result<WorkspacePosition>> {
9629 let paths = paths_to_open.to_vec();
9630
9631 cx.background_spawn(async move {
9632 let remote_connection_id = persistence::DB
9633 .get_or_create_remote_connection(connection_options)
9634 .await
9635 .context("fetching serialized ssh project")?;
9636 let serialized_workspace =
9637 persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
9638
9639 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
9640 (Some(WindowBounds::Windowed(bounds)), None)
9641 } else {
9642 let restorable_bounds = serialized_workspace
9643 .as_ref()
9644 .and_then(|workspace| {
9645 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
9646 })
9647 .or_else(|| persistence::read_default_window_bounds());
9648
9649 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
9650 (Some(serialized_bounds), Some(serialized_display))
9651 } else {
9652 (None, None)
9653 }
9654 };
9655
9656 let centered_layout = serialized_workspace
9657 .as_ref()
9658 .map(|w| w.centered_layout)
9659 .unwrap_or(false);
9660
9661 Ok(WorkspacePosition {
9662 window_bounds,
9663 display,
9664 centered_layout,
9665 })
9666 })
9667}
9668
9669pub fn with_active_or_new_workspace(
9670 cx: &mut App,
9671 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
9672) {
9673 match cx
9674 .active_window()
9675 .and_then(|w| w.downcast::<MultiWorkspace>())
9676 {
9677 Some(multi_workspace) => {
9678 cx.defer(move |cx| {
9679 multi_workspace
9680 .update(cx, |multi_workspace, window, cx| {
9681 let workspace = multi_workspace.workspace().clone();
9682 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
9683 })
9684 .log_err();
9685 });
9686 }
9687 None => {
9688 let app_state = AppState::global(cx);
9689 if let Some(app_state) = app_state.upgrade() {
9690 open_new(
9691 OpenOptions::default(),
9692 app_state,
9693 cx,
9694 move |workspace, window, cx| f(workspace, window, cx),
9695 )
9696 .detach_and_log_err(cx);
9697 }
9698 }
9699 }
9700}
9701
9702#[cfg(test)]
9703mod tests {
9704 use std::{cell::RefCell, rc::Rc};
9705
9706 use super::*;
9707 use crate::{
9708 dock::{PanelEvent, test::TestPanel},
9709 item::{
9710 ItemBufferKind, ItemEvent,
9711 test::{TestItem, TestProjectItem},
9712 },
9713 };
9714 use fs::FakeFs;
9715 use gpui::{
9716 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
9717 UpdateGlobal, VisualTestContext, px,
9718 };
9719 use project::{Project, ProjectEntryId};
9720 use serde_json::json;
9721 use settings::SettingsStore;
9722 use util::rel_path::rel_path;
9723
9724 #[gpui::test]
9725 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
9726 init_test(cx);
9727
9728 let fs = FakeFs::new(cx.executor());
9729 let project = Project::test(fs, [], cx).await;
9730 let (workspace, cx) =
9731 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9732
9733 // Adding an item with no ambiguity renders the tab without detail.
9734 let item1 = cx.new(|cx| {
9735 let mut item = TestItem::new(cx);
9736 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
9737 item
9738 });
9739 workspace.update_in(cx, |workspace, window, cx| {
9740 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
9741 });
9742 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
9743
9744 // Adding an item that creates ambiguity increases the level of detail on
9745 // both tabs.
9746 let item2 = cx.new_window_entity(|_window, cx| {
9747 let mut item = TestItem::new(cx);
9748 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
9749 item
9750 });
9751 workspace.update_in(cx, |workspace, window, cx| {
9752 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9753 });
9754 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
9755 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
9756
9757 // Adding an item that creates ambiguity increases the level of detail only
9758 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
9759 // we stop at the highest detail available.
9760 let item3 = cx.new(|cx| {
9761 let mut item = TestItem::new(cx);
9762 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
9763 item
9764 });
9765 workspace.update_in(cx, |workspace, window, cx| {
9766 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
9767 });
9768 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
9769 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
9770 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
9771 }
9772
9773 #[gpui::test]
9774 async fn test_tracking_active_path(cx: &mut TestAppContext) {
9775 init_test(cx);
9776
9777 let fs = FakeFs::new(cx.executor());
9778 fs.insert_tree(
9779 "/root1",
9780 json!({
9781 "one.txt": "",
9782 "two.txt": "",
9783 }),
9784 )
9785 .await;
9786 fs.insert_tree(
9787 "/root2",
9788 json!({
9789 "three.txt": "",
9790 }),
9791 )
9792 .await;
9793
9794 let project = Project::test(fs, ["root1".as_ref()], cx).await;
9795 let (workspace, cx) =
9796 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9797 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9798 let worktree_id = project.update(cx, |project, cx| {
9799 project.worktrees(cx).next().unwrap().read(cx).id()
9800 });
9801
9802 let item1 = cx.new(|cx| {
9803 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
9804 });
9805 let item2 = cx.new(|cx| {
9806 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
9807 });
9808
9809 // Add an item to an empty pane
9810 workspace.update_in(cx, |workspace, window, cx| {
9811 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
9812 });
9813 project.update(cx, |project, cx| {
9814 assert_eq!(
9815 project.active_entry(),
9816 project
9817 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
9818 .map(|e| e.id)
9819 );
9820 });
9821 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
9822
9823 // Add a second item to a non-empty pane
9824 workspace.update_in(cx, |workspace, window, cx| {
9825 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
9826 });
9827 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
9828 project.update(cx, |project, cx| {
9829 assert_eq!(
9830 project.active_entry(),
9831 project
9832 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
9833 .map(|e| e.id)
9834 );
9835 });
9836
9837 // Close the active item
9838 pane.update_in(cx, |pane, window, cx| {
9839 pane.close_active_item(&Default::default(), window, cx)
9840 })
9841 .await
9842 .unwrap();
9843 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
9844 project.update(cx, |project, cx| {
9845 assert_eq!(
9846 project.active_entry(),
9847 project
9848 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
9849 .map(|e| e.id)
9850 );
9851 });
9852
9853 // Add a project folder
9854 project
9855 .update(cx, |project, cx| {
9856 project.find_or_create_worktree("root2", true, cx)
9857 })
9858 .await
9859 .unwrap();
9860 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
9861
9862 // Remove a project folder
9863 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
9864 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
9865 }
9866
9867 #[gpui::test]
9868 async fn test_close_window(cx: &mut TestAppContext) {
9869 init_test(cx);
9870
9871 let fs = FakeFs::new(cx.executor());
9872 fs.insert_tree("/root", json!({ "one": "" })).await;
9873
9874 let project = Project::test(fs, ["root".as_ref()], cx).await;
9875 let (workspace, cx) =
9876 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9877
9878 // When there are no dirty items, there's nothing to do.
9879 let item1 = cx.new(TestItem::new);
9880 workspace.update_in(cx, |w, window, cx| {
9881 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
9882 });
9883 let task = workspace.update_in(cx, |w, window, cx| {
9884 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
9885 });
9886 assert!(task.await.unwrap());
9887
9888 // When there are dirty untitled items, prompt to save each one. If the user
9889 // cancels any prompt, then abort.
9890 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
9891 let item3 = cx.new(|cx| {
9892 TestItem::new(cx)
9893 .with_dirty(true)
9894 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
9895 });
9896 workspace.update_in(cx, |w, window, cx| {
9897 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9898 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
9899 });
9900 let task = workspace.update_in(cx, |w, window, cx| {
9901 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
9902 });
9903 cx.executor().run_until_parked();
9904 cx.simulate_prompt_answer("Cancel"); // cancel save all
9905 cx.executor().run_until_parked();
9906 assert!(!cx.has_pending_prompt());
9907 assert!(!task.await.unwrap());
9908 }
9909
9910 #[gpui::test]
9911 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
9912 init_test(cx);
9913
9914 // Register TestItem as a serializable item
9915 cx.update(|cx| {
9916 register_serializable_item::<TestItem>(cx);
9917 });
9918
9919 let fs = FakeFs::new(cx.executor());
9920 fs.insert_tree("/root", json!({ "one": "" })).await;
9921
9922 let project = Project::test(fs, ["root".as_ref()], cx).await;
9923 let (workspace, cx) =
9924 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9925
9926 // When there are dirty untitled items, but they can serialize, then there is no prompt.
9927 let item1 = cx.new(|cx| {
9928 TestItem::new(cx)
9929 .with_dirty(true)
9930 .with_serialize(|| Some(Task::ready(Ok(()))))
9931 });
9932 let item2 = cx.new(|cx| {
9933 TestItem::new(cx)
9934 .with_dirty(true)
9935 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
9936 .with_serialize(|| Some(Task::ready(Ok(()))))
9937 });
9938 workspace.update_in(cx, |w, window, cx| {
9939 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
9940 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9941 });
9942 let task = workspace.update_in(cx, |w, window, cx| {
9943 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
9944 });
9945 assert!(task.await.unwrap());
9946 }
9947
9948 #[gpui::test]
9949 async fn test_close_pane_items(cx: &mut TestAppContext) {
9950 init_test(cx);
9951
9952 let fs = FakeFs::new(cx.executor());
9953
9954 let project = Project::test(fs, None, cx).await;
9955 let (workspace, cx) =
9956 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9957
9958 let item1 = cx.new(|cx| {
9959 TestItem::new(cx)
9960 .with_dirty(true)
9961 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
9962 });
9963 let item2 = cx.new(|cx| {
9964 TestItem::new(cx)
9965 .with_dirty(true)
9966 .with_conflict(true)
9967 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
9968 });
9969 let item3 = cx.new(|cx| {
9970 TestItem::new(cx)
9971 .with_dirty(true)
9972 .with_conflict(true)
9973 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
9974 });
9975 let item4 = cx.new(|cx| {
9976 TestItem::new(cx).with_dirty(true).with_project_items(&[{
9977 let project_item = TestProjectItem::new_untitled(cx);
9978 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
9979 project_item
9980 }])
9981 });
9982 let pane = workspace.update_in(cx, |workspace, window, cx| {
9983 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
9984 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
9985 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
9986 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
9987 workspace.active_pane().clone()
9988 });
9989
9990 let close_items = pane.update_in(cx, |pane, window, cx| {
9991 pane.activate_item(1, true, true, window, cx);
9992 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
9993 let item1_id = item1.item_id();
9994 let item3_id = item3.item_id();
9995 let item4_id = item4.item_id();
9996 pane.close_items(window, cx, SaveIntent::Close, move |id| {
9997 [item1_id, item3_id, item4_id].contains(&id)
9998 })
9999 });
10000 cx.executor().run_until_parked();
10001
10002 assert!(cx.has_pending_prompt());
10003 cx.simulate_prompt_answer("Save all");
10004
10005 cx.executor().run_until_parked();
10006
10007 // Item 1 is saved. There's a prompt to save item 3.
10008 pane.update(cx, |pane, cx| {
10009 assert_eq!(item1.read(cx).save_count, 1);
10010 assert_eq!(item1.read(cx).save_as_count, 0);
10011 assert_eq!(item1.read(cx).reload_count, 0);
10012 assert_eq!(pane.items_len(), 3);
10013 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10014 });
10015 assert!(cx.has_pending_prompt());
10016
10017 // Cancel saving item 3.
10018 cx.simulate_prompt_answer("Discard");
10019 cx.executor().run_until_parked();
10020
10021 // Item 3 is reloaded. There's a prompt to save item 4.
10022 pane.update(cx, |pane, cx| {
10023 assert_eq!(item3.read(cx).save_count, 0);
10024 assert_eq!(item3.read(cx).save_as_count, 0);
10025 assert_eq!(item3.read(cx).reload_count, 1);
10026 assert_eq!(pane.items_len(), 2);
10027 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10028 });
10029
10030 // There's a prompt for a path for item 4.
10031 cx.simulate_new_path_selection(|_| Some(Default::default()));
10032 close_items.await.unwrap();
10033
10034 // The requested items are closed.
10035 pane.update(cx, |pane, cx| {
10036 assert_eq!(item4.read(cx).save_count, 0);
10037 assert_eq!(item4.read(cx).save_as_count, 1);
10038 assert_eq!(item4.read(cx).reload_count, 0);
10039 assert_eq!(pane.items_len(), 1);
10040 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10041 });
10042 }
10043
10044 #[gpui::test]
10045 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10046 init_test(cx);
10047
10048 let fs = FakeFs::new(cx.executor());
10049 let project = Project::test(fs, [], cx).await;
10050 let (workspace, cx) =
10051 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10052
10053 // Create several workspace items with single project entries, and two
10054 // workspace items with multiple project entries.
10055 let single_entry_items = (0..=4)
10056 .map(|project_entry_id| {
10057 cx.new(|cx| {
10058 TestItem::new(cx)
10059 .with_dirty(true)
10060 .with_project_items(&[dirty_project_item(
10061 project_entry_id,
10062 &format!("{project_entry_id}.txt"),
10063 cx,
10064 )])
10065 })
10066 })
10067 .collect::<Vec<_>>();
10068 let item_2_3 = cx.new(|cx| {
10069 TestItem::new(cx)
10070 .with_dirty(true)
10071 .with_buffer_kind(ItemBufferKind::Multibuffer)
10072 .with_project_items(&[
10073 single_entry_items[2].read(cx).project_items[0].clone(),
10074 single_entry_items[3].read(cx).project_items[0].clone(),
10075 ])
10076 });
10077 let item_3_4 = cx.new(|cx| {
10078 TestItem::new(cx)
10079 .with_dirty(true)
10080 .with_buffer_kind(ItemBufferKind::Multibuffer)
10081 .with_project_items(&[
10082 single_entry_items[3].read(cx).project_items[0].clone(),
10083 single_entry_items[4].read(cx).project_items[0].clone(),
10084 ])
10085 });
10086
10087 // Create two panes that contain the following project entries:
10088 // left pane:
10089 // multi-entry items: (2, 3)
10090 // single-entry items: 0, 2, 3, 4
10091 // right pane:
10092 // single-entry items: 4, 1
10093 // multi-entry items: (3, 4)
10094 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10095 let left_pane = workspace.active_pane().clone();
10096 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10097 workspace.add_item_to_active_pane(
10098 single_entry_items[0].boxed_clone(),
10099 None,
10100 true,
10101 window,
10102 cx,
10103 );
10104 workspace.add_item_to_active_pane(
10105 single_entry_items[2].boxed_clone(),
10106 None,
10107 true,
10108 window,
10109 cx,
10110 );
10111 workspace.add_item_to_active_pane(
10112 single_entry_items[3].boxed_clone(),
10113 None,
10114 true,
10115 window,
10116 cx,
10117 );
10118 workspace.add_item_to_active_pane(
10119 single_entry_items[4].boxed_clone(),
10120 None,
10121 true,
10122 window,
10123 cx,
10124 );
10125
10126 let right_pane =
10127 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10128
10129 let boxed_clone = single_entry_items[1].boxed_clone();
10130 let right_pane = window.spawn(cx, async move |cx| {
10131 right_pane.await.inspect(|right_pane| {
10132 right_pane
10133 .update_in(cx, |pane, window, cx| {
10134 pane.add_item(boxed_clone, true, true, None, window, cx);
10135 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10136 })
10137 .unwrap();
10138 })
10139 });
10140
10141 (left_pane, right_pane)
10142 });
10143 let right_pane = right_pane.await.unwrap();
10144 cx.focus(&right_pane);
10145
10146 let close = right_pane.update_in(cx, |pane, window, cx| {
10147 pane.close_all_items(&CloseAllItems::default(), window, cx)
10148 .unwrap()
10149 });
10150 cx.executor().run_until_parked();
10151
10152 let msg = cx.pending_prompt().unwrap().0;
10153 assert!(msg.contains("1.txt"));
10154 assert!(!msg.contains("2.txt"));
10155 assert!(!msg.contains("3.txt"));
10156 assert!(!msg.contains("4.txt"));
10157
10158 // With best-effort close, cancelling item 1 keeps it open but items 4
10159 // and (3,4) still close since their entries exist in left pane.
10160 cx.simulate_prompt_answer("Cancel");
10161 close.await;
10162
10163 right_pane.read_with(cx, |pane, _| {
10164 assert_eq!(pane.items_len(), 1);
10165 });
10166
10167 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10168 left_pane
10169 .update_in(cx, |left_pane, window, cx| {
10170 left_pane.close_item_by_id(
10171 single_entry_items[3].entity_id(),
10172 SaveIntent::Skip,
10173 window,
10174 cx,
10175 )
10176 })
10177 .await
10178 .unwrap();
10179
10180 let close = left_pane.update_in(cx, |pane, window, cx| {
10181 pane.close_all_items(&CloseAllItems::default(), window, cx)
10182 .unwrap()
10183 });
10184 cx.executor().run_until_parked();
10185
10186 let details = cx.pending_prompt().unwrap().1;
10187 assert!(details.contains("0.txt"));
10188 assert!(details.contains("3.txt"));
10189 assert!(details.contains("4.txt"));
10190 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10191 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10192 // assert!(!details.contains("2.txt"));
10193
10194 cx.simulate_prompt_answer("Save all");
10195 cx.executor().run_until_parked();
10196 close.await;
10197
10198 left_pane.read_with(cx, |pane, _| {
10199 assert_eq!(pane.items_len(), 0);
10200 });
10201 }
10202
10203 #[gpui::test]
10204 async fn test_autosave(cx: &mut gpui::TestAppContext) {
10205 init_test(cx);
10206
10207 let fs = FakeFs::new(cx.executor());
10208 let project = Project::test(fs, [], cx).await;
10209 let (workspace, cx) =
10210 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10211 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10212
10213 let item = cx.new(|cx| {
10214 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10215 });
10216 let item_id = item.entity_id();
10217 workspace.update_in(cx, |workspace, window, cx| {
10218 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10219 });
10220
10221 // Autosave on window change.
10222 item.update(cx, |item, cx| {
10223 SettingsStore::update_global(cx, |settings, cx| {
10224 settings.update_user_settings(cx, |settings| {
10225 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10226 })
10227 });
10228 item.is_dirty = true;
10229 });
10230
10231 // Deactivating the window saves the file.
10232 cx.deactivate_window();
10233 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10234
10235 // Re-activating the window doesn't save the file.
10236 cx.update(|window, _| window.activate_window());
10237 cx.executor().run_until_parked();
10238 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10239
10240 // Autosave on focus change.
10241 item.update_in(cx, |item, window, cx| {
10242 cx.focus_self(window);
10243 SettingsStore::update_global(cx, |settings, cx| {
10244 settings.update_user_settings(cx, |settings| {
10245 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10246 })
10247 });
10248 item.is_dirty = true;
10249 });
10250 // Blurring the item saves the file.
10251 item.update_in(cx, |_, window, _| window.blur());
10252 cx.executor().run_until_parked();
10253 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10254
10255 // Deactivating the window still saves the file.
10256 item.update_in(cx, |item, window, cx| {
10257 cx.focus_self(window);
10258 item.is_dirty = true;
10259 });
10260 cx.deactivate_window();
10261 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10262
10263 // Autosave after delay.
10264 item.update(cx, |item, cx| {
10265 SettingsStore::update_global(cx, |settings, cx| {
10266 settings.update_user_settings(cx, |settings| {
10267 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10268 milliseconds: 500.into(),
10269 });
10270 })
10271 });
10272 item.is_dirty = true;
10273 cx.emit(ItemEvent::Edit);
10274 });
10275
10276 // Delay hasn't fully expired, so the file is still dirty and unsaved.
10277 cx.executor().advance_clock(Duration::from_millis(250));
10278 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10279
10280 // After delay expires, the file is saved.
10281 cx.executor().advance_clock(Duration::from_millis(250));
10282 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10283
10284 // Autosave after delay, should save earlier than delay if tab is closed
10285 item.update(cx, |item, cx| {
10286 item.is_dirty = true;
10287 cx.emit(ItemEvent::Edit);
10288 });
10289 cx.executor().advance_clock(Duration::from_millis(250));
10290 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10291
10292 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10293 pane.update_in(cx, |pane, window, cx| {
10294 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
10295 })
10296 .await
10297 .unwrap();
10298 assert!(!cx.has_pending_prompt());
10299 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10300
10301 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10302 workspace.update_in(cx, |workspace, window, cx| {
10303 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10304 });
10305 item.update_in(cx, |item, _window, cx| {
10306 item.is_dirty = true;
10307 for project_item in &mut item.project_items {
10308 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10309 }
10310 });
10311 cx.run_until_parked();
10312 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10313
10314 // Autosave on focus change, ensuring closing the tab counts as such.
10315 item.update(cx, |item, cx| {
10316 SettingsStore::update_global(cx, |settings, cx| {
10317 settings.update_user_settings(cx, |settings| {
10318 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10319 })
10320 });
10321 item.is_dirty = true;
10322 for project_item in &mut item.project_items {
10323 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10324 }
10325 });
10326
10327 pane.update_in(cx, |pane, window, cx| {
10328 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
10329 })
10330 .await
10331 .unwrap();
10332 assert!(!cx.has_pending_prompt());
10333 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10334
10335 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10336 workspace.update_in(cx, |workspace, window, cx| {
10337 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10338 });
10339 item.update_in(cx, |item, window, cx| {
10340 item.project_items[0].update(cx, |item, _| {
10341 item.entry_id = None;
10342 });
10343 item.is_dirty = true;
10344 window.blur();
10345 });
10346 cx.run_until_parked();
10347 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10348
10349 // Ensure autosave is prevented for deleted files also when closing the buffer.
10350 let _close_items = pane.update_in(cx, |pane, window, cx| {
10351 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
10352 });
10353 cx.run_until_parked();
10354 assert!(cx.has_pending_prompt());
10355 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10356 }
10357
10358 #[gpui::test]
10359 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10360 init_test(cx);
10361
10362 let fs = FakeFs::new(cx.executor());
10363
10364 let project = Project::test(fs, [], cx).await;
10365 let (workspace, cx) =
10366 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10367
10368 let item = cx.new(|cx| {
10369 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10370 });
10371 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10372 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10373 let toolbar_notify_count = Rc::new(RefCell::new(0));
10374
10375 workspace.update_in(cx, |workspace, window, cx| {
10376 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10377 let toolbar_notification_count = toolbar_notify_count.clone();
10378 cx.observe_in(&toolbar, window, move |_, _, _, _| {
10379 *toolbar_notification_count.borrow_mut() += 1
10380 })
10381 .detach();
10382 });
10383
10384 pane.read_with(cx, |pane, _| {
10385 assert!(!pane.can_navigate_backward());
10386 assert!(!pane.can_navigate_forward());
10387 });
10388
10389 item.update_in(cx, |item, _, cx| {
10390 item.set_state("one".to_string(), cx);
10391 });
10392
10393 // Toolbar must be notified to re-render the navigation buttons
10394 assert_eq!(*toolbar_notify_count.borrow(), 1);
10395
10396 pane.read_with(cx, |pane, _| {
10397 assert!(pane.can_navigate_backward());
10398 assert!(!pane.can_navigate_forward());
10399 });
10400
10401 workspace
10402 .update_in(cx, |workspace, window, cx| {
10403 workspace.go_back(pane.downgrade(), window, cx)
10404 })
10405 .await
10406 .unwrap();
10407
10408 assert_eq!(*toolbar_notify_count.borrow(), 2);
10409 pane.read_with(cx, |pane, _| {
10410 assert!(!pane.can_navigate_backward());
10411 assert!(pane.can_navigate_forward());
10412 });
10413 }
10414
10415 #[gpui::test]
10416 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
10417 init_test(cx);
10418 let fs = FakeFs::new(cx.executor());
10419
10420 let project = Project::test(fs, [], cx).await;
10421 let (workspace, cx) =
10422 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10423
10424 let panel = workspace.update_in(cx, |workspace, window, cx| {
10425 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10426 workspace.add_panel(panel.clone(), window, cx);
10427
10428 workspace
10429 .right_dock()
10430 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10431
10432 panel
10433 });
10434
10435 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10436 pane.update_in(cx, |pane, window, cx| {
10437 let item = cx.new(TestItem::new);
10438 pane.add_item(Box::new(item), true, true, None, window, cx);
10439 });
10440
10441 // Transfer focus from center to panel
10442 workspace.update_in(cx, |workspace, window, cx| {
10443 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10444 });
10445
10446 workspace.update_in(cx, |workspace, window, cx| {
10447 assert!(workspace.right_dock().read(cx).is_open());
10448 assert!(!panel.is_zoomed(window, cx));
10449 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10450 });
10451
10452 // Transfer focus from panel to center
10453 workspace.update_in(cx, |workspace, window, cx| {
10454 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10455 });
10456
10457 workspace.update_in(cx, |workspace, window, cx| {
10458 assert!(workspace.right_dock().read(cx).is_open());
10459 assert!(!panel.is_zoomed(window, cx));
10460 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10461 });
10462
10463 // Close the dock
10464 workspace.update_in(cx, |workspace, window, cx| {
10465 workspace.toggle_dock(DockPosition::Right, window, cx);
10466 });
10467
10468 workspace.update_in(cx, |workspace, window, cx| {
10469 assert!(!workspace.right_dock().read(cx).is_open());
10470 assert!(!panel.is_zoomed(window, cx));
10471 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10472 });
10473
10474 // Open the dock
10475 workspace.update_in(cx, |workspace, window, cx| {
10476 workspace.toggle_dock(DockPosition::Right, 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 // Focus and zoom panel
10486 panel.update_in(cx, |panel, window, cx| {
10487 cx.focus_self(window);
10488 panel.set_zoomed(true, window, cx)
10489 });
10490
10491 workspace.update_in(cx, |workspace, window, cx| {
10492 assert!(workspace.right_dock().read(cx).is_open());
10493 assert!(panel.is_zoomed(window, cx));
10494 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10495 });
10496
10497 // Transfer focus to the center closes the dock
10498 workspace.update_in(cx, |workspace, window, cx| {
10499 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10500 });
10501
10502 workspace.update_in(cx, |workspace, window, cx| {
10503 assert!(!workspace.right_dock().read(cx).is_open());
10504 assert!(panel.is_zoomed(window, cx));
10505 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10506 });
10507
10508 // Transferring focus back to the panel keeps it zoomed
10509 workspace.update_in(cx, |workspace, window, cx| {
10510 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10511 });
10512
10513 workspace.update_in(cx, |workspace, window, cx| {
10514 assert!(workspace.right_dock().read(cx).is_open());
10515 assert!(panel.is_zoomed(window, cx));
10516 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10517 });
10518
10519 // Close the dock while it is zoomed
10520 workspace.update_in(cx, |workspace, window, cx| {
10521 workspace.toggle_dock(DockPosition::Right, 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!(workspace.zoomed.is_none());
10528 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10529 });
10530
10531 // Opening the dock, when it's zoomed, retains focus
10532 workspace.update_in(cx, |workspace, window, cx| {
10533 workspace.toggle_dock(DockPosition::Right, window, cx)
10534 });
10535
10536 workspace.update_in(cx, |workspace, window, cx| {
10537 assert!(workspace.right_dock().read(cx).is_open());
10538 assert!(panel.is_zoomed(window, cx));
10539 assert!(workspace.zoomed.is_some());
10540 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10541 });
10542
10543 // Unzoom and close the panel, zoom the active pane.
10544 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
10545 workspace.update_in(cx, |workspace, window, cx| {
10546 workspace.toggle_dock(DockPosition::Right, window, cx)
10547 });
10548 pane.update_in(cx, |pane, window, cx| {
10549 pane.toggle_zoom(&Default::default(), window, cx)
10550 });
10551
10552 // Opening a dock unzooms the pane.
10553 workspace.update_in(cx, |workspace, window, cx| {
10554 workspace.toggle_dock(DockPosition::Right, window, cx)
10555 });
10556 workspace.update_in(cx, |workspace, window, cx| {
10557 let pane = pane.read(cx);
10558 assert!(!pane.is_zoomed());
10559 assert!(!pane.focus_handle(cx).is_focused(window));
10560 assert!(workspace.right_dock().read(cx).is_open());
10561 assert!(workspace.zoomed.is_none());
10562 });
10563 }
10564
10565 #[gpui::test]
10566 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
10567 init_test(cx);
10568 let fs = FakeFs::new(cx.executor());
10569
10570 let project = Project::test(fs, [], cx).await;
10571 let (workspace, cx) =
10572 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10573
10574 let panel = workspace.update_in(cx, |workspace, window, cx| {
10575 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
10576 workspace.add_panel(panel.clone(), window, cx);
10577 panel
10578 });
10579
10580 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10581 pane.update_in(cx, |pane, window, cx| {
10582 let item = cx.new(TestItem::new);
10583 pane.add_item(Box::new(item), true, true, None, window, cx);
10584 });
10585
10586 // Enable close_panel_on_toggle
10587 cx.update_global(|store: &mut SettingsStore, cx| {
10588 store.update_user_settings(cx, |settings| {
10589 settings.workspace.close_panel_on_toggle = Some(true);
10590 });
10591 });
10592
10593 // Panel starts closed. Toggling should open and focus it.
10594 workspace.update_in(cx, |workspace, window, cx| {
10595 assert!(!workspace.right_dock().read(cx).is_open());
10596 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10597 });
10598
10599 workspace.update_in(cx, |workspace, window, cx| {
10600 assert!(
10601 workspace.right_dock().read(cx).is_open(),
10602 "Dock should be open after toggling from center"
10603 );
10604 assert!(
10605 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10606 "Panel should be focused after toggling from center"
10607 );
10608 });
10609
10610 // Panel is open and focused. Toggling should close the panel and
10611 // return focus to the center.
10612 workspace.update_in(cx, |workspace, window, cx| {
10613 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10614 });
10615
10616 workspace.update_in(cx, |workspace, window, cx| {
10617 assert!(
10618 !workspace.right_dock().read(cx).is_open(),
10619 "Dock should be closed after toggling from focused panel"
10620 );
10621 assert!(
10622 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10623 "Panel should not be focused after toggling from focused panel"
10624 );
10625 });
10626
10627 // Open the dock and focus something else so the panel is open but not
10628 // focused. Toggling should focus the panel (not close it).
10629 workspace.update_in(cx, |workspace, window, cx| {
10630 workspace
10631 .right_dock()
10632 .update(cx, |dock, cx| dock.set_open(true, window, cx));
10633 window.focus(&pane.read(cx).focus_handle(cx), cx);
10634 });
10635
10636 workspace.update_in(cx, |workspace, window, cx| {
10637 assert!(workspace.right_dock().read(cx).is_open());
10638 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
10639 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10640 });
10641
10642 workspace.update_in(cx, |workspace, window, cx| {
10643 assert!(
10644 workspace.right_dock().read(cx).is_open(),
10645 "Dock should remain open when toggling focuses an open-but-unfocused panel"
10646 );
10647 assert!(
10648 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10649 "Panel should be focused after toggling an open-but-unfocused panel"
10650 );
10651 });
10652
10653 // Now disable the setting and verify the original behavior: toggling
10654 // from a focused panel moves focus to center but leaves the dock open.
10655 cx.update_global(|store: &mut SettingsStore, cx| {
10656 store.update_user_settings(cx, |settings| {
10657 settings.workspace.close_panel_on_toggle = Some(false);
10658 });
10659 });
10660
10661 workspace.update_in(cx, |workspace, window, cx| {
10662 workspace.toggle_panel_focus::<TestPanel>(window, cx);
10663 });
10664
10665 workspace.update_in(cx, |workspace, window, cx| {
10666 assert!(
10667 workspace.right_dock().read(cx).is_open(),
10668 "Dock should remain open when setting is disabled"
10669 );
10670 assert!(
10671 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
10672 "Panel should not be focused after toggling with setting disabled"
10673 );
10674 });
10675 }
10676
10677 #[gpui::test]
10678 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
10679 init_test(cx);
10680 let fs = FakeFs::new(cx.executor());
10681
10682 let project = Project::test(fs, [], cx).await;
10683 let (workspace, cx) =
10684 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10685
10686 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
10687 workspace.active_pane().clone()
10688 });
10689
10690 // Add an item to the pane so it can be zoomed
10691 workspace.update_in(cx, |workspace, window, cx| {
10692 let item = cx.new(TestItem::new);
10693 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
10694 });
10695
10696 // Initially not zoomed
10697 workspace.update_in(cx, |workspace, _window, cx| {
10698 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
10699 assert!(
10700 workspace.zoomed.is_none(),
10701 "Workspace should track no zoomed pane"
10702 );
10703 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
10704 });
10705
10706 // Zoom In
10707 pane.update_in(cx, |pane, window, cx| {
10708 pane.zoom_in(&crate::ZoomIn, window, cx);
10709 });
10710
10711 workspace.update_in(cx, |workspace, window, cx| {
10712 assert!(
10713 pane.read(cx).is_zoomed(),
10714 "Pane should be zoomed after ZoomIn"
10715 );
10716 assert!(
10717 workspace.zoomed.is_some(),
10718 "Workspace should track the zoomed pane"
10719 );
10720 assert!(
10721 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
10722 "ZoomIn should focus the pane"
10723 );
10724 });
10725
10726 // Zoom In again is a no-op
10727 pane.update_in(cx, |pane, window, cx| {
10728 pane.zoom_in(&crate::ZoomIn, window, cx);
10729 });
10730
10731 workspace.update_in(cx, |workspace, window, cx| {
10732 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
10733 assert!(
10734 workspace.zoomed.is_some(),
10735 "Workspace still tracks zoomed pane"
10736 );
10737 assert!(
10738 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
10739 "Pane remains focused after repeated ZoomIn"
10740 );
10741 });
10742
10743 // Zoom Out
10744 pane.update_in(cx, |pane, window, cx| {
10745 pane.zoom_out(&crate::ZoomOut, window, cx);
10746 });
10747
10748 workspace.update_in(cx, |workspace, _window, cx| {
10749 assert!(
10750 !pane.read(cx).is_zoomed(),
10751 "Pane should unzoom after ZoomOut"
10752 );
10753 assert!(
10754 workspace.zoomed.is_none(),
10755 "Workspace clears zoom tracking after ZoomOut"
10756 );
10757 });
10758
10759 // Zoom Out again is a no-op
10760 pane.update_in(cx, |pane, window, cx| {
10761 pane.zoom_out(&crate::ZoomOut, window, cx);
10762 });
10763
10764 workspace.update_in(cx, |workspace, _window, cx| {
10765 assert!(
10766 !pane.read(cx).is_zoomed(),
10767 "Second ZoomOut keeps pane unzoomed"
10768 );
10769 assert!(
10770 workspace.zoomed.is_none(),
10771 "Workspace remains without zoomed pane"
10772 );
10773 });
10774 }
10775
10776 #[gpui::test]
10777 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
10778 init_test(cx);
10779 let fs = FakeFs::new(cx.executor());
10780
10781 let project = Project::test(fs, [], cx).await;
10782 let (workspace, cx) =
10783 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10784 workspace.update_in(cx, |workspace, window, cx| {
10785 // Open two docks
10786 let left_dock = workspace.dock_at_position(DockPosition::Left);
10787 let right_dock = workspace.dock_at_position(DockPosition::Right);
10788
10789 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10790 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10791
10792 assert!(left_dock.read(cx).is_open());
10793 assert!(right_dock.read(cx).is_open());
10794 });
10795
10796 workspace.update_in(cx, |workspace, window, cx| {
10797 // Toggle all docks - should close both
10798 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10799
10800 let left_dock = workspace.dock_at_position(DockPosition::Left);
10801 let right_dock = workspace.dock_at_position(DockPosition::Right);
10802 assert!(!left_dock.read(cx).is_open());
10803 assert!(!right_dock.read(cx).is_open());
10804 });
10805
10806 workspace.update_in(cx, |workspace, window, cx| {
10807 // Toggle again - should reopen both
10808 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10809
10810 let left_dock = workspace.dock_at_position(DockPosition::Left);
10811 let right_dock = workspace.dock_at_position(DockPosition::Right);
10812 assert!(left_dock.read(cx).is_open());
10813 assert!(right_dock.read(cx).is_open());
10814 });
10815 }
10816
10817 #[gpui::test]
10818 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
10819 init_test(cx);
10820 let fs = FakeFs::new(cx.executor());
10821
10822 let project = Project::test(fs, [], cx).await;
10823 let (workspace, cx) =
10824 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10825 workspace.update_in(cx, |workspace, window, cx| {
10826 // Open two docks
10827 let left_dock = workspace.dock_at_position(DockPosition::Left);
10828 let right_dock = workspace.dock_at_position(DockPosition::Right);
10829
10830 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10831 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
10832
10833 assert!(left_dock.read(cx).is_open());
10834 assert!(right_dock.read(cx).is_open());
10835 });
10836
10837 workspace.update_in(cx, |workspace, window, cx| {
10838 // Close them manually
10839 workspace.toggle_dock(DockPosition::Left, window, cx);
10840 workspace.toggle_dock(DockPosition::Right, window, cx);
10841
10842 let left_dock = workspace.dock_at_position(DockPosition::Left);
10843 let right_dock = workspace.dock_at_position(DockPosition::Right);
10844 assert!(!left_dock.read(cx).is_open());
10845 assert!(!right_dock.read(cx).is_open());
10846 });
10847
10848 workspace.update_in(cx, |workspace, window, cx| {
10849 // Toggle all docks - only last closed (right dock) should reopen
10850 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10851
10852 let left_dock = workspace.dock_at_position(DockPosition::Left);
10853 let right_dock = workspace.dock_at_position(DockPosition::Right);
10854 assert!(!left_dock.read(cx).is_open());
10855 assert!(right_dock.read(cx).is_open());
10856 });
10857 }
10858
10859 #[gpui::test]
10860 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
10861 init_test(cx);
10862 let fs = FakeFs::new(cx.executor());
10863 let project = Project::test(fs, [], cx).await;
10864 let (workspace, cx) =
10865 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10866
10867 // Open two docks (left and right) with one panel each
10868 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
10869 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
10870 workspace.add_panel(left_panel.clone(), window, cx);
10871
10872 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
10873 workspace.add_panel(right_panel.clone(), window, cx);
10874
10875 workspace.toggle_dock(DockPosition::Left, window, cx);
10876 workspace.toggle_dock(DockPosition::Right, window, cx);
10877
10878 // Verify initial state
10879 assert!(
10880 workspace.left_dock().read(cx).is_open(),
10881 "Left dock should be open"
10882 );
10883 assert_eq!(
10884 workspace
10885 .left_dock()
10886 .read(cx)
10887 .visible_panel()
10888 .unwrap()
10889 .panel_id(),
10890 left_panel.panel_id(),
10891 "Left panel should be visible in left dock"
10892 );
10893 assert!(
10894 workspace.right_dock().read(cx).is_open(),
10895 "Right dock should be open"
10896 );
10897 assert_eq!(
10898 workspace
10899 .right_dock()
10900 .read(cx)
10901 .visible_panel()
10902 .unwrap()
10903 .panel_id(),
10904 right_panel.panel_id(),
10905 "Right panel should be visible in right dock"
10906 );
10907 assert!(
10908 !workspace.bottom_dock().read(cx).is_open(),
10909 "Bottom dock should be closed"
10910 );
10911
10912 (left_panel, right_panel)
10913 });
10914
10915 // Focus the left panel and move it to the next position (bottom dock)
10916 workspace.update_in(cx, |workspace, window, cx| {
10917 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
10918 assert!(
10919 left_panel.read(cx).focus_handle(cx).is_focused(window),
10920 "Left panel should be focused"
10921 );
10922 });
10923
10924 cx.dispatch_action(MoveFocusedPanelToNextPosition);
10925
10926 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
10927 workspace.update(cx, |workspace, cx| {
10928 assert!(
10929 !workspace.left_dock().read(cx).is_open(),
10930 "Left dock should be closed"
10931 );
10932 assert!(
10933 workspace.bottom_dock().read(cx).is_open(),
10934 "Bottom dock should now be open"
10935 );
10936 assert_eq!(
10937 left_panel.read(cx).position,
10938 DockPosition::Bottom,
10939 "Left panel should now be in the bottom dock"
10940 );
10941 assert_eq!(
10942 workspace
10943 .bottom_dock()
10944 .read(cx)
10945 .visible_panel()
10946 .unwrap()
10947 .panel_id(),
10948 left_panel.panel_id(),
10949 "Left panel should be the visible panel in the bottom dock"
10950 );
10951 });
10952
10953 // Toggle all docks off
10954 workspace.update_in(cx, |workspace, window, cx| {
10955 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10956 assert!(
10957 !workspace.left_dock().read(cx).is_open(),
10958 "Left dock should be closed"
10959 );
10960 assert!(
10961 !workspace.right_dock().read(cx).is_open(),
10962 "Right dock should be closed"
10963 );
10964 assert!(
10965 !workspace.bottom_dock().read(cx).is_open(),
10966 "Bottom dock should be closed"
10967 );
10968 });
10969
10970 // Toggle all docks back on and verify positions are restored
10971 workspace.update_in(cx, |workspace, window, cx| {
10972 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
10973 assert!(
10974 !workspace.left_dock().read(cx).is_open(),
10975 "Left dock should remain closed"
10976 );
10977 assert!(
10978 workspace.right_dock().read(cx).is_open(),
10979 "Right dock should remain open"
10980 );
10981 assert!(
10982 workspace.bottom_dock().read(cx).is_open(),
10983 "Bottom dock should remain open"
10984 );
10985 assert_eq!(
10986 left_panel.read(cx).position,
10987 DockPosition::Bottom,
10988 "Left panel should remain in the bottom dock"
10989 );
10990 assert_eq!(
10991 right_panel.read(cx).position,
10992 DockPosition::Right,
10993 "Right panel should remain in the right dock"
10994 );
10995 assert_eq!(
10996 workspace
10997 .bottom_dock()
10998 .read(cx)
10999 .visible_panel()
11000 .unwrap()
11001 .panel_id(),
11002 left_panel.panel_id(),
11003 "Left panel should be the visible panel in the right dock"
11004 );
11005 });
11006 }
11007
11008 #[gpui::test]
11009 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11010 init_test(cx);
11011
11012 let fs = FakeFs::new(cx.executor());
11013
11014 let project = Project::test(fs, None, cx).await;
11015 let (workspace, cx) =
11016 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11017
11018 // Let's arrange the panes like this:
11019 //
11020 // +-----------------------+
11021 // | top |
11022 // +------+--------+-------+
11023 // | left | center | right |
11024 // +------+--------+-------+
11025 // | bottom |
11026 // +-----------------------+
11027
11028 let top_item = cx.new(|cx| {
11029 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11030 });
11031 let bottom_item = cx.new(|cx| {
11032 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11033 });
11034 let left_item = cx.new(|cx| {
11035 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11036 });
11037 let right_item = cx.new(|cx| {
11038 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11039 });
11040 let center_item = cx.new(|cx| {
11041 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11042 });
11043
11044 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11045 let top_pane_id = workspace.active_pane().entity_id();
11046 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11047 workspace.split_pane(
11048 workspace.active_pane().clone(),
11049 SplitDirection::Down,
11050 window,
11051 cx,
11052 );
11053 top_pane_id
11054 });
11055 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11056 let bottom_pane_id = workspace.active_pane().entity_id();
11057 workspace.add_item_to_active_pane(
11058 Box::new(bottom_item.clone()),
11059 None,
11060 false,
11061 window,
11062 cx,
11063 );
11064 workspace.split_pane(
11065 workspace.active_pane().clone(),
11066 SplitDirection::Up,
11067 window,
11068 cx,
11069 );
11070 bottom_pane_id
11071 });
11072 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11073 let left_pane_id = workspace.active_pane().entity_id();
11074 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11075 workspace.split_pane(
11076 workspace.active_pane().clone(),
11077 SplitDirection::Right,
11078 window,
11079 cx,
11080 );
11081 left_pane_id
11082 });
11083 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11084 let right_pane_id = workspace.active_pane().entity_id();
11085 workspace.add_item_to_active_pane(
11086 Box::new(right_item.clone()),
11087 None,
11088 false,
11089 window,
11090 cx,
11091 );
11092 workspace.split_pane(
11093 workspace.active_pane().clone(),
11094 SplitDirection::Left,
11095 window,
11096 cx,
11097 );
11098 right_pane_id
11099 });
11100 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11101 let center_pane_id = workspace.active_pane().entity_id();
11102 workspace.add_item_to_active_pane(
11103 Box::new(center_item.clone()),
11104 None,
11105 false,
11106 window,
11107 cx,
11108 );
11109 center_pane_id
11110 });
11111 cx.executor().run_until_parked();
11112
11113 workspace.update_in(cx, |workspace, window, cx| {
11114 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11115
11116 // Join into next from center pane into right
11117 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11118 });
11119
11120 workspace.update_in(cx, |workspace, window, cx| {
11121 let active_pane = workspace.active_pane();
11122 assert_eq!(right_pane_id, active_pane.entity_id());
11123 assert_eq!(2, active_pane.read(cx).items_len());
11124 let item_ids_in_pane =
11125 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11126 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11127 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11128
11129 // Join into next from right pane into bottom
11130 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11131 });
11132
11133 workspace.update_in(cx, |workspace, window, cx| {
11134 let active_pane = workspace.active_pane();
11135 assert_eq!(bottom_pane_id, active_pane.entity_id());
11136 assert_eq!(3, active_pane.read(cx).items_len());
11137 let item_ids_in_pane =
11138 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11139 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11140 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11141 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11142
11143 // Join into next from bottom pane into left
11144 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11145 });
11146
11147 workspace.update_in(cx, |workspace, window, cx| {
11148 let active_pane = workspace.active_pane();
11149 assert_eq!(left_pane_id, active_pane.entity_id());
11150 assert_eq!(4, active_pane.read(cx).items_len());
11151 let item_ids_in_pane =
11152 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11153 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11154 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11155 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11156 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11157
11158 // Join into next from left pane into top
11159 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11160 });
11161
11162 workspace.update_in(cx, |workspace, window, cx| {
11163 let active_pane = workspace.active_pane();
11164 assert_eq!(top_pane_id, active_pane.entity_id());
11165 assert_eq!(5, active_pane.read(cx).items_len());
11166 let item_ids_in_pane =
11167 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11168 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11169 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11170 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11171 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11172 assert!(item_ids_in_pane.contains(&top_item.item_id()));
11173
11174 // Single pane left: no-op
11175 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11176 });
11177
11178 workspace.update(cx, |workspace, _cx| {
11179 let active_pane = workspace.active_pane();
11180 assert_eq!(top_pane_id, active_pane.entity_id());
11181 });
11182 }
11183
11184 fn add_an_item_to_active_pane(
11185 cx: &mut VisualTestContext,
11186 workspace: &Entity<Workspace>,
11187 item_id: u64,
11188 ) -> Entity<TestItem> {
11189 let item = cx.new(|cx| {
11190 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11191 item_id,
11192 "item{item_id}.txt",
11193 cx,
11194 )])
11195 });
11196 workspace.update_in(cx, |workspace, window, cx| {
11197 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11198 });
11199 item
11200 }
11201
11202 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11203 workspace.update_in(cx, |workspace, window, cx| {
11204 workspace.split_pane(
11205 workspace.active_pane().clone(),
11206 SplitDirection::Right,
11207 window,
11208 cx,
11209 )
11210 })
11211 }
11212
11213 #[gpui::test]
11214 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11215 init_test(cx);
11216 let fs = FakeFs::new(cx.executor());
11217 let project = Project::test(fs, None, cx).await;
11218 let (workspace, cx) =
11219 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11220
11221 add_an_item_to_active_pane(cx, &workspace, 1);
11222 split_pane(cx, &workspace);
11223 add_an_item_to_active_pane(cx, &workspace, 2);
11224 split_pane(cx, &workspace); // empty pane
11225 split_pane(cx, &workspace);
11226 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11227
11228 cx.executor().run_until_parked();
11229
11230 workspace.update(cx, |workspace, cx| {
11231 let num_panes = workspace.panes().len();
11232 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11233 let active_item = workspace
11234 .active_pane()
11235 .read(cx)
11236 .active_item()
11237 .expect("item is in focus");
11238
11239 assert_eq!(num_panes, 4);
11240 assert_eq!(num_items_in_current_pane, 1);
11241 assert_eq!(active_item.item_id(), last_item.item_id());
11242 });
11243
11244 workspace.update_in(cx, |workspace, window, cx| {
11245 workspace.join_all_panes(window, cx);
11246 });
11247
11248 workspace.update(cx, |workspace, cx| {
11249 let num_panes = workspace.panes().len();
11250 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11251 let active_item = workspace
11252 .active_pane()
11253 .read(cx)
11254 .active_item()
11255 .expect("item is in focus");
11256
11257 assert_eq!(num_panes, 1);
11258 assert_eq!(num_items_in_current_pane, 3);
11259 assert_eq!(active_item.item_id(), last_item.item_id());
11260 });
11261 }
11262 struct TestModal(FocusHandle);
11263
11264 impl TestModal {
11265 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11266 Self(cx.focus_handle())
11267 }
11268 }
11269
11270 impl EventEmitter<DismissEvent> for TestModal {}
11271
11272 impl Focusable for TestModal {
11273 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11274 self.0.clone()
11275 }
11276 }
11277
11278 impl ModalView for TestModal {}
11279
11280 impl Render for TestModal {
11281 fn render(
11282 &mut self,
11283 _window: &mut Window,
11284 _cx: &mut Context<TestModal>,
11285 ) -> impl IntoElement {
11286 div().track_focus(&self.0)
11287 }
11288 }
11289
11290 #[gpui::test]
11291 async fn test_panels(cx: &mut gpui::TestAppContext) {
11292 init_test(cx);
11293 let fs = FakeFs::new(cx.executor());
11294
11295 let project = Project::test(fs, [], cx).await;
11296 let (workspace, cx) =
11297 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11298
11299 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11300 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11301 workspace.add_panel(panel_1.clone(), window, cx);
11302 workspace.toggle_dock(DockPosition::Left, window, cx);
11303 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11304 workspace.add_panel(panel_2.clone(), window, cx);
11305 workspace.toggle_dock(DockPosition::Right, window, cx);
11306
11307 let left_dock = workspace.left_dock();
11308 assert_eq!(
11309 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11310 panel_1.panel_id()
11311 );
11312 assert_eq!(
11313 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11314 panel_1.size(window, cx)
11315 );
11316
11317 left_dock.update(cx, |left_dock, cx| {
11318 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11319 });
11320 assert_eq!(
11321 workspace
11322 .right_dock()
11323 .read(cx)
11324 .visible_panel()
11325 .unwrap()
11326 .panel_id(),
11327 panel_2.panel_id(),
11328 );
11329
11330 (panel_1, panel_2)
11331 });
11332
11333 // Move panel_1 to the right
11334 panel_1.update_in(cx, |panel_1, window, cx| {
11335 panel_1.set_position(DockPosition::Right, window, cx)
11336 });
11337
11338 workspace.update_in(cx, |workspace, window, cx| {
11339 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11340 // Since it was the only panel on the left, the left dock should now be closed.
11341 assert!(!workspace.left_dock().read(cx).is_open());
11342 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11343 let right_dock = workspace.right_dock();
11344 assert_eq!(
11345 right_dock.read(cx).visible_panel().unwrap().panel_id(),
11346 panel_1.panel_id()
11347 );
11348 assert_eq!(
11349 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11350 px(1337.)
11351 );
11352
11353 // Now we move panel_2 to the left
11354 panel_2.set_position(DockPosition::Left, window, cx);
11355 });
11356
11357 workspace.update(cx, |workspace, cx| {
11358 // Since panel_2 was not visible on the right, we don't open the left dock.
11359 assert!(!workspace.left_dock().read(cx).is_open());
11360 // And the right dock is unaffected in its displaying of panel_1
11361 assert!(workspace.right_dock().read(cx).is_open());
11362 assert_eq!(
11363 workspace
11364 .right_dock()
11365 .read(cx)
11366 .visible_panel()
11367 .unwrap()
11368 .panel_id(),
11369 panel_1.panel_id(),
11370 );
11371 });
11372
11373 // Move panel_1 back to the left
11374 panel_1.update_in(cx, |panel_1, window, cx| {
11375 panel_1.set_position(DockPosition::Left, window, cx)
11376 });
11377
11378 workspace.update_in(cx, |workspace, window, cx| {
11379 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
11380 let left_dock = workspace.left_dock();
11381 assert!(left_dock.read(cx).is_open());
11382 assert_eq!(
11383 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11384 panel_1.panel_id()
11385 );
11386 assert_eq!(
11387 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11388 px(1337.)
11389 );
11390 // And the right dock should be closed as it no longer has any panels.
11391 assert!(!workspace.right_dock().read(cx).is_open());
11392
11393 // Now we move panel_1 to the bottom
11394 panel_1.set_position(DockPosition::Bottom, window, cx);
11395 });
11396
11397 workspace.update_in(cx, |workspace, window, cx| {
11398 // Since panel_1 was visible on the left, we close the left dock.
11399 assert!(!workspace.left_dock().read(cx).is_open());
11400 // The bottom dock is sized based on the panel's default size,
11401 // since the panel orientation changed from vertical to horizontal.
11402 let bottom_dock = workspace.bottom_dock();
11403 assert_eq!(
11404 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
11405 panel_1.size(window, cx),
11406 );
11407 // Close bottom dock and move panel_1 back to the left.
11408 bottom_dock.update(cx, |bottom_dock, cx| {
11409 bottom_dock.set_open(false, window, cx)
11410 });
11411 panel_1.set_position(DockPosition::Left, window, cx);
11412 });
11413
11414 // Emit activated event on panel 1
11415 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
11416
11417 // Now the left dock is open and panel_1 is active and focused.
11418 workspace.update_in(cx, |workspace, window, cx| {
11419 let left_dock = workspace.left_dock();
11420 assert!(left_dock.read(cx).is_open());
11421 assert_eq!(
11422 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11423 panel_1.panel_id(),
11424 );
11425 assert!(panel_1.focus_handle(cx).is_focused(window));
11426 });
11427
11428 // Emit closed event on panel 2, which is not active
11429 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11430
11431 // Wo don't close the left dock, because panel_2 wasn't the active panel
11432 workspace.update(cx, |workspace, cx| {
11433 let left_dock = workspace.left_dock();
11434 assert!(left_dock.read(cx).is_open());
11435 assert_eq!(
11436 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11437 panel_1.panel_id(),
11438 );
11439 });
11440
11441 // Emitting a ZoomIn event shows the panel as zoomed.
11442 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
11443 workspace.read_with(cx, |workspace, _| {
11444 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11445 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
11446 });
11447
11448 // Move panel to another dock while it is zoomed
11449 panel_1.update_in(cx, |panel, window, cx| {
11450 panel.set_position(DockPosition::Right, window, cx)
11451 });
11452 workspace.read_with(cx, |workspace, _| {
11453 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11454
11455 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11456 });
11457
11458 // This is a helper for getting a:
11459 // - valid focus on an element,
11460 // - that isn't a part of the panes and panels system of the Workspace,
11461 // - and doesn't trigger the 'on_focus_lost' API.
11462 let focus_other_view = {
11463 let workspace = workspace.clone();
11464 move |cx: &mut VisualTestContext| {
11465 workspace.update_in(cx, |workspace, window, cx| {
11466 if workspace.active_modal::<TestModal>(cx).is_some() {
11467 workspace.toggle_modal(window, cx, TestModal::new);
11468 workspace.toggle_modal(window, cx, TestModal::new);
11469 } else {
11470 workspace.toggle_modal(window, cx, TestModal::new);
11471 }
11472 })
11473 }
11474 };
11475
11476 // If focus is transferred to another view that's not a panel or another pane, we still show
11477 // the panel as zoomed.
11478 focus_other_view(cx);
11479 workspace.read_with(cx, |workspace, _| {
11480 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11481 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11482 });
11483
11484 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
11485 workspace.update_in(cx, |_workspace, window, cx| {
11486 cx.focus_self(window);
11487 });
11488 workspace.read_with(cx, |workspace, _| {
11489 assert_eq!(workspace.zoomed, None);
11490 assert_eq!(workspace.zoomed_position, None);
11491 });
11492
11493 // If focus is transferred again to another view that's not a panel or a pane, we won't
11494 // show the panel as zoomed because it wasn't zoomed before.
11495 focus_other_view(cx);
11496 workspace.read_with(cx, |workspace, _| {
11497 assert_eq!(workspace.zoomed, None);
11498 assert_eq!(workspace.zoomed_position, None);
11499 });
11500
11501 // When the panel is activated, it is zoomed again.
11502 cx.dispatch_action(ToggleRightDock);
11503 workspace.read_with(cx, |workspace, _| {
11504 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
11505 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
11506 });
11507
11508 // Emitting a ZoomOut event unzooms the panel.
11509 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
11510 workspace.read_with(cx, |workspace, _| {
11511 assert_eq!(workspace.zoomed, None);
11512 assert_eq!(workspace.zoomed_position, None);
11513 });
11514
11515 // Emit closed event on panel 1, which is active
11516 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
11517
11518 // Now the left dock is closed, because panel_1 was the active panel
11519 workspace.update(cx, |workspace, cx| {
11520 let right_dock = workspace.right_dock();
11521 assert!(!right_dock.read(cx).is_open());
11522 });
11523 }
11524
11525 #[gpui::test]
11526 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
11527 init_test(cx);
11528
11529 let fs = FakeFs::new(cx.background_executor.clone());
11530 let project = Project::test(fs, [], cx).await;
11531 let (workspace, cx) =
11532 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11533 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11534
11535 let dirty_regular_buffer = cx.new(|cx| {
11536 TestItem::new(cx)
11537 .with_dirty(true)
11538 .with_label("1.txt")
11539 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11540 });
11541 let dirty_regular_buffer_2 = cx.new(|cx| {
11542 TestItem::new(cx)
11543 .with_dirty(true)
11544 .with_label("2.txt")
11545 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11546 });
11547 let dirty_multi_buffer_with_both = cx.new(|cx| {
11548 TestItem::new(cx)
11549 .with_dirty(true)
11550 .with_buffer_kind(ItemBufferKind::Multibuffer)
11551 .with_label("Fake Project Search")
11552 .with_project_items(&[
11553 dirty_regular_buffer.read(cx).project_items[0].clone(),
11554 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11555 ])
11556 });
11557 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11558 workspace.update_in(cx, |workspace, window, cx| {
11559 workspace.add_item(
11560 pane.clone(),
11561 Box::new(dirty_regular_buffer.clone()),
11562 None,
11563 false,
11564 false,
11565 window,
11566 cx,
11567 );
11568 workspace.add_item(
11569 pane.clone(),
11570 Box::new(dirty_regular_buffer_2.clone()),
11571 None,
11572 false,
11573 false,
11574 window,
11575 cx,
11576 );
11577 workspace.add_item(
11578 pane.clone(),
11579 Box::new(dirty_multi_buffer_with_both.clone()),
11580 None,
11581 false,
11582 false,
11583 window,
11584 cx,
11585 );
11586 });
11587
11588 pane.update_in(cx, |pane, window, cx| {
11589 pane.activate_item(2, true, true, window, cx);
11590 assert_eq!(
11591 pane.active_item().unwrap().item_id(),
11592 multi_buffer_with_both_files_id,
11593 "Should select the multi buffer in the pane"
11594 );
11595 });
11596 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11597 pane.close_other_items(
11598 &CloseOtherItems {
11599 save_intent: Some(SaveIntent::Save),
11600 close_pinned: true,
11601 },
11602 None,
11603 window,
11604 cx,
11605 )
11606 });
11607 cx.background_executor.run_until_parked();
11608 assert!(!cx.has_pending_prompt());
11609 close_all_but_multi_buffer_task
11610 .await
11611 .expect("Closing all buffers but the multi buffer failed");
11612 pane.update(cx, |pane, cx| {
11613 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
11614 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
11615 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
11616 assert_eq!(pane.items_len(), 1);
11617 assert_eq!(
11618 pane.active_item().unwrap().item_id(),
11619 multi_buffer_with_both_files_id,
11620 "Should have only the multi buffer left in the pane"
11621 );
11622 assert!(
11623 dirty_multi_buffer_with_both.read(cx).is_dirty,
11624 "The multi buffer containing the unsaved buffer should still be dirty"
11625 );
11626 });
11627
11628 dirty_regular_buffer.update(cx, |buffer, cx| {
11629 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
11630 });
11631
11632 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11633 pane.close_active_item(
11634 &CloseActiveItem {
11635 save_intent: Some(SaveIntent::Close),
11636 close_pinned: false,
11637 },
11638 window,
11639 cx,
11640 )
11641 });
11642 cx.background_executor.run_until_parked();
11643 assert!(
11644 cx.has_pending_prompt(),
11645 "Dirty multi buffer should prompt a save dialog"
11646 );
11647 cx.simulate_prompt_answer("Save");
11648 cx.background_executor.run_until_parked();
11649 close_multi_buffer_task
11650 .await
11651 .expect("Closing the multi buffer failed");
11652 pane.update(cx, |pane, cx| {
11653 assert_eq!(
11654 dirty_multi_buffer_with_both.read(cx).save_count,
11655 1,
11656 "Multi buffer item should get be saved"
11657 );
11658 // Test impl does not save inner items, so we do not assert them
11659 assert_eq!(
11660 pane.items_len(),
11661 0,
11662 "No more items should be left in the pane"
11663 );
11664 assert!(pane.active_item().is_none());
11665 });
11666 }
11667
11668 #[gpui::test]
11669 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
11670 cx: &mut TestAppContext,
11671 ) {
11672 init_test(cx);
11673
11674 let fs = FakeFs::new(cx.background_executor.clone());
11675 let project = Project::test(fs, [], cx).await;
11676 let (workspace, cx) =
11677 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11678 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11679
11680 let dirty_regular_buffer = cx.new(|cx| {
11681 TestItem::new(cx)
11682 .with_dirty(true)
11683 .with_label("1.txt")
11684 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11685 });
11686 let dirty_regular_buffer_2 = cx.new(|cx| {
11687 TestItem::new(cx)
11688 .with_dirty(true)
11689 .with_label("2.txt")
11690 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11691 });
11692 let clear_regular_buffer = cx.new(|cx| {
11693 TestItem::new(cx)
11694 .with_label("3.txt")
11695 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
11696 });
11697
11698 let dirty_multi_buffer_with_both = cx.new(|cx| {
11699 TestItem::new(cx)
11700 .with_dirty(true)
11701 .with_buffer_kind(ItemBufferKind::Multibuffer)
11702 .with_label("Fake Project Search")
11703 .with_project_items(&[
11704 dirty_regular_buffer.read(cx).project_items[0].clone(),
11705 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11706 clear_regular_buffer.read(cx).project_items[0].clone(),
11707 ])
11708 });
11709 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
11710 workspace.update_in(cx, |workspace, window, cx| {
11711 workspace.add_item(
11712 pane.clone(),
11713 Box::new(dirty_regular_buffer.clone()),
11714 None,
11715 false,
11716 false,
11717 window,
11718 cx,
11719 );
11720 workspace.add_item(
11721 pane.clone(),
11722 Box::new(dirty_multi_buffer_with_both.clone()),
11723 None,
11724 false,
11725 false,
11726 window,
11727 cx,
11728 );
11729 });
11730
11731 pane.update_in(cx, |pane, window, cx| {
11732 pane.activate_item(1, true, true, window, cx);
11733 assert_eq!(
11734 pane.active_item().unwrap().item_id(),
11735 multi_buffer_with_both_files_id,
11736 "Should select the multi buffer in the pane"
11737 );
11738 });
11739 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11740 pane.close_active_item(
11741 &CloseActiveItem {
11742 save_intent: None,
11743 close_pinned: false,
11744 },
11745 window,
11746 cx,
11747 )
11748 });
11749 cx.background_executor.run_until_parked();
11750 assert!(
11751 cx.has_pending_prompt(),
11752 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
11753 );
11754 }
11755
11756 /// Tests that when `close_on_file_delete` is enabled, files are automatically
11757 /// closed when they are deleted from disk.
11758 #[gpui::test]
11759 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
11760 init_test(cx);
11761
11762 // Enable the close_on_disk_deletion setting
11763 cx.update_global(|store: &mut SettingsStore, cx| {
11764 store.update_user_settings(cx, |settings| {
11765 settings.workspace.close_on_file_delete = Some(true);
11766 });
11767 });
11768
11769 let fs = FakeFs::new(cx.background_executor.clone());
11770 let project = Project::test(fs, [], cx).await;
11771 let (workspace, cx) =
11772 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11773 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11774
11775 // Create a test item that simulates a file
11776 let item = cx.new(|cx| {
11777 TestItem::new(cx)
11778 .with_label("test.txt")
11779 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11780 });
11781
11782 // Add item to workspace
11783 workspace.update_in(cx, |workspace, window, cx| {
11784 workspace.add_item(
11785 pane.clone(),
11786 Box::new(item.clone()),
11787 None,
11788 false,
11789 false,
11790 window,
11791 cx,
11792 );
11793 });
11794
11795 // Verify the item is in the pane
11796 pane.read_with(cx, |pane, _| {
11797 assert_eq!(pane.items().count(), 1);
11798 });
11799
11800 // Simulate file deletion by setting the item's deleted state
11801 item.update(cx, |item, _| {
11802 item.set_has_deleted_file(true);
11803 });
11804
11805 // Emit UpdateTab event to trigger the close behavior
11806 cx.run_until_parked();
11807 item.update(cx, |_, cx| {
11808 cx.emit(ItemEvent::UpdateTab);
11809 });
11810
11811 // Allow the close operation to complete
11812 cx.run_until_parked();
11813
11814 // Verify the item was automatically closed
11815 pane.read_with(cx, |pane, _| {
11816 assert_eq!(
11817 pane.items().count(),
11818 0,
11819 "Item should be automatically closed when file is deleted"
11820 );
11821 });
11822 }
11823
11824 /// Tests that when `close_on_file_delete` is disabled (default), files remain
11825 /// open with a strikethrough when they are deleted from disk.
11826 #[gpui::test]
11827 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
11828 init_test(cx);
11829
11830 // Ensure close_on_disk_deletion is disabled (default)
11831 cx.update_global(|store: &mut SettingsStore, cx| {
11832 store.update_user_settings(cx, |settings| {
11833 settings.workspace.close_on_file_delete = Some(false);
11834 });
11835 });
11836
11837 let fs = FakeFs::new(cx.background_executor.clone());
11838 let project = Project::test(fs, [], cx).await;
11839 let (workspace, cx) =
11840 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11841 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11842
11843 // Create a test item that simulates a file
11844 let item = cx.new(|cx| {
11845 TestItem::new(cx)
11846 .with_label("test.txt")
11847 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11848 });
11849
11850 // Add item to workspace
11851 workspace.update_in(cx, |workspace, window, cx| {
11852 workspace.add_item(
11853 pane.clone(),
11854 Box::new(item.clone()),
11855 None,
11856 false,
11857 false,
11858 window,
11859 cx,
11860 );
11861 });
11862
11863 // Verify the item is in the pane
11864 pane.read_with(cx, |pane, _| {
11865 assert_eq!(pane.items().count(), 1);
11866 });
11867
11868 // Simulate file deletion
11869 item.update(cx, |item, _| {
11870 item.set_has_deleted_file(true);
11871 });
11872
11873 // Emit UpdateTab event
11874 cx.run_until_parked();
11875 item.update(cx, |_, cx| {
11876 cx.emit(ItemEvent::UpdateTab);
11877 });
11878
11879 // Allow any potential close operation to complete
11880 cx.run_until_parked();
11881
11882 // Verify the item remains open (with strikethrough)
11883 pane.read_with(cx, |pane, _| {
11884 assert_eq!(
11885 pane.items().count(),
11886 1,
11887 "Item should remain open when close_on_disk_deletion is disabled"
11888 );
11889 });
11890
11891 // Verify the item shows as deleted
11892 item.read_with(cx, |item, _| {
11893 assert!(
11894 item.has_deleted_file,
11895 "Item should be marked as having deleted file"
11896 );
11897 });
11898 }
11899
11900 /// Tests that dirty files are not automatically closed when deleted from disk,
11901 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
11902 /// unsaved changes without being prompted.
11903 #[gpui::test]
11904 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
11905 init_test(cx);
11906
11907 // Enable the close_on_file_delete setting
11908 cx.update_global(|store: &mut SettingsStore, cx| {
11909 store.update_user_settings(cx, |settings| {
11910 settings.workspace.close_on_file_delete = Some(true);
11911 });
11912 });
11913
11914 let fs = FakeFs::new(cx.background_executor.clone());
11915 let project = Project::test(fs, [], cx).await;
11916 let (workspace, cx) =
11917 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11918 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11919
11920 // Create a dirty test item
11921 let item = cx.new(|cx| {
11922 TestItem::new(cx)
11923 .with_dirty(true)
11924 .with_label("test.txt")
11925 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
11926 });
11927
11928 // Add item to workspace
11929 workspace.update_in(cx, |workspace, window, cx| {
11930 workspace.add_item(
11931 pane.clone(),
11932 Box::new(item.clone()),
11933 None,
11934 false,
11935 false,
11936 window,
11937 cx,
11938 );
11939 });
11940
11941 // Simulate file deletion
11942 item.update(cx, |item, _| {
11943 item.set_has_deleted_file(true);
11944 });
11945
11946 // Emit UpdateTab event to trigger the close behavior
11947 cx.run_until_parked();
11948 item.update(cx, |_, cx| {
11949 cx.emit(ItemEvent::UpdateTab);
11950 });
11951
11952 // Allow any potential close operation to complete
11953 cx.run_until_parked();
11954
11955 // Verify the item remains open (dirty files are not auto-closed)
11956 pane.read_with(cx, |pane, _| {
11957 assert_eq!(
11958 pane.items().count(),
11959 1,
11960 "Dirty items should not be automatically closed even when file is deleted"
11961 );
11962 });
11963
11964 // Verify the item is marked as deleted and still dirty
11965 item.read_with(cx, |item, _| {
11966 assert!(
11967 item.has_deleted_file,
11968 "Item should be marked as having deleted file"
11969 );
11970 assert!(item.is_dirty, "Item should still be dirty");
11971 });
11972 }
11973
11974 /// Tests that navigation history is cleaned up when files are auto-closed
11975 /// due to deletion from disk.
11976 #[gpui::test]
11977 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
11978 init_test(cx);
11979
11980 // Enable the close_on_file_delete setting
11981 cx.update_global(|store: &mut SettingsStore, cx| {
11982 store.update_user_settings(cx, |settings| {
11983 settings.workspace.close_on_file_delete = Some(true);
11984 });
11985 });
11986
11987 let fs = FakeFs::new(cx.background_executor.clone());
11988 let project = Project::test(fs, [], cx).await;
11989 let (workspace, cx) =
11990 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11991 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11992
11993 // Create test items
11994 let item1 = cx.new(|cx| {
11995 TestItem::new(cx)
11996 .with_label("test1.txt")
11997 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
11998 });
11999 let item1_id = item1.item_id();
12000
12001 let item2 = cx.new(|cx| {
12002 TestItem::new(cx)
12003 .with_label("test2.txt")
12004 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12005 });
12006
12007 // Add items to workspace
12008 workspace.update_in(cx, |workspace, window, cx| {
12009 workspace.add_item(
12010 pane.clone(),
12011 Box::new(item1.clone()),
12012 None,
12013 false,
12014 false,
12015 window,
12016 cx,
12017 );
12018 workspace.add_item(
12019 pane.clone(),
12020 Box::new(item2.clone()),
12021 None,
12022 false,
12023 false,
12024 window,
12025 cx,
12026 );
12027 });
12028
12029 // Activate item1 to ensure it gets navigation entries
12030 pane.update_in(cx, |pane, window, cx| {
12031 pane.activate_item(0, true, true, window, cx);
12032 });
12033
12034 // Switch to item2 and back to create navigation history
12035 pane.update_in(cx, |pane, window, cx| {
12036 pane.activate_item(1, true, true, window, cx);
12037 });
12038 cx.run_until_parked();
12039
12040 pane.update_in(cx, |pane, window, cx| {
12041 pane.activate_item(0, true, true, window, cx);
12042 });
12043 cx.run_until_parked();
12044
12045 // Simulate file deletion for item1
12046 item1.update(cx, |item, _| {
12047 item.set_has_deleted_file(true);
12048 });
12049
12050 // Emit UpdateTab event to trigger the close behavior
12051 item1.update(cx, |_, cx| {
12052 cx.emit(ItemEvent::UpdateTab);
12053 });
12054 cx.run_until_parked();
12055
12056 // Verify item1 was closed
12057 pane.read_with(cx, |pane, _| {
12058 assert_eq!(
12059 pane.items().count(),
12060 1,
12061 "Should have 1 item remaining after auto-close"
12062 );
12063 });
12064
12065 // Check navigation history after close
12066 let has_item = pane.read_with(cx, |pane, cx| {
12067 let mut has_item = false;
12068 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12069 if entry.item.id() == item1_id {
12070 has_item = true;
12071 }
12072 });
12073 has_item
12074 });
12075
12076 assert!(
12077 !has_item,
12078 "Navigation history should not contain closed item entries"
12079 );
12080 }
12081
12082 #[gpui::test]
12083 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12084 cx: &mut TestAppContext,
12085 ) {
12086 init_test(cx);
12087
12088 let fs = FakeFs::new(cx.background_executor.clone());
12089 let project = Project::test(fs, [], cx).await;
12090 let (workspace, cx) =
12091 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12092 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12093
12094 let dirty_regular_buffer = cx.new(|cx| {
12095 TestItem::new(cx)
12096 .with_dirty(true)
12097 .with_label("1.txt")
12098 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12099 });
12100 let dirty_regular_buffer_2 = cx.new(|cx| {
12101 TestItem::new(cx)
12102 .with_dirty(true)
12103 .with_label("2.txt")
12104 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12105 });
12106 let clear_regular_buffer = cx.new(|cx| {
12107 TestItem::new(cx)
12108 .with_label("3.txt")
12109 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12110 });
12111
12112 let dirty_multi_buffer = cx.new(|cx| {
12113 TestItem::new(cx)
12114 .with_dirty(true)
12115 .with_buffer_kind(ItemBufferKind::Multibuffer)
12116 .with_label("Fake Project Search")
12117 .with_project_items(&[
12118 dirty_regular_buffer.read(cx).project_items[0].clone(),
12119 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12120 clear_regular_buffer.read(cx).project_items[0].clone(),
12121 ])
12122 });
12123 workspace.update_in(cx, |workspace, window, cx| {
12124 workspace.add_item(
12125 pane.clone(),
12126 Box::new(dirty_regular_buffer.clone()),
12127 None,
12128 false,
12129 false,
12130 window,
12131 cx,
12132 );
12133 workspace.add_item(
12134 pane.clone(),
12135 Box::new(dirty_regular_buffer_2.clone()),
12136 None,
12137 false,
12138 false,
12139 window,
12140 cx,
12141 );
12142 workspace.add_item(
12143 pane.clone(),
12144 Box::new(dirty_multi_buffer.clone()),
12145 None,
12146 false,
12147 false,
12148 window,
12149 cx,
12150 );
12151 });
12152
12153 pane.update_in(cx, |pane, window, cx| {
12154 pane.activate_item(2, true, true, window, cx);
12155 assert_eq!(
12156 pane.active_item().unwrap().item_id(),
12157 dirty_multi_buffer.item_id(),
12158 "Should select the multi buffer in the pane"
12159 );
12160 });
12161 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12162 pane.close_active_item(
12163 &CloseActiveItem {
12164 save_intent: None,
12165 close_pinned: false,
12166 },
12167 window,
12168 cx,
12169 )
12170 });
12171 cx.background_executor.run_until_parked();
12172 assert!(
12173 !cx.has_pending_prompt(),
12174 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12175 );
12176 close_multi_buffer_task
12177 .await
12178 .expect("Closing multi buffer failed");
12179 pane.update(cx, |pane, cx| {
12180 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12181 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12182 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12183 assert_eq!(
12184 pane.items()
12185 .map(|item| item.item_id())
12186 .sorted()
12187 .collect::<Vec<_>>(),
12188 vec![
12189 dirty_regular_buffer.item_id(),
12190 dirty_regular_buffer_2.item_id(),
12191 ],
12192 "Should have no multi buffer left in the pane"
12193 );
12194 assert!(dirty_regular_buffer.read(cx).is_dirty);
12195 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12196 });
12197 }
12198
12199 #[gpui::test]
12200 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12201 init_test(cx);
12202 let fs = FakeFs::new(cx.executor());
12203 let project = Project::test(fs, [], cx).await;
12204 let (workspace, cx) =
12205 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12206
12207 // Add a new panel to the right dock, opening the dock and setting the
12208 // focus to the new panel.
12209 let panel = workspace.update_in(cx, |workspace, window, cx| {
12210 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12211 workspace.add_panel(panel.clone(), window, cx);
12212
12213 workspace
12214 .right_dock()
12215 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12216
12217 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12218
12219 panel
12220 });
12221
12222 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12223 // panel to the next valid position which, in this case, is the left
12224 // dock.
12225 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12226 workspace.update(cx, |workspace, cx| {
12227 assert!(workspace.left_dock().read(cx).is_open());
12228 assert_eq!(panel.read(cx).position, DockPosition::Left);
12229 });
12230
12231 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12232 // panel to the next valid position which, in this case, is the bottom
12233 // dock.
12234 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12235 workspace.update(cx, |workspace, cx| {
12236 assert!(workspace.bottom_dock().read(cx).is_open());
12237 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12238 });
12239
12240 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12241 // around moving the panel to its initial position, the right dock.
12242 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12243 workspace.update(cx, |workspace, cx| {
12244 assert!(workspace.right_dock().read(cx).is_open());
12245 assert_eq!(panel.read(cx).position, DockPosition::Right);
12246 });
12247
12248 // Remove focus from the panel, ensuring that, if the panel is not
12249 // focused, the `MoveFocusedPanelToNextPosition` action does not update
12250 // the panel's position, so the panel is still in the right dock.
12251 workspace.update_in(cx, |workspace, window, cx| {
12252 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12253 });
12254
12255 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12256 workspace.update(cx, |workspace, cx| {
12257 assert!(workspace.right_dock().read(cx).is_open());
12258 assert_eq!(panel.read(cx).position, DockPosition::Right);
12259 });
12260 }
12261
12262 #[gpui::test]
12263 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12264 init_test(cx);
12265
12266 let fs = FakeFs::new(cx.executor());
12267 let project = Project::test(fs, [], cx).await;
12268 let (workspace, cx) =
12269 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12270
12271 let item_1 = cx.new(|cx| {
12272 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12273 });
12274 workspace.update_in(cx, |workspace, window, cx| {
12275 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12276 workspace.move_item_to_pane_in_direction(
12277 &MoveItemToPaneInDirection {
12278 direction: SplitDirection::Right,
12279 focus: true,
12280 clone: false,
12281 },
12282 window,
12283 cx,
12284 );
12285 workspace.move_item_to_pane_at_index(
12286 &MoveItemToPane {
12287 destination: 3,
12288 focus: true,
12289 clone: false,
12290 },
12291 window,
12292 cx,
12293 );
12294
12295 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12296 assert_eq!(
12297 pane_items_paths(&workspace.active_pane, cx),
12298 vec!["first.txt".to_string()],
12299 "Single item was not moved anywhere"
12300 );
12301 });
12302
12303 let item_2 = cx.new(|cx| {
12304 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12305 });
12306 workspace.update_in(cx, |workspace, window, cx| {
12307 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12308 assert_eq!(
12309 pane_items_paths(&workspace.panes[0], cx),
12310 vec!["first.txt".to_string(), "second.txt".to_string()],
12311 );
12312 workspace.move_item_to_pane_in_direction(
12313 &MoveItemToPaneInDirection {
12314 direction: SplitDirection::Right,
12315 focus: true,
12316 clone: false,
12317 },
12318 window,
12319 cx,
12320 );
12321
12322 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12323 assert_eq!(
12324 pane_items_paths(&workspace.panes[0], cx),
12325 vec!["first.txt".to_string()],
12326 "After moving, one item should be left in the original pane"
12327 );
12328 assert_eq!(
12329 pane_items_paths(&workspace.panes[1], cx),
12330 vec!["second.txt".to_string()],
12331 "New item should have been moved to the new pane"
12332 );
12333 });
12334
12335 let item_3 = cx.new(|cx| {
12336 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12337 });
12338 workspace.update_in(cx, |workspace, window, cx| {
12339 let original_pane = workspace.panes[0].clone();
12340 workspace.set_active_pane(&original_pane, window, cx);
12341 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12342 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12343 assert_eq!(
12344 pane_items_paths(&workspace.active_pane, cx),
12345 vec!["first.txt".to_string(), "third.txt".to_string()],
12346 "New pane should be ready to move one item out"
12347 );
12348
12349 workspace.move_item_to_pane_at_index(
12350 &MoveItemToPane {
12351 destination: 3,
12352 focus: true,
12353 clone: false,
12354 },
12355 window,
12356 cx,
12357 );
12358 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12359 assert_eq!(
12360 pane_items_paths(&workspace.active_pane, cx),
12361 vec!["first.txt".to_string()],
12362 "After moving, one item should be left in the original pane"
12363 );
12364 assert_eq!(
12365 pane_items_paths(&workspace.panes[1], cx),
12366 vec!["second.txt".to_string()],
12367 "Previously created pane should be unchanged"
12368 );
12369 assert_eq!(
12370 pane_items_paths(&workspace.panes[2], cx),
12371 vec!["third.txt".to_string()],
12372 "New item should have been moved to the new pane"
12373 );
12374 });
12375 }
12376
12377 #[gpui::test]
12378 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
12379 init_test(cx);
12380
12381 let fs = FakeFs::new(cx.executor());
12382 let project = Project::test(fs, [], cx).await;
12383 let (workspace, cx) =
12384 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12385
12386 let item_1 = cx.new(|cx| {
12387 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12388 });
12389 workspace.update_in(cx, |workspace, window, cx| {
12390 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12391 workspace.move_item_to_pane_in_direction(
12392 &MoveItemToPaneInDirection {
12393 direction: SplitDirection::Right,
12394 focus: true,
12395 clone: true,
12396 },
12397 window,
12398 cx,
12399 );
12400 });
12401 cx.run_until_parked();
12402 workspace.update_in(cx, |workspace, window, cx| {
12403 workspace.move_item_to_pane_at_index(
12404 &MoveItemToPane {
12405 destination: 3,
12406 focus: true,
12407 clone: true,
12408 },
12409 window,
12410 cx,
12411 );
12412 });
12413 cx.run_until_parked();
12414
12415 workspace.update(cx, |workspace, cx| {
12416 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
12417 for pane in workspace.panes() {
12418 assert_eq!(
12419 pane_items_paths(pane, cx),
12420 vec!["first.txt".to_string()],
12421 "Single item exists in all panes"
12422 );
12423 }
12424 });
12425
12426 // verify that the active pane has been updated after waiting for the
12427 // pane focus event to fire and resolve
12428 workspace.read_with(cx, |workspace, _app| {
12429 assert_eq!(
12430 workspace.active_pane(),
12431 &workspace.panes[2],
12432 "The third pane should be the active one: {:?}",
12433 workspace.panes
12434 );
12435 })
12436 }
12437
12438 #[gpui::test]
12439 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
12440 init_test(cx);
12441
12442 let fs = FakeFs::new(cx.executor());
12443 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
12444
12445 let project = Project::test(fs, ["root".as_ref()], cx).await;
12446 let (workspace, cx) =
12447 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12448
12449 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12450 // Add item to pane A with project path
12451 let item_a = cx.new(|cx| {
12452 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12453 });
12454 workspace.update_in(cx, |workspace, window, cx| {
12455 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
12456 });
12457
12458 // Split to create pane B
12459 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
12460 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
12461 });
12462
12463 // Add item with SAME project path to pane B, and pin it
12464 let item_b = cx.new(|cx| {
12465 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12466 });
12467 pane_b.update_in(cx, |pane, window, cx| {
12468 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
12469 pane.set_pinned_count(1);
12470 });
12471
12472 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
12473 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
12474
12475 // close_pinned: false should only close the unpinned copy
12476 workspace.update_in(cx, |workspace, window, cx| {
12477 workspace.close_item_in_all_panes(
12478 &CloseItemInAllPanes {
12479 save_intent: Some(SaveIntent::Close),
12480 close_pinned: false,
12481 },
12482 window,
12483 cx,
12484 )
12485 });
12486 cx.executor().run_until_parked();
12487
12488 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
12489 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12490 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
12491 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
12492
12493 // Split again, seeing as closing the previous item also closed its
12494 // pane, so only pane remains, which does not allow us to properly test
12495 // that both items close when `close_pinned: true`.
12496 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
12497 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
12498 });
12499
12500 // Add an item with the same project path to pane C so that
12501 // close_item_in_all_panes can determine what to close across all panes
12502 // (it reads the active item from the active pane, and split_pane
12503 // creates an empty pane).
12504 let item_c = cx.new(|cx| {
12505 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12506 });
12507 pane_c.update_in(cx, |pane, window, cx| {
12508 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
12509 });
12510
12511 // close_pinned: true should close the pinned copy too
12512 workspace.update_in(cx, |workspace, window, cx| {
12513 let panes_count = workspace.panes().len();
12514 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
12515
12516 workspace.close_item_in_all_panes(
12517 &CloseItemInAllPanes {
12518 save_intent: Some(SaveIntent::Close),
12519 close_pinned: true,
12520 },
12521 window,
12522 cx,
12523 )
12524 });
12525 cx.executor().run_until_parked();
12526
12527 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
12528 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
12529 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
12530 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
12531 }
12532
12533 mod register_project_item_tests {
12534
12535 use super::*;
12536
12537 // View
12538 struct TestPngItemView {
12539 focus_handle: FocusHandle,
12540 }
12541 // Model
12542 struct TestPngItem {}
12543
12544 impl project::ProjectItem for TestPngItem {
12545 fn try_open(
12546 _project: &Entity<Project>,
12547 path: &ProjectPath,
12548 cx: &mut App,
12549 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12550 if path.path.extension().unwrap() == "png" {
12551 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
12552 } else {
12553 None
12554 }
12555 }
12556
12557 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12558 None
12559 }
12560
12561 fn project_path(&self, _: &App) -> Option<ProjectPath> {
12562 None
12563 }
12564
12565 fn is_dirty(&self) -> bool {
12566 false
12567 }
12568 }
12569
12570 impl Item for TestPngItemView {
12571 type Event = ();
12572 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12573 "".into()
12574 }
12575 }
12576 impl EventEmitter<()> for TestPngItemView {}
12577 impl Focusable for TestPngItemView {
12578 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12579 self.focus_handle.clone()
12580 }
12581 }
12582
12583 impl Render for TestPngItemView {
12584 fn render(
12585 &mut self,
12586 _window: &mut Window,
12587 _cx: &mut Context<Self>,
12588 ) -> impl IntoElement {
12589 Empty
12590 }
12591 }
12592
12593 impl ProjectItem for TestPngItemView {
12594 type Item = TestPngItem;
12595
12596 fn for_project_item(
12597 _project: Entity<Project>,
12598 _pane: Option<&Pane>,
12599 _item: Entity<Self::Item>,
12600 _: &mut Window,
12601 cx: &mut Context<Self>,
12602 ) -> Self
12603 where
12604 Self: Sized,
12605 {
12606 Self {
12607 focus_handle: cx.focus_handle(),
12608 }
12609 }
12610 }
12611
12612 // View
12613 struct TestIpynbItemView {
12614 focus_handle: FocusHandle,
12615 }
12616 // Model
12617 struct TestIpynbItem {}
12618
12619 impl project::ProjectItem for TestIpynbItem {
12620 fn try_open(
12621 _project: &Entity<Project>,
12622 path: &ProjectPath,
12623 cx: &mut App,
12624 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
12625 if path.path.extension().unwrap() == "ipynb" {
12626 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
12627 } else {
12628 None
12629 }
12630 }
12631
12632 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
12633 None
12634 }
12635
12636 fn project_path(&self, _: &App) -> Option<ProjectPath> {
12637 None
12638 }
12639
12640 fn is_dirty(&self) -> bool {
12641 false
12642 }
12643 }
12644
12645 impl Item for TestIpynbItemView {
12646 type Event = ();
12647 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12648 "".into()
12649 }
12650 }
12651 impl EventEmitter<()> for TestIpynbItemView {}
12652 impl Focusable for TestIpynbItemView {
12653 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12654 self.focus_handle.clone()
12655 }
12656 }
12657
12658 impl Render for TestIpynbItemView {
12659 fn render(
12660 &mut self,
12661 _window: &mut Window,
12662 _cx: &mut Context<Self>,
12663 ) -> impl IntoElement {
12664 Empty
12665 }
12666 }
12667
12668 impl ProjectItem for TestIpynbItemView {
12669 type Item = TestIpynbItem;
12670
12671 fn for_project_item(
12672 _project: Entity<Project>,
12673 _pane: Option<&Pane>,
12674 _item: Entity<Self::Item>,
12675 _: &mut Window,
12676 cx: &mut Context<Self>,
12677 ) -> Self
12678 where
12679 Self: Sized,
12680 {
12681 Self {
12682 focus_handle: cx.focus_handle(),
12683 }
12684 }
12685 }
12686
12687 struct TestAlternatePngItemView {
12688 focus_handle: FocusHandle,
12689 }
12690
12691 impl Item for TestAlternatePngItemView {
12692 type Event = ();
12693 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
12694 "".into()
12695 }
12696 }
12697
12698 impl EventEmitter<()> for TestAlternatePngItemView {}
12699 impl Focusable for TestAlternatePngItemView {
12700 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12701 self.focus_handle.clone()
12702 }
12703 }
12704
12705 impl Render for TestAlternatePngItemView {
12706 fn render(
12707 &mut self,
12708 _window: &mut Window,
12709 _cx: &mut Context<Self>,
12710 ) -> impl IntoElement {
12711 Empty
12712 }
12713 }
12714
12715 impl ProjectItem for TestAlternatePngItemView {
12716 type Item = TestPngItem;
12717
12718 fn for_project_item(
12719 _project: Entity<Project>,
12720 _pane: Option<&Pane>,
12721 _item: Entity<Self::Item>,
12722 _: &mut Window,
12723 cx: &mut Context<Self>,
12724 ) -> Self
12725 where
12726 Self: Sized,
12727 {
12728 Self {
12729 focus_handle: cx.focus_handle(),
12730 }
12731 }
12732 }
12733
12734 #[gpui::test]
12735 async fn test_register_project_item(cx: &mut TestAppContext) {
12736 init_test(cx);
12737
12738 cx.update(|cx| {
12739 register_project_item::<TestPngItemView>(cx);
12740 register_project_item::<TestIpynbItemView>(cx);
12741 });
12742
12743 let fs = FakeFs::new(cx.executor());
12744 fs.insert_tree(
12745 "/root1",
12746 json!({
12747 "one.png": "BINARYDATAHERE",
12748 "two.ipynb": "{ totally a notebook }",
12749 "three.txt": "editing text, sure why not?"
12750 }),
12751 )
12752 .await;
12753
12754 let project = Project::test(fs, ["root1".as_ref()], cx).await;
12755 let (workspace, cx) =
12756 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12757
12758 let worktree_id = project.update(cx, |project, cx| {
12759 project.worktrees(cx).next().unwrap().read(cx).id()
12760 });
12761
12762 let handle = workspace
12763 .update_in(cx, |workspace, window, cx| {
12764 let project_path = (worktree_id, rel_path("one.png"));
12765 workspace.open_path(project_path, None, true, window, cx)
12766 })
12767 .await
12768 .unwrap();
12769
12770 // Now we can check if the handle we got back errored or not
12771 assert_eq!(
12772 handle.to_any_view().entity_type(),
12773 TypeId::of::<TestPngItemView>()
12774 );
12775
12776 let handle = workspace
12777 .update_in(cx, |workspace, window, cx| {
12778 let project_path = (worktree_id, rel_path("two.ipynb"));
12779 workspace.open_path(project_path, None, true, window, cx)
12780 })
12781 .await
12782 .unwrap();
12783
12784 assert_eq!(
12785 handle.to_any_view().entity_type(),
12786 TypeId::of::<TestIpynbItemView>()
12787 );
12788
12789 let handle = workspace
12790 .update_in(cx, |workspace, window, cx| {
12791 let project_path = (worktree_id, rel_path("three.txt"));
12792 workspace.open_path(project_path, None, true, window, cx)
12793 })
12794 .await;
12795 assert!(handle.is_err());
12796 }
12797
12798 #[gpui::test]
12799 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
12800 init_test(cx);
12801
12802 cx.update(|cx| {
12803 register_project_item::<TestPngItemView>(cx);
12804 register_project_item::<TestAlternatePngItemView>(cx);
12805 });
12806
12807 let fs = FakeFs::new(cx.executor());
12808 fs.insert_tree(
12809 "/root1",
12810 json!({
12811 "one.png": "BINARYDATAHERE",
12812 "two.ipynb": "{ totally a notebook }",
12813 "three.txt": "editing text, sure why not?"
12814 }),
12815 )
12816 .await;
12817 let project = Project::test(fs, ["root1".as_ref()], cx).await;
12818 let (workspace, cx) =
12819 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12820 let worktree_id = project.update(cx, |project, cx| {
12821 project.worktrees(cx).next().unwrap().read(cx).id()
12822 });
12823
12824 let handle = workspace
12825 .update_in(cx, |workspace, window, cx| {
12826 let project_path = (worktree_id, rel_path("one.png"));
12827 workspace.open_path(project_path, None, true, window, cx)
12828 })
12829 .await
12830 .unwrap();
12831
12832 // This _must_ be the second item registered
12833 assert_eq!(
12834 handle.to_any_view().entity_type(),
12835 TypeId::of::<TestAlternatePngItemView>()
12836 );
12837
12838 let handle = workspace
12839 .update_in(cx, |workspace, window, cx| {
12840 let project_path = (worktree_id, rel_path("three.txt"));
12841 workspace.open_path(project_path, None, true, window, cx)
12842 })
12843 .await;
12844 assert!(handle.is_err());
12845 }
12846 }
12847
12848 #[gpui::test]
12849 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
12850 init_test(cx);
12851
12852 let fs = FakeFs::new(cx.executor());
12853 let project = Project::test(fs, [], cx).await;
12854 let (workspace, _cx) =
12855 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12856
12857 // Test with status bar shown (default)
12858 workspace.read_with(cx, |workspace, cx| {
12859 let visible = workspace.status_bar_visible(cx);
12860 assert!(visible, "Status bar should be visible by default");
12861 });
12862
12863 // Test with status bar hidden
12864 cx.update_global(|store: &mut SettingsStore, cx| {
12865 store.update_user_settings(cx, |settings| {
12866 settings.status_bar.get_or_insert_default().show = Some(false);
12867 });
12868 });
12869
12870 workspace.read_with(cx, |workspace, cx| {
12871 let visible = workspace.status_bar_visible(cx);
12872 assert!(!visible, "Status bar should be hidden when show is false");
12873 });
12874
12875 // Test with status bar shown explicitly
12876 cx.update_global(|store: &mut SettingsStore, cx| {
12877 store.update_user_settings(cx, |settings| {
12878 settings.status_bar.get_or_insert_default().show = Some(true);
12879 });
12880 });
12881
12882 workspace.read_with(cx, |workspace, cx| {
12883 let visible = workspace.status_bar_visible(cx);
12884 assert!(visible, "Status bar should be visible when show is true");
12885 });
12886 }
12887
12888 #[gpui::test]
12889 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
12890 init_test(cx);
12891
12892 let fs = FakeFs::new(cx.executor());
12893 let project = Project::test(fs, [], cx).await;
12894 let (workspace, cx) =
12895 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12896 let panel = workspace.update_in(cx, |workspace, window, cx| {
12897 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12898 workspace.add_panel(panel.clone(), window, cx);
12899
12900 workspace
12901 .right_dock()
12902 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12903
12904 panel
12905 });
12906
12907 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12908 let item_a = cx.new(TestItem::new);
12909 let item_b = cx.new(TestItem::new);
12910 let item_a_id = item_a.entity_id();
12911 let item_b_id = item_b.entity_id();
12912
12913 pane.update_in(cx, |pane, window, cx| {
12914 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
12915 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
12916 });
12917
12918 pane.read_with(cx, |pane, _| {
12919 assert_eq!(pane.items_len(), 2);
12920 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
12921 });
12922
12923 workspace.update_in(cx, |workspace, window, cx| {
12924 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12925 });
12926
12927 workspace.update_in(cx, |_, window, cx| {
12928 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12929 });
12930
12931 // Assert that the `pane::CloseActiveItem` action is handled at the
12932 // workspace level when one of the dock panels is focused and, in that
12933 // case, the center pane's active item is closed but the focus is not
12934 // moved.
12935 cx.dispatch_action(pane::CloseActiveItem::default());
12936 cx.run_until_parked();
12937
12938 pane.read_with(cx, |pane, _| {
12939 assert_eq!(pane.items_len(), 1);
12940 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
12941 });
12942
12943 workspace.update_in(cx, |workspace, window, cx| {
12944 assert!(workspace.right_dock().read(cx).is_open());
12945 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12946 });
12947 }
12948
12949 #[gpui::test]
12950 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
12951 init_test(cx);
12952 let fs = FakeFs::new(cx.executor());
12953
12954 let project_a = Project::test(fs.clone(), [], cx).await;
12955 let project_b = Project::test(fs, [], cx).await;
12956
12957 let multi_workspace_handle =
12958 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
12959
12960 let workspace_a = multi_workspace_handle
12961 .read_with(cx, |mw, _| mw.workspace().clone())
12962 .unwrap();
12963
12964 let _workspace_b = multi_workspace_handle
12965 .update(cx, |mw, window, cx| {
12966 mw.test_add_workspace(project_b, window, cx)
12967 })
12968 .unwrap();
12969
12970 // Switch to workspace A
12971 multi_workspace_handle
12972 .update(cx, |mw, window, cx| {
12973 mw.activate_index(0, window, cx);
12974 })
12975 .unwrap();
12976
12977 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
12978
12979 // Add a panel to workspace A's right dock and open the dock
12980 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
12981 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12982 workspace.add_panel(panel.clone(), window, cx);
12983 workspace
12984 .right_dock()
12985 .update(cx, |dock, cx| dock.set_open(true, window, cx));
12986 panel
12987 });
12988
12989 // Focus the panel through the workspace (matching existing test pattern)
12990 workspace_a.update_in(cx, |workspace, window, cx| {
12991 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12992 });
12993
12994 // Zoom the panel
12995 panel.update_in(cx, |panel, window, cx| {
12996 panel.set_zoomed(true, window, cx);
12997 });
12998
12999 // Verify the panel is zoomed and the dock is open
13000 workspace_a.update_in(cx, |workspace, window, cx| {
13001 assert!(
13002 workspace.right_dock().read(cx).is_open(),
13003 "dock should be open before switch"
13004 );
13005 assert!(
13006 panel.is_zoomed(window, cx),
13007 "panel should be zoomed before switch"
13008 );
13009 assert!(
13010 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13011 "panel should be focused before switch"
13012 );
13013 });
13014
13015 // Switch to workspace B
13016 multi_workspace_handle
13017 .update(cx, |mw, window, cx| {
13018 mw.activate_index(1, window, cx);
13019 })
13020 .unwrap();
13021 cx.run_until_parked();
13022
13023 // Switch back to workspace A
13024 multi_workspace_handle
13025 .update(cx, |mw, window, cx| {
13026 mw.activate_index(0, window, cx);
13027 })
13028 .unwrap();
13029 cx.run_until_parked();
13030
13031 // Verify the panel is still zoomed and the dock is still open
13032 workspace_a.update_in(cx, |workspace, window, cx| {
13033 assert!(
13034 workspace.right_dock().read(cx).is_open(),
13035 "dock should still be open after switching back"
13036 );
13037 assert!(
13038 panel.is_zoomed(window, cx),
13039 "panel should still be zoomed after switching back"
13040 );
13041 });
13042 }
13043
13044 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13045 pane.read(cx)
13046 .items()
13047 .flat_map(|item| {
13048 item.project_paths(cx)
13049 .into_iter()
13050 .map(|path| path.path.display(PathStyle::local()).into_owned())
13051 })
13052 .collect()
13053 }
13054
13055 pub fn init_test(cx: &mut TestAppContext) {
13056 cx.update(|cx| {
13057 let settings_store = SettingsStore::test(cx);
13058 cx.set_global(settings_store);
13059 theme::init(theme::LoadThemes::JustBase, cx);
13060 });
13061 }
13062
13063 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13064 let item = TestProjectItem::new(id, path, cx);
13065 item.update(cx, |item, _| {
13066 item.is_dirty = true;
13067 });
13068 item
13069 }
13070
13071 #[gpui::test]
13072 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13073 cx: &mut gpui::TestAppContext,
13074 ) {
13075 init_test(cx);
13076 let fs = FakeFs::new(cx.executor());
13077
13078 let project = Project::test(fs, [], cx).await;
13079 let (workspace, cx) =
13080 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13081
13082 let panel = workspace.update_in(cx, |workspace, window, cx| {
13083 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13084 workspace.add_panel(panel.clone(), window, cx);
13085 workspace
13086 .right_dock()
13087 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13088 panel
13089 });
13090
13091 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13092 pane.update_in(cx, |pane, window, cx| {
13093 let item = cx.new(TestItem::new);
13094 pane.add_item(Box::new(item), true, true, None, window, cx);
13095 });
13096
13097 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13098 // mirrors the real-world flow and avoids side effects from directly
13099 // focusing the panel while the center pane is active.
13100 workspace.update_in(cx, |workspace, window, cx| {
13101 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13102 });
13103
13104 panel.update_in(cx, |panel, window, cx| {
13105 panel.set_zoomed(true, window, cx);
13106 });
13107
13108 workspace.update_in(cx, |workspace, window, cx| {
13109 assert!(workspace.right_dock().read(cx).is_open());
13110 assert!(panel.is_zoomed(window, cx));
13111 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13112 });
13113
13114 // Simulate a spurious pane::Event::Focus on the center pane while the
13115 // panel still has focus. This mirrors what happens during macOS window
13116 // activation: the center pane fires a focus event even though actual
13117 // focus remains on the dock panel.
13118 pane.update_in(cx, |_, _, cx| {
13119 cx.emit(pane::Event::Focus);
13120 });
13121
13122 // The dock must remain open because the panel had focus at the time the
13123 // event was processed. Before the fix, dock_to_preserve was None for
13124 // panels that don't implement pane(), causing the dock to close.
13125 workspace.update_in(cx, |workspace, window, cx| {
13126 assert!(
13127 workspace.right_dock().read(cx).is_open(),
13128 "Dock should stay open when its zoomed panel (without pane()) still has focus"
13129 );
13130 assert!(panel.is_zoomed(window, cx));
13131 });
13132 }
13133}